Sei sulla pagina 1di 142

NS Simulator for beginners

Le ture notes, Automn 2002


Univ. de Los Andes, Merida, Venezuela
Eitan Altman and Tania Jimenez
July 23, 2003

Contents
1 Introdu tion

1.1 Ba kground on the ns simulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


1.2 T l and Ot l programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2 ns Simulator Preliminaries

2.1 Initialization and termination . . . . . . .


2.2 De nition of a network of links and nodes
2.3 Agents and appli ations . . . . . . . . . .
2.3.1 FTP over TCP . . . . . . . . . . .
2.3.2 CBR over UDP . . . . . . . . . . .
2.3.3 UDP with other tra sour es . .
2.4 S heduling events . . . . . . . . . . . . . .
2.5 Visualisation: using nam . . . . . . . . . .
2.6 Tra ing . . . . . . . . . . . . . . . . . . .
2.6.1 Tra ing obje ts . . . . . . . . . . .
2.6.2 Stru ture of tra e les . . . . . . .
2.6.3 Tra ing a subset of events . . . . .
2.7 Random variables . . . . . . . . . . . . . .
2.7.1 Seeds and generators . . . . . . . .
2.7.2 Creating Random Variables . . . .

3 How to work with tra e les


3.1
3.2
3.3
3.4
3.5
3.6

Pro essing data les with awk . . . . . . .


Using grep . . . . . . . . . . . . . . . . .
Pro essing data les with perl . . . . . .
Plotting with gnuplot . . . . . . . . . . .
Plotting with xgraph . . . . . . . . . . . .
Extra ting information within a t l s ript

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

4.1 Des ription of TCP . . . . . . . . . . . . . . . . . .


4.1.1 Obje tives of TCP and window ow ontrol
4.1.2 A knowledgements . . . . . . . . . . . . . .
4.1.3 Dynami ongestion window . . . . . . . . .
4.1.4 Losses and a dynami threshold Wth . . . .
4.1.5 Initiating a onne tion . . . . . . . . . . . .
4.2 Tra ing and analysis of Example ex1.t l . . . . . .
4.3 TCP over Noisy links and queue monitoring . . . .
4.4 Creating many onne tions with random features .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.

4 Des ription and simulation of TCP/IP

.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

8
8

13

13
14
15
16
18
18
19
22
23
23
23
26
26
26
26

29

29
30
31
33
34
34

35

35
35
35
36
37
37
37
38
43

CONTENTS

4.5 Short TCP onne tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


4.6 Advan ed monitoring tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7 Exer ises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5 Routing and network dynami s

5.1 Uni ast routing . . . . . . . . . . . . . . . . .


5.2 Network dynami s . . . . . . . . . . . . . . .
5.3 Multi ast proto ols . . . . . . . . . . . . . . .
5.3.1 The Dense mode . . . . . . . . . . . .
5.3.2 Routinng based on a RV point . . . .
5.4 Simulating multi ast routing . . . . . . . . .
5.4.1 DM mode . . . . . . . . . . . . . . . .
5.4.2 Routing with a entralized RV point .
5.5 Observations on the simulation of pimdm.t l
5.6 Exer ises . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

6 RED: Random Early Dis ard

6.1 Des ription of RED . . . . . . . . . . . . . . . . . . . . . .


6.2 Setting RED parameters in ns . . . . . . . . . . . . . . . . .
6.3 Simulation examples . . . . . . . . . . . . . . . . . . . . . .
6.3.1 Drop tail bu er . . . . . . . . . . . . . . . . . . . . .
6.3.2 RED bu er with automati parameter on guration
6.3.3 RED bu er with other parmaters . . . . . . . . . . .
6.4 Monitoring ows . . . . . . . . . . . . . . . . . . . . . . . .
6.5 Exer ises . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7 Di erentiated Servi es

7.1 Des ription of assured forwarding Di serv . . . . . . .


7.2 MRED routers . . . . . . . . . . . . . . . . . . . . . .
7.2.1 General des ription . . . . . . . . . . . . . . . .
7.2.2 Con guration of MRED in ns . . . . . . . . . .
7.2.3 TCL querying . . . . . . . . . . . . . . . . . . .
7.3 De ning poli ies . . . . . . . . . . . . . . . . . . . . .
7.3.1 Des ription . . . . . . . . . . . . . . . . . . . .
7.3.2 Con guration . . . . . . . . . . . . . . . . . . .
7.3.3 TCL querying . . . . . . . . . . . . . . . . . . .
7.4 Simulation of di serv: prote tion of vulnerable pa kets
7.4.1 The simulated s enario . . . . . . . . . . . . . .
7.5 Simulation results . . . . . . . . . . . . . . . . . . . .
7.6 Dis ussions and on lusions . . . . . . . . . . . . . . .
7.7 Exer ises . . . . . . . . . . . . . . . . . . . . . . . . .

8 Lo al area networks

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

46
52
58

59

59
62
62
63
63
64
67
67
70
70

71

71
72
73
73
78
83
83
88

89

. 89
. 90
. 90
. 90
. 91
. 91
. 91
. 93
. 93
. 93
. 93
. 101
. 102
. 102

103

8.1 Ba kground . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103


8.2 Simulating LANs with ns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

CONTENTS

9 Mobile networks

9.1 The routing algorithms . . . . . . . . . . . . . . . . . . .


9.1.1 Destination Sequen ed Distan e Ve tor - DSDV .
9.1.2 Ad-ho On Demand Distan e Ve tor - AODV . .
9.1.3 Dynami Sour e Routing - DSR . . . . . . . . .
9.1.4 Temporally Ordered Routing Algorithm - TORA
9.2 Simulating mobile networks . . . . . . . . . . . . . . . .
9.2.1 Simulation s enario . . . . . . . . . . . . . . . . .
9.2.2 Writing the t l s ript . . . . . . . . . . . . . . . .
9.3 Tra e format . . . . . . . . . . . . . . . . . . . . . . . .
9.4 Analysis of simulation results . . . . . . . . . . . . . . .
9.5 Comparison with other ad-ho routing . . . . . . . . . .
9.5.1 TCP over DSR . . . . . . . . . . . . . . . . . . .
9.5.2 TCP over AODV . . . . . . . . . . . . . . . . . .
9.5.3 TCP over TORA . . . . . . . . . . . . . . . . . .
9.5.4 Some omments . . . . . . . . . . . . . . . . . .
9.6 The intera tion of TCP with the MAC proto ol . . . . .
9.6.1 Ba kground . . . . . . . . . . . . . . . . . . . . .
9.6.2 The simulated s enario . . . . . . . . . . . . . . .
9.6.3 Simulation results . . . . . . . . . . . . . . . . .
9.6.4 Modi ation of ns for the ase d > 2 . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

107

107
108
108
109
109
110
110
110
112
116
116
116
118
118
119
119
119
120
123
125

10 Classi al queueing models

127

11 Appendix I: Random variables: ba kground

133

12 Appendix II: Con den e intervals

135

10.1 Simulating an M/M/1, M/D/1 and D/M/1 queues . . . . . . . . . . . . . . . . . . 127


10.2 Finite queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

CONTENTS

Chapter 1

Introdu tion
ns simluator overs a very large number of appli ations, of proto ols, of network types, of network
elements and of tra models. We all these "simulated obje ts". The goal of our notes is twofold:
on one hand to learn how to use ns simulator, and on the other hand, to be ome a quainted with
and to understand the operations of some of the simulated obje ts using ns simulations. Our notes
prvide therefore not only some basis and des ription of ns simulator (espe ially through a large
number of t l s ripts), but also a des ription of the simulated obje ts. Finally, we fo us on the
analysis of the behavior of the simulated obje ts using ns simulations.
The notes are intended to help students, engineers or resear hers who need not have mu h
ba kground in programming or who want to learn through simple examples how to analyse some
simulated obje t using ns. In that purpose, we provide a large number of t l s ripts that an be
used by the reader so as to start programming immediately. For readers who are interested to learn
from examples, we should mention that a very large number of examples is already available in
the software pa kage of the ns simulator1. Other tutorials ontaining many examples are available
ele troni ally: Mar Greis's tutorial2 and the tutorial by Jae Chung and Mark Claypool3.
For a mu h deaper study of the ns simulator one should refer to the ns manual whi h is
maintained up-to-date at http://www.isi.edu/nsnam/ns/.
We present in this book many simple (but hopefuly useful) s enari for simulations. Simulations
may di er from ea h other in many aspe ts: the appli ations, topologies, parameters of network
obje ts (links nodes) and prot oles used et . We do not aim at being exhaustive; instead we
present what we onsider to be "typi al" examples. If one needs a more exhaustive des ription
of ns, one may nd it very useful to onsult the ns manual4. An alternative simple way to know
about other possibilities for hoosing network elements, network proto oles or their parameters,
appli ation parameters et is to look dire tly at the library les that de ne them5 . For example, the
de nitions of mobile nodes would be nd in the le ns-mobilenode.t l, those des ribing queueing
dis iplines and parameters in the le ns-queue.t l, et . Defaults parameters an be found at the
le ns-default.t l. Note: to know whi h default obje t is related to whi h ommand, one may need
to he k the le ns-lib.t l as we shall see in an example in Se tion 2.2.
1 it typi ally appears in the dire tory ns-2/t l/ex, where dire tory "ns-2" ould have other longer names that
depend on the ns release, e.g. "ns-2.1b8a"
2 http://www.isi.edu/nsnam/ns/tutorial/index.html
3 http://nile.wpi.edu/NS/
4 see http://www.isi.edu/nsnam/ns/ns-do umentation.html
5 ns-allinone-2.1b8a/ns-2.1b8a/t l/lib

CHAPTER 1.

INTRODUCTION

1.1 Ba kground on the ns simulator


NS simulator is based on two languages: an obje t oriented simulator, written in C++, and a
OT l (an obje t oriented extension of T l) interpreter, used to exe ute user's ommand s ripts.
NS has a ri h library of network and proto ol obje ts. There are two lass hierar hies: the
ompiled C++ hierar hy and the interpreted OT l one, with one to one orrespondan e between
them.
The ompiled C++ hierar hy allows us to a hieve e ien y in the simulation and faster exe ution times. This is in parti ular useful for the detailed de nition and operation of proto ols.
This allows one to redu e pa ket and event pro essing time.
Then in the OT l s ript provided by the user, we an de ne a parti ular network topology, the
spe i proto ols and appli ations that we wish to simulate (whose behavior is already de ned in
the ompiled hierar hy) and the form of the output that we wish to obtain from the simulator.
The OT l an make use of the obje ts ompiled in C++ through an OT l linkage (done using
TCt l) that reates a mat hing of OT l obje t for ea h of the C++.
NS is a dis rete event simulator, where timing of events are determined by a s heduler. An
event is a pa ket's ID that is unique for a pa ket with s heduled time and the pointer to an obje t
that handles the event. The s heduler keeps tra k of simulation time and res all the events in the
event queue s heduled for the urrent time by invoking appropriate network omponents, whi h
usually are the ones who issued the events, and let them do the appropriate a tion asso iated with
pa ket pointed by the event.

1.2 T l and Ot l programming


Here are some basi s of t l and Ot l programming.

Assigning a value to a variable is done through the "set" ommand; for example: "set b
0" assigns to b the value of 0.

When we wish to use the value assigned to a variable, we should use a $ sign before the
variable. For example, if we want to assign to variable x the value that variable a has, then
we should write: "set x $a".

A mathemati al operation is done using the expression ommand. For example, if we wish
to assign to a variable x the sum of values of the values of some variables a and b, we
should write "set x [expr $a + $b". Note: assume that we want to print the result of
the division 1/60. If we write
puts"[expr1=60"
then the result will be 0! To have the orre t result, we need to indi ate that we do not
work with integers, and should thus type

puts"[expr1:0=60:0"




The sign # starts a ommented line that is not part of the program.
To reate a le, one has to give it a name, say " lename", and to assign a pointer to it that
will be used within the t l program in order to relate to it, say " le1". This is done with
the ommand
set file1 [open filename w

1.2.

TCL AND OTCL PROGRAMMING

puts is used for printing an output. Note: ea h time the "puts" ommand is used, a new
line is started. To avoid new line, one has to add -nonewline after the "puts" ommand.
If we want to print into a le (say the one we de ned above) we type puts $file "text"1.
Tabulating is done by inserting \t. For example, if a variable, say x, has the value 2 and we

type

puts $file1 "x \t $x"

then this will print a line into the le whose name is " lename" with two elements: "x" and
"2" separated by a large spa e.

Exe ution of a unix ommand: is done by typing "exe " and then the ommand. For
example, we may want ns to initiate the display of a urve whose data are given in a two
olumn le named "data" within the simulation. This an be using the xgraph ommand
and will be written as:
exe xgraph data &

(note that the "&" sign is used to have the ommand exe uted in the ba kground).

The stru ture of an if ommand is as follows:


if { expression } {
<exe ute some ommands>
} else {
<exe ute some ommands>
}

The if ommand an be nested with other "if"s and with "else"s that an appear in the
"<exe ute some ommands>" part. Note that when testing equality, we should use "==" and
not "=". The inequality iswritten wiith !=.

Loops have the following form:


for { set i 0 } ( $i < 5 } { in r i } {
<exe ute some ommands>
}

t l allows to reate pro edures. They an return some value in whi h ase they ontain a
"return" ommand. The general form of a pro edure whi h we name "blue" is
pro blue { par1 par2 ... } {
global var1 var2
< ommands>
return $something
}

The pro edure re eives some parameters that an be obje ts les or variables. In our ase
these are named par1, par2, et . These parameters will be used within the pro edures with
these names. The pro edure is alled by typing blue x y ... where the values of x and
y will be used by the pro edure for par1 and par2. If par1 and par2 are hanged within
the pro edure, this will not a e t the values of x and y. On the other hand, if we wish
the pro edure to be able to a e t dire tly variables external to it, we have to de lare these
variables as "global". In the above example these are var1 and var2.

10

CHAPTER 1.

INTRODUCTION

# Usage: ns prime.t l NUMBER


#
NUMBER is the number up to whi h we want to obtain the prime numbers
#
if {$arg != 1} {
# Must get a single argument or program fails.
puts stderr "ERROR! ns alled with wrong number of arguments!($arg )"
exit 1
} else {
set j [lindex $argv 0
}
pro prime {j} {
# Computes all the prime numbers till j

prime $j

for {set a 2} {$a <= $j} {in r a} {


set b 0
for {set i 2} {$i < $a} {in r i} {
set d [expr fmod($a,$i)
if {$d==0} {
set b 1}
}
if {$b==1} {
puts "$a is not a prime number"
} else {
puts "$a is a prime number"
}
}}

Table 1.1: t l program for omputing prime numbers


In Table 1.1 is an example of a t l program for omputing all the prime numbers upto a given
limit j. For example, to obtain all the prime numbers up to 11 type simply "ns prime.t l 11". The
prime numbers example shows how to use an if ommand, loops, and a pro edure.

1.2.

TCL AND OTCL PROGRAMMING

# Usage: ns fa t.t l
#
NUMBER is
#
if {$arg != 1} {
# Must get a single
puts stderr "ERROR!
exit 1
} else {
set f [lindex $argv
}

NUMBER
the number we want to obtain the fa torial
argument or program fails.
ns alled with wrong number of arguments!($arg )"
0

pro Fa torial {x} {


for {set result 1} {$x > 1} {set x [expr $x - 1}{
set result [expr $result * $x
}
}
set res [Fa torial $f
puts "Fa torial is $res"

Table 1.2: t l simple program for omputing the fa torial fun tion

11

12

CHAPTER 1.

INTRODUCTION

Class Real
Real instpro init {a} {
$self instvar value_
set value_ $a
}
Real instpro sum {x} {
$self instvar value_
set op "$value_ + [$x set value_ = \t"
set value_ [expr $value_ + [$x set value_
puts "$op $value_"
}
Real instpro multiply {x} {
$self instvar value_
set op "$value_ * [$x set value_ = \t"
set value_ [expr $value_ * [$x set value_
puts "$op $value_"
}
Real instpro divide {x} {
$self instvar value_
set op "$value_ / [$x set value_ = \t"
set value_ [expr $value_ / [$x set value_
puts "$op $value_"
}
Class Integer -super lass Real
Integer instpro divide {x} {
$self instvar value_
set op "$value_ / [$x set value_ = \t"
set d [expr $value_ / [$x set value_
set value_ [expr round($d)
puts "$op $value_"
}
set realA [new Real 12.3
set realB [new Real 0.5
$realA sum $realB
$realA multiply $realB
$realA divide $realB
set integerA [new Integer 12
set integerB [new Integer 5
set integerC [new Integer 7
$integerA multiply $integerB
$integerB divide $integerC

Table 1.3: Simple Ot l program using real and integer numbers

Chapter 2

ns Simulator Preliminaries
In this Chapter we present the rst steps that onsist of








Initialization and termination aspe ts of ns simulator,


De nition of network nodes, links, queues and topology,
De nition of agents and of appli ations,
The nam visualisation tool,
Tra ing,
Random variables.

Some simple examples will be given that will enable us to do the rst steps in ns simulation.

2.1 Initialization and termination


An ns simulation starts with the ommand
set ns [new Simulator

whi h is thus the rst line in the t l s ript. In order to have output les with data on the
simulation (tra e les) or les used for visualisation (nam les), we need to reate the les using
"open":
#Open the Tra e file
set file1 [open out.tr w
$ns tra e-all $file1
#Open the NAM tra e file
set file2 [open out.nam w
$ns namtra e-all $file2

The above reates a data tra e le alled " le1" and a nam visualisation tra e le (for the NAM
tool) alled " le2". Within the t l s ript, these les are not alled expli itely by their names, but
instead by pointers that are de lared above and alled " le1" and " le2" respe tively.
The rst and fourth lines in the s ript are only omments, they are not simulation ommands.
The last line tells the simulator to re ord all simulation tra es in NAM input format. It also gives
the le name that the tra e will be written to later by the ommand $ns ush-tra e (see pro edure
13

14

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

" nish" below). In our ase, this will be the le pointed at by the pointer "$ le2", i.e. the le
"out.tr". Similarly, the fun tion tra e-all is for re ording the simulation tra e in a general as ii
format.
Note: the ommands tra e-all and namtra e-all may result in the reation of huge les. If we
wish to save spa e, other tra e ommands should be used so as to reate tra e only a subset of
the simulated events whi h may be dire tly needed. Su h ommands are des ribed in Se tion 2.6.
The termination of the program is done using a " nish" pro edure.
#Define a 'finish' pro edure
pro finish {} {
global ns file1 file2
$ns flush-tra e
lose $file1
lose $file2
exe nam out.nam &
exit 0
}

It loses the tra e les de ned before and exe utes the nam program for visualisation.
At the end of the ns program we should all the pro edure " nish" and spe ify at what time
the termination should o ur. For example,
$ns at 125.0 "finish"

will be used to all " nish" at time 125 se .


The simulation an then begin using the ommand
$ns run

2.2 De nition of a network of links and nodes


The way to de ne a node is
set n0 [$ns node

We reated a node that is pointed by the pointer n0. When we shall refer to that node in the
s ript, we shall thus write $ n0 (sin e n0 is the name of a pointer to a node and note of an a tual
node!)
On e we de ne several nodes, we an de ne the links that onne t them. An example of a
de nition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail

whi h means that nodes $ n0 and $ n2 are to be onne ted using a bi-dire tional link that has
10ms of propagation delay and a apa ity of 10 Mb/se for ea h dire tion.
To de ne a dire tional link instead of a bi-dire tional one, we should repla e "duplex-link" by
"simplex-link".
In NS, an output queue of a node is implemented as a part of ea h link whose input is that
node. The de nition of the link then in ludes the way to handle over ow at that queue. In
our ase, if the bu er apa ity of the output queue is ex eeded then the last pa ket to arrive
is dropped (DropTail option). Many alternative options exist, su h as the RED (Random Early
Dis ard) me hanism, the FQ (Fair Queueing), the DRR (De it Round Robin), the Sto hasti

2.3.

15

AGENTS AND APPLICATIONS

Fair Queueing (SFQ) and the CBQ (whi h in luding a priority and a round-robin s heduler); we
shall return later to the RED me hanism in more details.
Of ourse, we should also de ne the bu er apa ity of the queue related to ea h link. An
example would be:
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 20

A simplex link has the form presented in Fig. 2.1. A queue over ow is implemented by sending
dropped pa kets to a Null Agent. The TTL obje t omputes the Time To Live parameter1 for
ea h re eived pa ket. A duplex link is onstru ted from two parallel simplex links.
As an example of a simple network, onsider the one depi ted in Fig. 2.2; this network is
de ned through the s ript given in Table 2.1.
Note that we de ned the bu er apa ity orresponding to one link only (between n2 and n3).
The queues orresponding to all other links have the default value of 50. This default value an
be found at ns-default.t l2 in the ommand
file Queue set limit_ 50

How ould we nd this default? by rst he king the le ns-lib.t l where we nd the queue-limit
pro edure
Simulator instpro queue-limit { n1 n2 limit } {
$self instvar link_
[$link_([$n1 id:[$n2 id) queue set limit_ $limit
}

in whi h we see that the queue limit is indeed given by the variable limit_.

2.3 Agents and appli ations


Having de ned the topology (nodes and links) we should now make tra ow through them. To
that end, we need to de ne routing (in parti ular sour es, destinations) the agents (proto oles)
and appli ations that use them.
1 pa ktes have some asso iated tags whi h are updated in the network and that indi ate how long they an still
stay in the network before rea hing the destination. When this time expires then the pa ket is dropped
2 in ns-allinone-2.XXX/ns-2.XXX/t l/lib, where XXX stands for the version number, e.g. 1b9a

n1

n0
Queue

Delay

TTL

Agent/Null
drop
Figure 2.1: A simplex link

16
#Create six
set n0 [$ns
set n1 [$ns
set n2 [$ns
set n3 [$ns
set n4 [$ns
set n5 [$ns

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

nodes
node
node
node
node
node
node

#Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
$ns duplex-link $n3 $n4 0.5Mb 40ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 30ms DropTail
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 20

Table 2.1: De ning nodes, links and assigning queue size


In the previous example, we may wish to run an FTP (File Transfer Proto ol) appli ation
between node $ n0 and $ n4, and a CBR (Constant Bit Rate) appli ation between node $ n1 and
$ n5. The Internet proto l used by FTP is TCP/IP (TCP for Transport Control Proto ol/Internet
Proto ol) and the one used by CBR is UDP (User Datagram Proto ol). We should rst de ne
in Table 2.2 a TCP agent between the sour e node $n0 and the destination node $n4 and then
the FTP appli ation that uses it. We then de ne in Table 2.3 the UDP agent between the sour e
node $n1 and the destination node $n5 and the CBR appli ation that uses it.

2.3.1 FTP over TCP


TCP/IP is a dynami reliable ongestion ontrol proto ol whi h will be explained in details in
Chapter 4. It uses a knowledgements reated by the destination to know whether pa kets are well
re eived; lost pa kets are interpreted as ongestion signals. why TCP/IP thus requires bidire tional

$n0
2Mbps
10ms

300kbps
100ms

$n3

$n2
2Mbps
$n1 10ms

$n4
500kbps
40ms

300kbps
100ms

500kbps
30ms $n5

Figure 2.2: Example of a simple network

2.3.

AGENTS AND APPLICATIONS

17

#Setup a TCP onne tion


set t p [new Agent/TCP/Newreno
$ns atta h-agent $n0 $t p
set sink [new Agent/TCPSink/DelA k
$ns atta h-agent $n4 $sink
$ns onne t $t p $sink
$t p set fid_ 1
$t p set pa ketSize_ 552
#Setup a FTP over TCP onne tion
set ftp [new Appli ation/FTP
$ftp atta h-agent $t p
$ftp set type_ FTP

Table 2.2: The de nition of an FTP appli ation using a TCP agent
links in order for the A knowledgements to return to the sour e.
There are a number variants of the TCP/IP proto ol, su h as Tahoe, Reno, Newreno, Vegas.
The type of agent appears in the rst line:
set t p [new Agent/TCP/Newreno

This ommands also gives a pointer alled "t p" here to the TCP onne tion.
The ommand $ns atta h-agent $n0 $t p de nes the sour e node of the TCP onne tion.
The ommand
set sink [new Agent/TCPSink/DelA k

de nes the behavior of the destination node of TCP and assigns to it a pointer alled sink. We
note that in TCP the destination node has an a tive role in the proto ol of generating A knowledgements in order to guarantee that all pa kets arrive at the destination.
The ommand $ns atta h-agent $n4 $sink de nes the destination node. The ommand
$ns onne t $t p $sink

nally makes the TCP onne tion between the sour e and destination nodes.
TCP has many parameters with initial xed defaults values that an be hanged if mentionned
expli itly. For example, the default TCP pa ket size has a size of 1000 bytes. This an be
hanged to another value, say 552 bytes, using the ommand $t p set pa ketSize_ 552. Other
parameters that an be de ned are the maximum ongestion window max wnd_ and the maximum
advertized window window_. By default there is no bound on these windows, in whi h ase the
values are de ned to be zero.
When we have several ows, we may wish to distinguish them so that we an identify them with
di erent olors in the visualisation part. This is done by the ommand $t p set fid_ 1 that
assigns to the TCP onne tion a ow identi ation of "1"; we shall later give the ow identi ation
of "2" to the UDP onne tion.
On e the TCP onne tion is de ned, the FTP appli ation is de ned over it. This is done in
the three last lines in Table 2.2.
Note that both the TCP agent as well as the FTP appli ation are given pointers: we alled
the one for the TCP agent "t p" (but ould have used any other name) and the one for FTP is
alled "ftp".

18

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

#Setup a UDP onne tion


set udp [new Agent/UDP
$ns atta h-agent $n1 $udp
set null [new Agent/Null
$ns atta h-agent $n5 $null
$ns onne t $udp $null
$udp set fid_ 2
#Setup a CBR over UDP onne tion
set br [new Appli ation/Traffi /CBR
$ br atta h-agent $udp
$ br set type_ CBR
$ br set pa ket_size_ 1000
$ br set rate_ 0.01mb
$ br set random_ false

Table 2.3: The de nition of a CBR appli ation using a UDP agent

2.3.2 CBR over UDP


Next we de ne the UDP onne tion and the CBR appli ation over it, see Table 2.3. A UDP sour e
(Agent/UDP) and destination (Agent/Null) is de ned in a similar way as in the ase of TCP. For
the CBR appli ation that uses UDP, the table shows also how to de ne the transmission rate and
pa ket size.
Instead of de ning the rate, in the ommand $ br set rate_ 0.01mb, one an de ne the time
interval between transmission of pa kets using the ommand
$ br set interval_ 0.005

Other hara teristi s of CBR are random_ whi h is a ag indi ating whether or not to introdu e
random "moise"in the s heduled transmission times. It is "o " by default, and an be set to be
"on" by typing
$ br set random_ 1

The pa ket size an be set to some value (in bytes) using


$ br set pa ketSize_ <pa ket size>

2.3.3 UDP with other tra sour es


We may simulate other types of tra appli ations that use the UDP proto ol: the exponential
on-o tra sour e, the Pareto on-o sour e, and a tra e driven sour e. The exponential and
Pareto sour es are de lared, respe tively, using
set sour e [new Appli ation/Traffi /Exponential
set sour e [new Appli ation/Traffi /Pareto

These sour es take as parameters pa ketSIze_ (in bytes), burst_time_ whi h de nes the average
"on" time, idle_time_ whi h de nes the average "o " time, and rate_ whi h determines the
transmission rate during the "on" periods. In the Pareto On/O sour e we also de ne the "shape"
paremeter shape_. An example of a Pareto On/O is given by:

2.4.

SCHEDULING EVENTS

19

set sour e [new Appli ation/Traffi /Pareto


$sour e set pa ketSize_ 500
$sour e set burst_time_ 200ms
$sour e set idle_time 400ms
$sour e set rate_ 100k
$sour e set shape_ 1.5

(For a dis ussion on random variables, see Se tion 2.7.)


The tra e driven appli ation is de ned as follows. We rst de lare the tra e le:
set tra efile [bew Tra efile
$tra efile filename <file>

Then, we de ne the appli ation to be tra e driven and atta h it to that le:
set sr [New Appli ation/Traffi /Tra e
$sr atta h-tra efile $tra efile

The le should be in binary format and ontain inter-pa ket time in mse and pa ket size in bytes.

2.4 S heduling events


ns is a dis rete event based simulation. The t l s ript de nes when event should o ur. The
initializing ommand set ns [new Simulator reates an event s heduler, and event are then
s heduled using the format:
$ns at <time> <event>

The s heduler is started when running ns, i.e. through the ommand $ns run.
In our simple example, we should s hedule the beginning and end of the FTP and the CBR
appli ations. This an be done through the following ommands:
$ns
$ns
$ns
$ns

at
at
at
at

0.1 "$ br start"


1.0 "$ftp start"
124.0 "$ftp stop"
124.5 "$ br stop"

Thus the FTP will be a tive during from time 1.0 till 124.0 and the CBR will be a tive during
from time 0.1 till 124.5 (all units are in se onds).
We are now ready to run the whole simulation. If our ommands were written in a le alled
"ex1.t l" (see table 2.4) we have to simply type "ns ex1.t l".
Note: in Table 2.4 we added at the end another pro edure that writes an output le with the
instantaneous sizes of the window of TCP at time intervals of 0.1 se . In the example, the name
of the output le is "WinFile". The pro edure is a re ursive one, after ea h 0.1 se it alls itself
again. It passes as parameter the TCP sour e and the le to whi h we wish to write the output.

20

CHAPTER 2.

set ns [new Simulator


#Define different olors for data flows (for NAM)
$ns olor 1 Blue
$ns olor 2 Red
#Open the Tra e files
set file1 [open out.tr w
set winfile [open WinFile w
$ns tra e-all $file1
#Open the NAM tra e file
set file2 [open out.nam w
$ns namtra e-all $file2
#Define a 'finish' pro edure
pro finish {} {
global ns file1 file2
$ns flush-tra e
lose $file1
lose $file2
exe nam out.nam &
exit 0
}
#Create six
set n0 [$ns
set n1 [$ns
set n2 [$ns
set n3 [$ns
set n4 [$ns
set n5 [$ns

nodes
node
node
node
node
node
node

#Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
$ns duplex-link $n3 $n4 0.5Mb 40ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 30ms DropTail
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns simplex-link-op $n2 $n3 orient right
$ns simplex-link-op $n3 $n2 orient left
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

NS SIMULATOR PRELIMINARIES

2.4.

21

SCHEDULING EVENTS

#Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 20
#Setup a TCP onne tion
set t p [new Agent/TCP/Newreno
$ns atta h-agent $n0 $t p
set sink [new Agent/TCPSink/DelA k
$ns atta h-agent $n4 $sink
$ns onne t $t p $sink
$t p set fid_ 1
$t p set window_ 8000
$t p set pa ketSize_ 552
#Setup a FTP over TCP onne tion
set ftp [new Appli ation/FTP
$ftp atta h-agent $t p
$ftp set type_ FTP
#Setup a UDP onne tion
set udp [new Agent/UDP
$ns atta h-agent $n1 $udp
set null [new Agent/Null
$ns atta h-agent $n5 $null
$ns onne t $udp $null
$udp set fid_ 2
#Setup a CBR over UDP onne tion
set br [new Appli ation/Traffi /CBR
$ br atta h-agent $udp
$ br set type_ CBR
$ br set pa ket_size_ 1000
$ br set rate_ 0.01mb
$ br set random_ false
$ns
$ns
$ns
$ns

at
at
at
at

0.1 "$ br start"


1.0 "$ftp start"
124.0 "$ftp stop"
124.5 "$ br stop"

# Pro edure for plotting window size. Gets as arguments the name
# of the t p sour e node ( alled "t p") and of output file.
pro plotWindow {t pSour e file} {
global ns
set time 0.1
set now [$ns now
set wnd [$t pSour e set wnd_
puts $file "$now $ wnd"
$ns at [expr $now+$time "plotWindow $t pSour e $file" }
$ns at 0.1 "plotWindow $t p $winfile"
$ns at 125.0 "finish"
$ns run

Table 2.4: ex1.t l s ript le

22

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

2.5 Visualisation: using nam


When we run the example 2.1, the visualisation tool nam will display a 6 nodes network. The
lo ation of the nodes ould have been hosen at random. In order to reprodu e the initial lo ation
of the nodes as in Fig. 2.2, we added to the t l s ript the following lines:
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns simplex-link-op $n2 $n3 orient right
$ns simplex-link-op $n3 $n2 orient left
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

Note: if a random lo ation of nodes is hosen and it is not satisfa tory, one an press on the
"re-layout" button and then another random lo ation is hosen. One an also edit the lo ation by
li king at the Edit/View button, and then "draggind" ea h node to its required lo ation (with
the help of the mouth).
We note that the nam display shows us with animation the CBR pa kets (that ow from node 1
to 5) in red, and TCP pa kets ( owing from node 0 to 4) in blue. TCP ACKs (a knowledgements)
that go in the reverse dire tions are also in blue but are mu h shorter, sin e an ACK has a size of
40 bytes whereas the TCP pa ket is of size 552 bytes. To obtain the olors, we had to de ne in
the beginning of our s ript ex1.t l
$ns olor 1 Blue
$ns olor 2 Red

Note that if we already have a nam le, we do not have to run ns in order to view it, but
instead type dire tly the ommand nam <file name>.
"Snapshots" from the nam visualisations an be printed (into a printer or into a le) by going
into the "File" option in the top menu.
Othe things that an be done in NAM:




Coloring nodes; for example if n0 is to appear in red we write $n0 olor red.

Coloring links: type for example

Shape of nodes: by default they are round, but an appear di erently. For example one an
type $n1 shape box (or instead of "box" one an use "hexagon" or " ir le").
$ns duplex-link-op $n0 $n2 olor "green"

Adding and removing marks: We an mark a node at a given time (for example at the same
time as we a tivated some tra sour e at that time). For example, we an type:
$ns at 2.0 "$n3 add-mark m3 blue box"
$ns at 30.0 "$n3 delete-mark m3"

This results in a blue mark that surrounds the node 3 during the time interval [1,3.

Adding a labels: a label an appear on the s reen from a given time onwards. E.g. for giving
the label "a tive node" to a node n3 from time 1.2, type:
$ns at 1.2 "$n3 label \"a tive node\""

2.6.

23

TRACING

and to give a the label "TCP input link" to link n0-n2 type
$ns duplex-link-op $n0 $n2 label "TCP input link"

Adding text: at the bottom frame of the NAM window one an make text appear at a given
time. This an be used to des ribe some event that is s heduled at that time. An example
is
$ns at 5 "$ns tra e-annotate \"pa ket drop\""

One may further add in NAM a monitoring of the queue size. For example, to monitor the
input queue of the link n2-n3, one type
$ns simplex-link-op $n2 $n3 queuePos 0.5

(All the examples refer to obje ts de ned in ex1.t l.)

2.6 Tra ing


2.6.1 Tra ing obje ts
ns simulation an produ e both the visualisation tra e (for NAM) as well as an as ii le tra e
orresponding to the events registered at the network.
When we use tra ing (as mentionned in Se tion 2.1), ns inserts four obje ts to obje ts in the
link: EnqT, DeqT, Re vT and DrpT, as indi ated in Fig. 2.3.

n0

n1
EnqT

Queue
drop

DeqT

Delay

DrpT

Agent/Null

TTL

RecvT

Figure 2.3: Tra ing obje ts in a simplex link


EnqT registers information on erning a pa ket that arrives and is queued at the input queue
of the link. If the pa ket over ows then information on erning the dropped pa ket are handled
by DrpT. DeqT registers information at the instant the pa ket is dequed. Finally, Re vT gives us
information about pa kets that have been re eived at the ouput of the link.
ns allows us to get more information than through the above tra ing. One way is by using
queue monitoring. This is des ribed at the end of Se tion 4.3.

2.6.2 Stru ture of tra e les


When tra ing into an output as ii le, the tra e is organized in 12 elds as follows in Fig. 2.4.
The meanings of the elds are:
1. The rst eld is the event type. It is given by one of four possible symbols r; +; ; d whi h
orrespond respe tively to re eive (at the output of the link), enqueued, dequeued and
dropped.

24

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

From To Pkt Pkt Flags Fid Src Dst Seq Pkt


Event Time node
node size size
addr addr num id
Figure 2.4: Fields appearing in a tra e
2. The se ond eld gives the time at whi h the event o ur.
3. Gives the input node of the link at whi h the event o urs.
4. Gives the output node of the link at whi h the event o urs.
5. Gives the pa ket type (for example, CBR, or TCP. The type orresponds to the name that
we gave to those appli ations. For example, the TCP appli ation in Table 2.2 is alled "t p".
6. Gives the pa ket size.
7. Some ags (that we shall see later).
8. This is the ow id ( d) of IPv6 that a user an set for ea h ow at the input OT l s ript.
One an further use this eld for analysis purposes; it is also used when spe ifying stream
olor for the NAM display.
9. This is the sour e address given in the form of "node.port".
10. This is the destination address, given in the same form.
11. This is the network layer proto ol's pa ket sequen e number. Even though UDP implementations in a real network do not use sequen e number, ns keeps tra k of UDP pa ket sequen e
number for analysis purposes.
12. The last eld shows the unique id of the pa ket.
As an example, onsider the rst lines of the tra e produ ed by running the s ript ex1.t l given
in Table 2.4.

2.6.

+
r
+
r
+
r
+
r
+
+
r
+
r
+
r
r
+
r
+
+
r
+
r
+
r
+
+
r

TRACING

0.1 1 2 br 1000 ------- 2 1.0 5.0 0 0


0.1 1 2 br 1000 ------- 2 1.0 5.0 0 0
0.114 1 2 br 1000 ------- 2 1.0 5.0 0 0
0.114 2 3 br 1000 ------- 2 1.0 5.0 0 0
0.114 2 3 br 1000 ------- 2 1.0 5.0 0 0
0.240667 2 3 br 1000 ------- 2 1.0 5.0 0 0
0.240667 3 5 br 1000 ------- 2 1.0 5.0 0 0
0.240667 3 5 br 1000 ------- 2 1.0 5.0 0 0
0.286667 3 5 br 1000 ------- 2 1.0 5.0 0 0
0.9 1 2 br 1000 ------- 2 1.0 5.0 1 1
0.9 1 2 br 1000 ------- 2 1.0 5.0 1 1
0.914 1 2 br 1000 ------- 2 1.0 5.0 1 1
0.914 2 3 br 1000 ------- 2 1.0 5.0 1 1
0.914 2 3 br 1000 ------- 2 1.0 5.0 1 1
1 0 2 t p 40 ------- 1 0.0 4.0 0 2
1 0 2 t p 40 ------- 1 0.0 4.0 0 2
1.01016 0 2 t p 40 ------- 1 0.0 4.0 0 2
1.01016 2 3 t p 40 ------- 1 0.0 4.0 0 2
1.01016 2 3 t p 40 ------- 1 0.0 4.0 0 2
1.040667 2 3 br 1000 ------- 2 1.0 5.0 1 1
1.040667 3 5 br 1000 ------- 2 1.0 5.0 1 1
1.040667 3 5 br 1000 ------- 2 1.0 5.0 1 1
1.086667 3 5 br 1000 ------- 2 1.0 5.0 1 1
1.111227 2 3 t p 40 ------- 1 0.0 4.0 0 2
1.111227 3 4 t p 40 ------- 1 0.0 4.0 0 2
1.111227 3 4 t p 40 ------- 1 0.0 4.0 0 2
1.151867 3 4 t p 40 ------- 1 0.0 4.0 0 2
1.251867 4 3 a k 40 ------- 1 4.0 0.0 0 3
1.251867 4 3 a k 40 ------- 1 4.0 0.0 0 3
1.251867 4 3 a k 40 ------- 1 4.0 0.0 0 3
1.251867 4 3 a k 40 ------- 1 4.0 0.0 0 3
1.292507 4 3 a k 40 ------- 1 4.0 0.0 0 3
1.292507 3 2 a k 40 ------- 1 4.0 0.0 0 3
1.292507 3 2 a k 40 ------- 1 4.0 0.0 0 3
1.393573 3 2 a k 40 ------- 1 4.0 0.0 0 3
1.393573 2 0 a k 40 ------- 1 4.0 0.0 0 3
1.393573 2 0 a k 40 ------- 1 4.0 0.0 0 3
1.403733 2 0 a k 40 ------- 1 4.0 0.0 0 3
1.403733 0 2 t p 552 ------- 1 0.0 4.0 1 4
1.403733 0 2 t p 552 ------- 1 0.0 4.0 1 4
1.403733 0 2 t p 552 ------- 1 0.0 4.0 2 5
1.405941 0 2 t p 552 ------- 1 0.0 4.0 2 5
1.415941 0 2 t p 552 ------- 1 0.0 4.0 1 4

Table 2.5: First lines of the tra e le "out.tr" produ ed by ex1.t l

25

26

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

2.6.3 Tra ing a subset of events


In Se tion 2.1 we already mentioned how to tra e all simulated events. We now indi ate ways to
tra e only a subset of these.
The rst way to do so is by repla ing the ommand $ns tra e-all <filename> by the ommand $ns tra e-queue. For example, we an type
$ns tra e-queue $n2 $n3 $file1

whi h will result in an output tra e le that ontains only events that o ured over the link between
nodes n2 and n3 (these are nodes de ned in Table 2.1). (A similar ommand an be used for the
nam tra e, using namtra e-queue instead of tra e-queue.) The tra e-queue line should appear
of ourse after the de nition of the links, i.e. after the s ript part of Table 2.1.
It is also possible to lter events using unix ommands within the t l s ript. This will be
dis ussed in Se tion 3.6.

2.7 Random variables


Random variables with di erent distributions an be reated in ns. Due to its import role in tra
modeling and in network simulation we brie y re all the de nitions and moments of main random
variables in Appendix 11. For more ba kground, one an onslut e.g. http://www.xy oon. om/.

2.7.1 Seeds and generators


In addition to its distribution, there are other aspe ts that we need to be on erned of when
simulating a random variable:

Do we want to obtain the same value of the random variable when running again the simulation (possibly varying some other parameters of simulations)? this would allow us to
ompare dire tly, for a single random set of events, how the simulated results depend on
some physi al parameters (su h as link delays or queue length).

Often we need random variables to be independent of ea h other.

The generation of random variables uses a seed (whi h is some number that we write in the t l
s ript). The seed value of 0 results in the generation of a new random variable ea h time we run
the simulation, so if we wish to have the same generated random variables for di erent simulations
we would have to save the generated random variables. In ontrast, the if we use other seeds then
ea h time we run the simulation, the same sequen e of random variables that are generated in a
simulation will be generated.
In ns, if we use di erent generators with the same seed and the same distribution, they will
reate the same values of random variables (unless the seed is zero). We shall see this in an
example below.

2.7.2 Creating Random Variables


We rst reate a new generator and assign to it a seed, say 2, with the ommand
set MyRng1 [new RNG
$MyRng2 seed 2

Then when a tually reating a random variable, we have to de ne its distribution type and its
parameters. We give several examples below: we reate RVs with Pareto, Constant, Uniform,
Exponential and HyperExponential distributions.

2.7.

RANDOM VARIABLES

27

1. Pareto Distribution. A Pareto distributed RV, say r1 is ontsru ted by spe ifying its
expe tation and its shape parameter .
set
$r1
$r1
$r1

r1 [new RandomVariable/Pareto
use-rng $MyRng
set avg_ 10.0
set shape_ 1.2

2. Constant. A degenerated random variable is the onstant whi h equals to its average:
set r2 [new RandomVariable/Constant
$r2 use-rng $MyRng
$r2 set avg_ 5.0

3. Uniform distribution. It is de ned through the smallest and laregst point in its support:
set
$r3
$r3
$r3

r3 [new RandomVariable/Uniform
use-rng $MyRng
set min_ 0.0
set max_ 10.0

4. Exponential distribution. It's de ned through its average value:


set r4 [new RandomVariable/Exponential
$r4 use-rng $MyRng
$r4 set avg_ 5

5. Hyperexponential distribution. It is de ned as follows:


set
$r5
$r5
$r5

r5 [new RandomVariable/HyperExponential
use-rng $MyRng
set avg_ 1.0
set ov_ 4.0

Next we present a small program (rv1.t l) that tests Pareto distributed random variables with
di erent seeds and generators but with the same Pareto distribution. It is given in Table 2.6. For
ea h seed (of values 0, 1 and 2) and generator, we reate a sequen e of three random variables.
The " ount" variable is assigned the number of RVs that we reate using the "test" for ea h seed
and generator.
When we run this example we an observe that for seed 0, the two generators give di erent
values of variables; we thus obtain 6 di erent values (three from ea h generator). For other seeds,
a generator reates three di erent values, but these values do not depend on the generator: the
nth value reated by generator 1 is the same as the nth reated by generator 2.

28

CHAPTER 2.

NS SIMULATOR PRELIMINARIES

## simple example demonstrating use of the RandomVariable lass from t l


set ount 3
for {set i 0} {$i<3} {in r i} {
puts "===== i = $i "
set MyRng1 [new RNG
$MyRng2 seed $i
set MyRng2 [new RNG
$MyRng1 seed $i
set r1 [new RandomVariable/Pareto
$r1 use-rng $MyRng1
$r1 set avg_ 10.0
$r1 set shape_ 1.2
puts stdout "Testing Pareto Distribution, avg = [$r1 set avg_ shape = [$r1 set shape_"
$r1 test $ ount
set r2 [new RandomVariable/Pareto
$r2 use-rng $MyRng2
$r2 set avg_ 10.0
$r2 set shape_ 1.2
puts stdout "Testing Pareto Distribution, avg = [$r2 set avg_ shape = [$r2 set shape_"
$r2 test $ ount
}

Table 2.6: Testing Pareto distributed random variables with di erent seeds

Chapter 3

How to work with tra e les


NS simulator an provide a lot of detailed data on events that o ur at the network. If we wish
to analyze the data we may need to extra t relevant information from tra es and to manipulate
them.
One an of ourse write programs in any programming language that an handle data les.
Yet several tools that seem parti ularly adapted for these purposes already exist and are freely
available under various operating systems (unix, linux, windows et ). All they require is to write
short s ripts that are interpreted and exe uted without need for ompilation.

3.1 Pro essing data les with awk


awk allows us to do simple operations on data les su h as averaging the values of a given olumn,
summing or multiplying term by term between several olumns et .
In the two following examples we show how to take the average value of a given olumn in a
le, and then to ompute the standard deviation.
BEGIN { FS = "\t"} { nl++ } { s=s+$4} END {print "average:" s/nl}

Table 3.1: awk s ript for averaging the values in olumn 4 of a le


(Note: the "\t" should be used if olomns are tabulated. If not then one should repla e it by
" ".)
BEGIN {FS="\t"}{ln++}{d=$4-t}{s2=s2+d*d} END {print "standev:" sqrt(s2/ln)}

Table 3.2: awk s ript for obtaining the standard deviation of olumn 4 of a le
To use the rst s ript to ompute the average of olumn four of a le named "Out.ns" we
should type in unix:
awk -f Average.awk Out.ns

We shall get as a result something like: average : 29.397 for the average of olumn 4 (where
the rst olomn is onsidered as number 1).
29

30

CHAPTER 3.

HOW TO WORK WITH TRACE FILES

To ompute now the standard deviation of that olumn, we should type


awk -v t=29.397 -f StDev.awk Out.ns

whi h will give in response something like standev : 33.2003 Note that in the above s ript, we
have to opy the average value obtained from the previous s ript into the ommand that omputes
the standard deviation.
Note that if we do not divide at the end of the rst awk s ript (Table 3.1) by nl, we shall
obtain simply the sum of entries of olumn 4 instead of their average.
Note: awk ommands should be written in a single line. If we wish however to move to a new
line then we should type "at the end of the line (to indi ate its ontinuing).
The next examples takes as input a le with 15 olumns (0 to 14). It then reates as output
5 olumns, where the rst ontains olumn no. 1 of the original le, and olumns 2 to 5 are the
sum of olumbs 3-4, 6-8, 9-11 and 12-14, respe tively (12-14 orrespond to the three last olumns
in the original le).
BEGIN {FS="\t"}{l1=$3+$4+$5}{l2=$6+$7+$8}{d1=$9+$10+$11} \
{d2=$12+$13+$14}{print $1"\t" l1"\t" l2"\t" d1"\t" d2 } END {}

Table 3.3: Another awk s ript


The use of this s ript an be as follows:
awk -f suma.awk Conn4.tr > outfile

The original le here is Conn4.tr and the output is written into a le alled oufile.

3.2 Using

grep

The grep ommand in unix allows us to " lter" a le. We an reate a new le whi h onsists of
only those lines from the original le that ontain a given hara ter sequen e. For example, output
tra es in ns may ontain all types pa kets that go through all links and we may be interested only
in the data on erning t p pa kets that went from node 0 to node 2. If lines on erning su h
events ontain the string " 0 2 t p " then all we have to do is type
grep " 0 2 t p " tr1.tr > tr2.tr

where "tr1.tr" is the original tra e and "tr2.tr" is the new le. If we wish to obtain a le ontaining
all lines of tr1.tr that begin with the letter r, we should type
grep "^r" tr1.tr > tr2.tr

If we wish to make a le of all the lines that begin with "s" and have later "t p 1020" we
should type
grep "^s" simple.tr | grep "t p 1020" > tr3.tr

3.3.

PROCESSING DATA FILES WITH

PERL

31

3.3 Pro essing data les with perl


Perl allows easy ltring and pro essing of ASCII data les in unix. We present in this Se tion
some useful perl s ripts.
The rst, alled " olumn", allows to reate an outpput le that ontains some subset of olumns
from an original le. It an be loaded from http://nile.wpi.edu/NS/Example/ olumn.
The next example given in Table 3.4 omputes dynami ally the throughput of TCP onne tions.
The program averages the throughput over periods de ned by a parameter alled "granularity".
As input it takes three arguments: the name of a tra e le (e.g. out.tr), the node at whi h we
wish to he k the throughput of TCP, and the granularity.

32

CHAPTER 3.

HOW TO WORK WITH TRACE FILES

# type: perl throughput.pl <tra e file> <required node> <granlarity> >

file

$infile=$ARGV[0;
$tonode=$ARGV[1;
$granularity=$ARGV[2;
#we ompute how many bytes were transmitted during time interval spe ified
#by granularity parameter in se onds
$sum=0;
$ lo k=0;
open (DATA,"<$infile")
|| die "Can't open $infile $!";
while (<DATA>) {
x = split(' ');
# olumn 1 is time
if ($x[1-$ lo k <= $granularity)
{
# he king if the event orresponds to a re eption
if ($x[0 eq 'r')
{
# he king if the destination orresponds to 1st argument
if ($x[3 eq $tonode)
{
# he king if the pa ket type is TCP
if ($x[4 eq 't p')
{
$sum=$sum+$x[5;
}
}
}
}
else
{ $throughput=$sum/$granularity;
print STDOUT "$x[1 $throughput\n";
$ lo k=$ lo k+$granularity;
$sum=0;
}
}
$throughput=$sum/$granularity;
print STDOUT "$x[1 $throughput\n";
$ lo k=$ lo k+$granularity;
$sum=0;
lose DATA;
exit(0);

Table 3.4: perl program for omputing the throughput

3.4.

PLOTTING WITH GNUPLOT

33

3.4 Plotting with gnuplot


Gnuplot is a widely available free software both for unix/linux as well as window operating systems.
Gnuplot has a help ommand that an be used to learn details of its operation.
The simplest way to use gnuplot is to type "plot < fn >", where the le (whose name we
write as fn) has two olumns representing the x and y values of points. Points an be joined by a
line of di erent styles by writing ommands like:
plot 'fn' w lines 1

(di erent numbers an be given instead of "1") that produ e. di erent line styles). Alternatively,
one may use di erent type of points by writing ommands of the form
plot 'fn' w points 9

(again, several types of points an be depi ted depending on the number that appears after
"points").
Some other features of gnuplot: onsider for example the following ommands:
set size 0.6,0.6
set pointsize 3
set key 100,8
set xrange [90.0:120.0
plot 'fn1' w lines 1, 'fn2' w lines 8, 'fn3' with points 9




Line 1 will produ e a smaller size urve that the default.


Line 2 will produ e points that are larger than the defaults. (In both lines, other numbers
an be used).




Line 4 restri ts the range of the x axis to the interval 90-120.

Line 3 tells gnuplot where exa tly to put the `key`; the latter is the legend part in the gure
des ribing the plotted obje ts. In parti ular, it gives for ea h plotted obje t the line type
or point type that is used. Instead of an exa t poistion, one ould use the keywords `left`,
`right`, `top`, `bottom`, `outside` and `below`, e.g.

Line 5 superimposes three urves in a single gure, obtained from three di erent les: fn1,
fn2, fn3.

set key below

(whi h sets the key below the graph), or simply "set nokey" whi h disables the key ompletely. Note that the default name of ea h obje t that appears in the key is simply its
orresponding le name. If we wish to give an obje t a title other than the le name we
have to expli it this in the "plot" ommand, for example:
plot 'fn1' t "expe tation" w lines 1, 'fn2' t "varian e" w lines 2

Here, the names "expe tation" and "varian e" will appear in the key.
If the same sequen e of ommands are to be used several times, one an write them into a le, say
having the name "g1. om", and then simply load the le ea h time one wishes to use it:
load 'g1. om'

34

CHAPTER 3.

HOW TO WORK WITH TRACE FILES

gnuplot an be used to extra t some olumn from a multi olumn le. This is done as follows
plot 'queue.tr' using 1:($4/1000) t "kbytes" w lines 1, \
'queue.tr' using 1:5 t "pa kets" w lines 2

whi h means plotting rst a urve using olumn 1 of the le "queue.tr' as the x axis and 4 divided
by 1000 as the y axis, and then plotting on the same urve the olumn 5 for the y axis using the
same olumn 1 for the x axis. Note: this order between "using", "t" and "lines" is important!

3.5 Plotting with xgraph


Xgraph is a plotting utility that is provided by ns. (Sometimes it needs separate ompiling using
./ onfigure and then make when at the dire tory xgraph. Also, sometimes this does not work
with the xgraph that arrives with the whole ns single pa kage, and it an then be downloaded and
installed separately). Note that it allows to reate posts ript, Tgif les, and others, by li king on
the botton "Hd py". It an be invo ed within the t l ommand whi h thus results in an immediate
display after the end of the simulation.
As input, the xgraph ommand expe ts one or more as ii les ontaining ea h x y data point
pair perl line. For example, xgraph f1 f2 will print on the same gure the les f1 and f2.
Some options in xgraph are:





Title: use -t "title".

Color of text and grid: with the ag -v.

Size: -geometry xsize x ysize.


Title for axis: -x "xtitle" (for the title of the x axis) and -y "ytitle" (for the title of
the y axis).

An example of a ommand would be


xgraph f1 f2 -geometry 800x400 -t "Loss rates" -x "time" -y "Lost pa kets"

3.6 Extra ting information within a t l s ript


It is possible to integrate unix ommands su h as "grep" and "awk" already into the t l s ripts,
so as to start the pro essing of data while writing the le. For example Another way to limit the
tra ing les (or in general, to pro ess them online while they are being written) is to use linux
ommands related to le pro essing within the t l ommand that opens the required le.
For example, we may repla e the ommand $set file1 [open out.tr w (that we had in
the beginning of the s ript ex1.t l, see Table 2.4) by the ommand
set file1 [open "| grep \"t p\" > out.tr" w

This will result in ltering the lines written to the le "out.tr" and leaving only those that ontain
the word "t p".

Chapter 4

Des ription and simulation of


TCP/IP
TCP (Transport Control Proto ol) is the transport proto ol that is responsible for the transmission
of around 90% of the Internet tra , and understanding TCP is thus rui ial for dimensionning the
Internet. Although TCP is already largely deployed, it ontinues to envolve. The IETF (Internet
Engineering Task For e) is the main standardizing organization that is on erns with TCP. Unlike
some other standization organizations (ITU or ATM forum), all standards are free and available
on-line.
In the rst se tion we des ribe the operation of TCP. Then in the subsequent hapters we
present several ns s ripts that illustrate the analysis of TCP through simulations.

4.1 Des ription of TCP


4.1.1 Obje tives of TCP and window ow ontrol
TCP has several obje tives:





Adapt the transmission rate of pa kets to the available bandwidth,


Avoid ongestion at the network,
Create a reliable onne tion by retransmitting lost pa kets.

In order to ontrol the transmission rate, the number of pa kets that have not yet been re eived
(or more pre isely, for whi h the sour e has not obtained the information of good re eption) is
bounded by a parameter alled a ongestion window. We denote it by W . This means that the
sour e is obliged to wait and stop transmissions the number of pa kets that it had transmitted
and that have not been "a knowledged" rea hes W . In order to a knowledge pa kets and thus to
be able to retransmit lost pa kets, ea h transmitted pa ket has a suquen e number.

4.1.2 A knowledgements
The obje tives of A knowledgements (ACKs) are:

Regulate the transmission rate of TCP, ensuring that pa kets an be transmitted only when
other have left the network.

Render the onne tion reliable by transmitting to the sour e information it needs so as to
retransmit pa kets that have not rea hed the destination.
35

36

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

How does the destination know that a pa ket is missing?


How do we know that a pa ket is lost?
What information does the ACK arry along?
The ACK tells the sour e what is the sequen e number of the pa ket it expe ts. This is
illustrated by the following example. Suppose pa kets 1,2,...,6 have rea hed the destination (in
order). When pa ket 6 arrives, the destination sends an ACK to say it expe ts pa ket number 7.
If pa ket 7 arrives, the destination requests the number 8. Suppose pa ket 8 is lost and pa ket 9
arrives well. At that time, the destination sends an ACK alled "repeated ACK" as it tells the
sour e that it awaits pa ket 8. The information arried by the ACK is thus the same as the one
arried by the previous ACK.
This method is alled "impli it ACK". It is robust under losses of ACKs. Indeed, assume
that the ACK saying that the destination waits for pa ket 5, is lost. When the next ACK arrives,
saying it awaits pa ket 6, the sour e knows that the destination has re eived pa ket 5, so the
information sent by the lost ACK is dedu ed from the next ACK.
A TCP pa ket is onsidered lost if
 Three repeated ACKs for the same pa kets arrive at the sour e1, or

When a pa ket is transmitted, there is a timer that starts ounting. If its ACK does not
arrive within a period T0 , there is a \Time-Out" and the pa ket is onsidered to be lost.

Retransmitting after three duppli ated ACKS is alled "fast retransmit".


How to hoose T0? The sour e has an estimation of the average round trip time RT T , whi h
is the time ne essary for a pa ket to rea h the destination plus the time for its ACK to rea h the
sour e. It also has an estimation of the variability or RT T . T0 is determinied as follows:

T0 = RT T + 4D
Where RT T is the urrent estimation of RT T , and D is the estimation of the variability of RT T .
In order to estimate RT T , we measure the di eren e M between the transmission time of a pa ket
and the time its ACK returns. Then we ompute

RT T

a  RT T + (1 a)M;

D aD + (1 a)jRT T M j:
In order to de rease the number of ACKs in the system, TCP frequently uses the "delayed
ACK" option where an ACK is transmitted for only every d pa kets that rea h the destination.
The standard value of d is 2 (see RFC 1122). However, delaying an ACK till d > 1 pa kets are
re eived ould result in a deadlo k in ase that the window size is one! Theferore, if the rst
pa ket (of an expe ted group of d pa kets) arrives at the destination, then after some time interval
(typi ally 100ms) if d pa kets have not yet arrived, then an a knowledgement is generated without
further waiting.

4.1.3 Dynami ongestion window


Sin e the beginnings of the eighties, during several years, TCP had a xed ongestion window.
Networks at that time were unstable, there were many losses, large and severe ongestion periods,
during whi h the throughputs de reased substantially, there were many pa ket retransmissions
and large delays. In order to solve this problem, Van Ja obson proposed [24 to use a dynami
1 One does not onsider a single repeated ACK as a loss indi ation sin e duppli ated ACKS ould be due to
resequen ing of pa kets at the Internet

4.2.

TRACING AND ANALYSIS OF EXAMPLE EX1.TCL

37

ongestion window: its size an vary a ording to the network state. The basi idea is as follows.
When the window is small, it an grow rapidly, and when it rea hes large values it an only
grow slowly. When ongestion is dete ted, the window size de rease drasti ally. This dynami
me hanism allows to resolve ongestion rapidly and yet use e iently the network's bandwidth.
More pre isely, de ne a threshold Wth alled \slow start threshold" whi h represents our
estimation of the network apa ity. The window starts at a value of one. It thus transmits a
single pa ket. When its ACK returns, we an taransmit two pa kets. For ea h ACK of these
two pa kets, the window in reases by one, so that when the ACKs of these two pa kets return we
transmit four pa kets. We see that there is an exponential growth of the window. This phase is
alled "slow start". It is alled so be ause in spight of the rapid growth, it is slower than if we
had started dire tly with a value of W = Wth .
When W = Wth , we pass to a se ond phase alled \ ongestion avoidan e", where the window
W in reases by 1=bW whi h ea h ACK that returns. After transmitting W pa kets, W in reases
by 1. If we transmit the W pa kets at t, then at time t + RT T we transmit W +1, and at t +2RT T
we transmit W + 2, et ... We see that the window growth is linear.

4.1.4 Losses and a dynami threshold Wth


Not only W is dynami , Wth is too. It is xed in TCP to half the value of W when there has been
a pa ket loss.
There are several variants of TCP. In the rst variant, alled "Tahoe", whenever a loss is
dete ted then the window redu es to the value of 1 and a slow-start phase begins. This is a drasti
de rease of the window size and thus of the transmission rate.
In the other mostly used variants, alled Reno or New-Reno, the window drops to 1 only if
the loss is dete ted through a time-out. When a loss is dete ted through repeated ACKs then the
ongestion window drops by half. Slow start is not initiated and we remain in the " ongestion
avoidan e" phase.

4.1.5 Initiating a onne tion


To initiate a TCP onne tion, the sour e sends a "syn " pa ket of 40 bytes to the destination. The
destination then sends an ACK (also 40 pa kets long, alled "syn ACK"). When re eiving this
ACK, TCP an start sending data. Note: if either of these pa kets is lost then after a time-out
expires (usually 3 or 6 se s) then it is retransmitted. When a retransmitted pa ket is lost, the
time-out duration doubles and the pa ket is sent again.

4.2 Tra ing and analysis of Example ex1.t l


Let's run the perl program "throughput.pl" (Table 3.4) on the tra e le out.tr generated by the
ex1.t l s ript (see Table 2.4). We have to type
perl throughput.pl out.tr 4 1 > thp

We obtain an output le with the averaged re eived throughput of TCP (in bytes per se ond) as
a fun tion of time, where in our ase, ea h 1 se ond, a new value of the throughput is obtained.
This output le an be displayed using gnuplot by typing
gnuplot
set size 0.4,0.4
set key 60,15000
plot 'thp' w lines 1

38

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

The result is given in Fig. 4.1.


40000
35000
30000
25000
20000
15000
10000
5000
0

60
WinFile

50
40
30
thp

20
10
0

20 40 60 80 100 120 140

Figure 4.1: Throughput of TCP onne tion

20

40

60

80 100 120 140

Figure 4.2: Window size of TCP onne tion

In order to understand better the behavior of the system, we also plot the window size (Fig.
4.2). This is the le "WinFile" reated by running ex1.t l.
We see that from time 20 onwards a steady-state y li regime of TCP is attained: TCP is
always in ongestion avoidan e, and its window size in reases (almost linearly) untill ongestion
o urs.
Before time 20, we see a transient behavior in whi h TCP is in the slow-start phase.
At time 4.2 there are losses at the slow start phase. The window halves, whereas the throughput
be omes lose to zero. How an we explain that? The reason is that at time 4.2 there is a time-out,
so although the window is of size 30 (pa kets), there are no transmissions. At time 11 there are
again losses during a slow-start phase.

4.3 TCP over Noisy links and queue monitoring


In the previous examples losses were due to ongestion. In prati e, losses may also be aused from
noisy links. This is espe ially true in the ase of radio links, e.g. in ellular phones or in satellite
links. A link be ome may in fa t ompletely dis onne ted for some period. We shall see this aspe t
later, in Se tion 5.1. Or it may su er from o ausional interferen es (due to shadowing, fading
et ) that ause pa kets to ontain errors and then to be dropped. In this se tion we shall show
how to introdu e the simplest error model: we assume that pa kets are dropped on the forward
link a ording independently with some xed onstant probability.
This link error model, that will be introdu ed to the link onne ting nodes n3 and n2 (in the
example in Figure 4.3), is reated as follows:
#Set error model on link n2 to n3.
set loss_module [new ErrorModel
$loss_module set rate_ 0.2
$loss_module ranvar [new RandomVariable/Uniform
$loss_module drop-target [new Agent/Null
$ns lossmodel $loss_module $n2 $n3

The ommand $loss_module set rate_ 0.2 determines a loss rate of 20% of the pa kets. It
uses a generator of a uniformly distributed random variable, whi h is de lared in the next line.
The last line determines whi h link will be a e ted.
As an example of a TCP onne tion that shares a noisy bottle link with a UDP onne tion,
we onsider the network depi ted in Figure 4.3.

4.3.

39

TCP OVER NOISY LINKS AND QUEUE MONITORING


FTP

CBR

Figure 4.3: Example rdrop.t l

Queue monitoring An important obje t of ns is the monitor-queue. It allows to olle t mu h


useful information on queue length, on the arrivals, departures and losses. To implement a queue
monitor between nodes n2 and n3, we type:
set qmon [$ns monitor-queue $n2 $n3 [open qm.out w 0.1;
[$ns link $n2 $n3 queue-sample-timeout; # [$ns link $n2 $n3 start-tra ing

The "monitor-queue" obje t has 4 arguments: the rst two de nes the link where the queue is
lo ated, the third is the output tra e le and the last sais how frequently we wish to monitor the
queue. In our ase, the queue at the input of node n2-n3 is monitored every 0.1 se and the output
is printed into the le qm.out. The output le ontains the following 11 olumns:












the time,
the input and output nodes de ning the queue,
the queue size in bytes ( orresponds to the attribute size_ of the monitor-queue obje t)
the queue size in pa kets, ( orresponds to the attribute pkt_)
the number of pa kets that have arrived, ( orresponds to the attribute parrivals_)
the number of pa kets that have departured the link, ( orresponds to the attribute pdepartures_)
the number of pa kets dropped at the queue, ( orresponds to the attribute pdrops_)
the number of bytes that have arrived, ( orresponds to the attribute barrivals_)
the number of bytes that have departured the link, ( orresponds to the attribute bdepartures_)
the number of bytes dropped ( orresponds to the attribute bdrops_).

An alternative way to work dire tly with these attributes is des ribed in Se tion 4.5.

40

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

set ns [new Simulator


$ns olor 1 Blue
$ns olor 2 Red
#Open the NAM tra e file
set nf [open out.nam w
$ns namtra e-all $nf
#Open the Tra e file
set tf [open out.tr w
set windowVsTime2 [open WindowVsTimeNReno w
$ns tra e-all $tf
#Define a 'finish' pro edure
pro finish {} {
global ns nf tf
$ns flush-tra e
lose $nf
lose $tf
exe nam out.nam &
exit 0
}
#Create four nodes
set n0 [$ns node
set n1 [$ns node
set n2 [$ns node
set n3 [$ns node
$ns at 0.1 "$n1 label \"CBR\""
$ns at 1.0 "$n0 label \"FTP\""
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.07Mb 20ms DropTail
$ns simplex-link $n3 $n2 0.07Mb 20ms DropTail
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 10
#Monitor the queue for link (n2-n3). (for NAM)
$ns simplex-link-op $n2 $n3 queuePos 0.5
#Set error model on link n3 to n2.
set loss_module [new ErrorModel
$loss_module set rate_ 0.2
$loss_module ranvar [new RandomVariable/Uniform
$loss_module drop-target [new Agent/Null
$ns lossmodel $loss_module $n2 $n3

4.3.

TCP OVER NOISY LINKS AND QUEUE MONITORING

#Setup a TCP onne tion


set t p [new Agent/TCP/Newreno
$ns atta h-agent $n0 $t p
set sink [new Agent/TCPSink/DelA k
$ns atta h-agent $n3 $sink
$ns onne t $t p $sink
$t p set fid_ 1
#Setup a FTP over TCP onne tion
set ftp [new Appli ation/FTP
$ftp atta h-agent $t p
$ftp set type_ FTP
#Setup a UDP onne tion
set udp [new Agent/UDP
$ns atta h-agent $n1 $udp
set null [new Agent/Null
$ns atta h-agent $n3 $null
$ns onne t $udp $null
$udp set fid_ 2
#Setup a CBR over UDP onne tion
set br [new Appli ation/Traffi /CBR
$ br atta h-agent $udp
$ br set type_ CBR
$ br set pa ket_size_ 1000
$ br set rate_ 0.01mb
$ br set random_ false
#S hedule events for the CBR and FTP agents
$ns at 0.1 "$ br start"
$ns at 1.0 "$ftp start"
$ns at 624.0 "$ftp stop"
$ns at 624.5 "$ br stop"
# Printing the window size
pro plotWindow {t pSour e file} {
global ns
set time 0.01
set now [$ns now
set wnd [$t pSour e set wnd_
puts $file "$now $ wnd"
$ns at [expr $now+$time "plotWindow $t pSour e $file" }
$ns at 1.1 "plotWindow $t p $windowVsTime2"
# sample the bottlene k queue every 0.1 se . store the tra e in qm.out
set qmon [$ns monitor-queue $n2 $n3 [open qm.out w 0.1;
[$ns link $n2 $n3 queue-sample-timeout; # [$ns link $n2 $n3 start-tra ing

41

42

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

#Deta h t p and sink agents (not really ne essary)


$ns at 624.5 "$ns deta h-agent $n0 $t p ; $ns deta h-agent $n3 $sink"
$ns at 625.0 "finish"
$ns run

Table 4.1: t l s ript rdrop.t l for TCP over a noisy hannel


In Figure 4.4 we tra e (using gnuplot) the le WindowVsTimeNReno reated by the simulation.
A zoomed version is given in Figure 4.5.
8

8
win20

7
6

1
0

win20

100 200 300 400 500 600 700

Figure 4.4: Window size of TCP with 20%


random losses

1
100

150

200

250

300

Figure 4.5: Window size of TCP with 20%


random losses: a zoom

In several ases we an observe long timeouts, in parti ular at time 300. To see the huge impa t
of the random loss on TCP performan e, we run again the simulation but with no losses. The
result is depi ted in Fig. 4.6.
12
10
8
6
4
2
0
100

win0
150

200

250

300

Figure 4.6: TCP window size for 0 loss rate


An important performan e measure is the average throughput of TCP. A very simple way to
ompute it is to sear h in the tra e le out.tr the time that a TCP pa ket was re eived at the
destination (at node 3). In our simulation this is found at time 624.08754 and the orresponding
tra e line is
r 624.082754 2 3 t p 1000 ------- 1 0.0 3.0 1562 4350

4.4.

CREATING MANY CONNECTIONS WITH RANDOM FEATURES

43

The number before the last means that this is the 1562nd TCP pa ket to be well re eived at the
destination. The TCP throughput is thus simply this number divided by the duration of the FTP
onne tion (623 se onds), i.e. 2.507 pa kets per se ond, or equivalently, 2.507 Kbytes per se ond
(as a TCP pa ket ontains by default 1000 bytes) or 20058 bps.
Note: if we look at the rst lines of the out.tr le, we shall see that there are other TCP
pa kets (of size 40 pa kets ea h) whi h we have not ounted in the total number 1562. Their
serial numer is zero. We do not ount them be ause they orrespond to signalling pa kets that
are involved in the opening of the TCP onne tion.
Note that we used the delayed A k version of TCP by using the ommand
set sink [new Agent/TCPSink/DelA k

instead of simply set sink [new Agent/TCPSink.

4.4 Creating many onne tions with random features


In order to reate many onne tions, it is useful instead of de ning ea h node, link, onne tion or
appli ation individually, to de ne them as ve tors (or arrays) in t l (within loop statements).
Furthermore, it be omes of interest to hoose onne tions' parameters (su h as time of beginning or end of a tivity, link delays, et ) at a random way. We treat both issues in this Se tion,
and then provide an example. Note that we have already onsidered other aspe ts of randomness
in Se tion 4.3.

An example Consider the network at Figure 4.7. The t l s ript is given in Table 4.2.
6
5

3
2

Figure 4.7: Example of a network with several TCP onne tions


We reate 5 FTP onne tions that start at random: the starting time is uniformly distributed
between 0 and 7 se . The whole simulation duration is 10 se onds. We reate links with delay
that is hosen at random, uniformly distributed between 1ms and 5ms.
In addition to the standard tra e outputs, we also reate a le named win that will ontain
the evolution of the window size of all onne tion at a granularity of 0.03se . This is done in the
pro edure plotWindow. Note that the le "win" is addressed using the pointer "windowVsTimes".
The pro edure is alled re ursively for ea h of the 5 onne tions.

44

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

set ns [new Simulator


set nf [open out.nam w
$ns namtra e-all $nf
set
set
set
$ns

tf [open out.tr w
windowVsTime [open win w
param [open parameters w
tra e-all $tf

#Define a 'finish' pro edure


pro finish {} {
global ns nf tf
$ns flush-tra e
lose $nf
lose $tf
exe nam out.nam &
exit 0
}
#Create bottlene k and dest nodes and link between them
set n2 [$ns node
set n3 [$ns node
$ns duplex-link $n2 $n3 0.7Mb 20ms DropTail
set NumbSr 5
set Duration 10
#Sour e nodes
for {set j 1} {$j<=$NumbSr } { in r j } {
set S($j) [$ns node
}
# Create a random generator for starting the ftp and for bottlene k link delays
set rng [new RNG
$rng seed 0
# paratmers for random variables for delays
set RVdly [new RandomVariable/Uniform
$RVdly set min_ 1
$RVdly set max_ 5
$RVdly use-rng $rng
# parameters for random variables for begenning of ftp onne tions
set RVstart [new RandomVariable/Uniform
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng
}

4.4.

CREATING MANY CONNECTIONS WITH RANDOM FEATURES

#We define two random parameters for ea h onne tions


for {set i 1} {$i<=$NumbSr } { in r i } {
set startT($i) [expr [$RVstart value
set dly($i) [expr [$RVdly value
puts $param "dly($i) $dly($i) ms"
puts $param "startT($i) $startT($i) se "
#Links between sour e and bottlene k
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 100
}
#Monitor the queue for link (n2-n3). (for NAM)
$ns duplex-link-op $n2 $n3 queuePos 0.5
#Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 10
#TCP Sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
set t p_sr ($j) [new Agent/TCP/Reno
}
#TCP Destinations
for {set j 1} {$j<=$NumbSr } { in r j } {
set t p_snk($j) [new Agent/TCPSink
}
#Conne tions
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns atta h-agent $S($j) $t p_sr ($j)
$ns atta h-agent $n3 $t p_snk($j)
$ns onne t $t p_sr ($j) $t p_snk($j)
}
#FTP sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
set ftp($j) [$t p_sr ($j) atta h-sour e FTP
}
#Parametrisation of TCP sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
$t p_sr ($j) set pa ketSize_ 552
}
#S hedule events for the FTP agents:
for {set i 1} {$i<=$NumbSr } { in r i } {
$ns at $startT($i) "$ftp($i) start"
$ns at $Duration "$ftp($i) stop"
}

45

46

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

pro plotWindow {t pSour e file k} {


global ns
set time 0.03
set now [$ns now
set wnd [$t pSour e set wnd_
puts $file "$now $ wnd"
$ns at [expr $now+$time "plotWindow $t pSour e $file $k" }
# The pro edure will now be alled for all t p sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns at 0.1 "plotWindow $t p_sr ($j) $windowVsTime $j"
}
$ns at [expr $Duration "finish"
$ns run

Table 4.2: t l s ript ex3.t l for several ompeting TCP onne tions

4.5 Short TCP onne tions


The majority of the tra over the Internet onstitutes of le transfers. The average transfered le
is around 10Kbytes. This means that an "average" le has no more than 10 TCP pa kets taking
the typi al TCP pa ket size to be 1Kbyte [10, 35. This means that most of the le transfers end
in slow start phase. These les are frequently alled "mi e". Surprisingly, however, most tra in
the Internet is transmitted by very long les. These are alled "elephants". A typi al distribution
that des ribes the le size is the Pareto [10, with shape parameter of between 1 and 2 [10 (and
average of 10KB). The median of the le size is around 2.5Kbytes ([35 and referen es therein).
Note that a Pareto distribution with mean 10Kbytes and a median size of 2.5Kbytes de nes a
Pareto distribution with shape parameter = 1:16 and with a minimum size of 1.37Kbytes. The
distribution of interarrival times of new onne tions is frequently taken to be exponential.
In this Se tion we shall present ways to simulate short sessions, and to measure the distribution
of the transmission duration, of the number of ongoing onne tions and the throughput.
We shall onsider a network with the same topology as the one in Figure 4.2: several sour es
sharing a ommon bottlene k node and a ommon destination. There are several sour es of
TCP sharing a bottlene k link and a single destination. Their number is given by the paramter
"NodeNb" (in our example it is 6). TCP sour es are parametrized now by two parameters: the
sour e node and the session number from that node. For ea h TCP agent we de ne a new FTP
appli ation. New TCP onne tions arrive a ording to a Poisson pro ess. We shall therefore
generate the beginning of new TCP onne tion using exponentially distributed random variables.
The bottlene k link is assumed to be of 2Mbps, to have a delay of 1ms and to have a queue
of size 3000. All other input links that join this link have bandwidth of 100 Mbps and a delay of
1ms. We use the New Reno version with a maximum window size of 2000.
The average time between the arrivals of new TCP sessions at ea h node is in our example 45
mse . This means that on the average, 22.22 new sessions arrive at ea h node so that the global
arrival rate of sessions is 22.22 times NodeNb, whi h gives in our ase 133.33 sessions/se . We
generate sessions with random size with a mean of 10Kbytes, with Pareto distribution with shape

4.5.

SHORT TCP CONNECTIONS

47

1.5. The global rate of generation of bits is thus


133:33  104  8 = 10:67Mbps:
We see that the rate of generation of bits is larger than the bottlene k apa ity, so we shall expe t
a ongestion phenomenon to appear. However, TCP has the apa ity to avoid ongestion in the
network (at the bottlene k queue). Congestion will therefore appear in other forms that we shall
see.

Monitoring the number of sessions In the ontext of short TCP sessions we are interested not
only in pa ket statisti s but also in session statisti s. In the ns program we shall de ne a re ursive
pro edure, alled "Test" that he ks for ea h session whether it has ended. The pro edure alls
itself ea h 0.1 se (this is set in the variable "time"). If a onne tion has ended then we print in
an output le






the onne tion identi ers i and j (where (i; j ) stand for the j th onne tion from node i),
the start and end time of that onne tion,
the throughput of that onne tion,
the size of that transfer in bytes.

The pro edure then de nes another beginning of transfer after a random time. In the s ript that
follows, the output le will be Out.ns. To he k whether a session has ended, we use the ommand
if {[$t psr ($i,$j) set a k_==[$t psr ($i,$j) set maxseq_} {

Another re ursive pro edure alled " ountFlows" is used to update the number of a tive onne tions from ea h node (stored in a ve tor "Cnts" whose j th element orresponds to the number
of ongoing onne tions from node j .2 The pro edure has two parameters: "ind" and "sign". The
"ind" indi ates whi h sour e node is on erns. The "sign" indi ates to the pro edure what to
do: it is 0 when a all ends and 1 when it begins. These parameters are used when alling the
pro edure at the beginning or end of a onne tion. The pro edure also alls itself periodi ally
wa h 0.2 and it then prints the number of a tive alls into a le (Conn.tr). To do that, the the
"sign" parameter that is passed should be neither 1 nor 0 (we set it as 3).

Monitoring the queue In the t l program to ome, we present an alternative way to do

queue monitoring, more sophisti ated than the method we saw in Se tion 4.3. We use again the
ommands
set qfile [$ns monitor-queue $N $D [open queue.tr w 0.05
[$ns link $N $D queue-sample-timeout;

We ould however delet the se ond line. Instead of restri ting to that ommand, we work dire tly
with the attributes of the "monitor-queue" whi h have been des ribed in Se tion 4.3. This is done
in a pro edure alled "re ord" that is re ursively alled every 0.05 se . For example, we print
the used bandwidth of the queue (in Kbytes per se ond) into a le by dividing the number of
departures in a time epo h by the epo h duration. Note that the monitor-queue keeps tra k of the
total number of arrived bytes in the attribute bdepartures_. In order to ount only the number
of departures in a time epo h (and not during the entire simulation duration), we have to reset
the value of bdepartures_ at the end of ea h new omputation of the bandwidth.
2 The interest in having di erent ounters at di erent nodes lies in the fa t that we an also use the program for
the ase of asymetri input links, in whi h ase we shall be able to study the dependen e of the performan e on the
link's delay and bandwidth.

48

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

set ns [new Simulator


# There are several sour es of TCP sharing a bottlene k link
# and a single destination. Their number is given by the paramter NodeNb
#
#
#
#
#

S(1)
.
.
.
S(NodeNb)

---|
---- ---- N -------- D(1)...D(NodeNb)
|
----

# Next file will ontain the transfer time of different onne tions
set Out [open Out.ns w
# Next file will ontain the number of onne tions
set Conn [open Conn.tr w
#Open the Tra e file
set tf [open out.tr w
$ns tra e-all $tf
# We define three files that will be used to tra e the queue size,
# the bandwidth and losses at the bottlene k.
set qsize [open queuesize.tr w
set qbw [open queuebw.tr w
set qlost [open queuelost.tr w
# defining the topology
set N [$ns node
set D [$ns node
$ns duplex-link $N $D 2Mb 1ms DropTail
$ns queue-limit $N $D 3000
# Number of sour es
set NodeNb 6
# Number of flows per sour e node
set NumberFlows 530
#Nodes and links
for {set j 1} {$j<=$NodeNb} { in r j } {
set S($j) [$ns node
$ns duplex-link $S($j) $N 100Mb 1ms DropTail
$ns queue-limit $S($j) $N 1000
}
#TCP Sour es and Desstinations
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
set t psr ($i,$j) [new Agent/TCP/Newreno
set t p_snk($i,$j) [new Agent/TCPSink
$t psr ($i,$j) set window_ 2000
}
}

4.5.

SHORT TCP CONNECTIONS

#Conne tions
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
$ns atta h-agent $S($i) $t psr ($i,$j)
$ns atta h-agent $D $t p_snk($i,$j)
$ns onne t $t psr ($i,$j) $t p_snk($i,$j)
}
}
#FTP sour es
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
set ftp($i,$j) [$t psr ($i,$j) atta h-sour e FTP
}
}
# Generators for random size of files.
set rng1 [new RNG
$rng1 seed 0
set rng2 [new RNG
$rng2 seed 0
# Random interarrival time of TCP transfers at ea h sour e i
set RV [new RandomVariable/Exponential
$RV set avg_ 0.045
$RV use-rng $rng1
# Random size of files to transmit
set RVSize [new RandomVariable/Pareto
$RVSize set avg_ 10000
$RVSize set shape_ 1.5
$RVSize use-rng $rng2
# We now define the beginning times of transfers and the transfer sizes
# Arrivals of sessions follow a Poisson pro ess.
#
for {set i 1} {$i<=$NodeNb} { in r i } {
set t [$ns now
for {set j 1} {$j<=$NumberFlows} { in r j } {
# set the beginning time of next transfer from sour e i
set t [expr $t + [$RV value
set Con t($i,$j) $t

49

50

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

# set the size of next transfer from sour e i


set Size($i,$j) [expr [$RVSize value
$ns at $Con t($i,$j) "$ftp($i,$j) send $Size($i,$j)"
# update the number of flows
$ns at $Con t($i,$j) " ountFlows $i 1"
} }
#
#
#
#
#
#
#
#
#

Next is a re ursive pro edure that he ks for ea h session whether


it has ended. The pro edure alls itself ea h 0.1 se (this is
set in the variable "time").
If a onne tion has ended then we print in the file $Out
* the onne tion identifiers i and j,
* the start and end time of the onne tion,
* the throughput of the session,
* the size of the transfer in bytes
and we further define another beginning of transfer after a random time.

pro Test {} {
global Con t t psr Size NodeNb NumberFlows ns RV ftp Out t p_snk RVSize
set time 0.1
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
# We now he k if the transfer is over
if {[$t psr ($i,$j) set a k_==[$t psr ($i,$j) set maxseq_} {
if {[$t psr ($i,$j) set a k_>=0} {
# If the transfer is over, we print relevant information in $Out
puts $Out "$i,$j\t$Con t($i,$j)\t[expr [$ns now\t\
[expr ($Size($i,$j))/(1000*([expr [$ns now - $Con t($i,$j)))\t$Size($i,$j)"
ountFlows $i 0
$t psr ($i,$j) reset
$t p_snk($i,$j) reset
} } } }
$ns at [expr [$ns now+$time "Test"
}
for {set j 1} {$j<=$NodeNb} { in r j } {
set Cnts($j) 0
}
#
#
#
#
#
#
#

The following re ursive pro edure updates the number of onne tions
as a fun tion of time. Ea h 0.2 it prints them into $Conn. This
is done by alling the pro edure with the "sign" parameter equal
3 (in whi h ase the "ind" parameter does not play a role). The
pro edure is also alled by the Test pro edure whenever a onne tion
from sour e i ends by assigning the "sign" parameter 0, or when
it begins, by assigning it 1 (i is passed through the "ind" variable).

pro ountFlows { ind sign } {


global Cnts Conn NodeNb
set ns [Simulator instan e

4.5.

SHORT TCP CONNECTIONS

51

if { $sign==0 } { set Cnts($ind) [expr $Cnts($ind) - 1


} elseif { $sign==1 } { set Cnts($ind) [expr $Cnts($ind) + 1
} else {
puts -nonewline $Conn "[$ns now \t"
set sum 0
for {set j 1} {$j<=$NodeNb} { in r j } {
puts -nonewline $Conn "$Cnts($j) \t"
set sum [expr $sum + $Cnts($j)
}
puts $Conn "$sum"
$ns at [expr [$ns now + 0.2 " ountFlows 1 3"
}}
#Define a 'finish' pro edure
pro finish {} {
global ns tf qsize qbw qlost
$ns flush-tra e
lose $qsize
lose $qbw
lose $qlost
# Exe ute xgraph to display the queue size, queue bandwidth and loss rate
exe xgraph queuesize.tr -geometry 800x400 -t "Queue size" -x "se s" -y "# pa kets" &
exe xgraph queuebw.tr -geometry 800x400 -t "bandwidth" -x "se s" -y "Kbps" -fg white &
exe xgraph queuelost.tr -geometry 800x400 -t "# Pa kets lost" -x "se s" -y "pa kets" &
exit 0
}
# QUEUE MONiTORiNG
set qfile [$ns monitor-queue $N $D [open queue.tr w 0.05
[$ns link $N $D queue-sample-timeout;
# The following pro edure re ords queue size, bandwidth and loss rate
pro re ord {} {
global ns qfile qsize qbw qlost N D
set time 0.05
set now [$ns now
# print the urrent queue size in $qsize, the urrent used
# bandwidth in $qbw, and the loss rate in $qloss
$qfile instvar parrivals_ pdepartures_ bdrops_ bdepartures_ pdrops_
puts $qsize "$now [expr $parrivals_-$pdepartures_-$pdrops_"
puts $qbw "$now [expr $bdepartures_*8/1024/$time"
set bdepartures_ 0
puts $qlost "$now [expr $pdrops_/$time"
$ns at [expr $now+$time "re ord"
}
$ns
$ns
$ns
$ns
$ns

at 0.0 "re ord"


at 0.01 "Test"
at 0.5 " ountFlows 1 3"
at 20 "finish"
run

Table 4.3: t l s ript shortT p.t l for short TCP onne tions

52

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

The number of sessions generated (530 per sour e) insured that arrivals from all nodes ontinued
till the end of the simulations.
When running the s ript we obtain the queue size in Kbytes and in pa kets as depi ted in Fig.
4.8.
We also ran later the simulation with a redu ed number of 130 sessions per node, and the
queue size in Kbytes and in pa kets as depi ted in Fig. 4.9.
3000

1400

2500

1200
1000

2000

800

1500

600

1000
500

400
Kbytes
packets

200

Kbytes
packets

0
0 2 4 6 8 10 12 14 16 18 20

0 2 4 6 8 10 12 14 16 18 20

Figure 4.8: Queue size for the example in short- Figure 4.9: Queue size for the example in shortT p.t l
T p.t l where we limit the number of sessions
Here are some observations:
1. In both gures, the number of pa kets at the queue is larger than the number of Kbytes
queued. This may seem strange, sin e a TCP pa ket has a size of 1Kbyte! The reason is that
a very large number of sessions are very small (3 pa kets or less). Therefore the number of
over head pa kets of syze 40 bytes (that are sent at the beginning of ea h TCP onne tion)
is onsiderable (around one out of three!). Taking into a ount these short pa kets as well,
there are more pa kets then Kbytes.
2. Observe that in Figure 4.8 the queue size stabilizes at 3000, this is the maximum queue size
that is rea hed. From this moment on there will be losses at the queue.
3. Whereas the number of pa kets is always larger than the number of Kbytes queued in Fig.
4.8, we see that in Fig. 4.9 after some time, the number of pa kets agrees with the number
of Kbytes. At this point all pa kets at the queue are TCP data pa kets and there are no
pa kets of 40 bytes orresponding to beginning of sessions. This is due to the fa t that we
limitted the number of sessions per node to 130.
4. If we subtra t the output rate of the bottlene k link from the generatioin rate of data, we
shall obtain mu h more than the amount of data queued at the bottlene k queue. The reason
is that the data is also bu ered at the senders's bu er.
Next we observe the evolution of the number of ongoing onne tions at the system, as given
in Fig. 4.10 and the used bandwidth at the bottlene k link, see Fig. 4.11.

4.6 Advan ed monitoring tools


In Se tion 4.5 we he ked the termination of ea h TCP session periodi ally by omparing the
urrent a k sequen e number with the maximum sequen e number of onne tion. This probing
approa h is quite ostly. We mention two alternative monitoring approa hes:

4.6.

53

ADVANCED MONITORING TOOLS

2500

2500
Conn.tr

2000

2000

1500

1500

1000

1000

500

500

queuebw.tr
0 2 4 6 8 10 12 14 16 18 20

Figure 4.10: Number of Conne tions

0 2 4 6 8 10 12 14 16 18 20

Figure 4.11: Used bandwidth at the bottlene k

1. The rst is to de ne the a tions to be taken upon termination within a pro edure alled
"done" that is automati ally invoked when a onne tion is ended. The id of the onne tion
that has ended as well as other properties of the onne tion (su h as its start time) an be
used by the pro edure if de ned as states of the onne tion. The approa h is presented in
the t l s ript shortT p2.t l in Table 4.4.
2. One an use a per- ow monitor. It an give statisti s on ea h ow with information su h as
the amount of transfered pa kets, tranfered bytes, losses, et . We delay the dis ussion on
this approa h to Se tion 6.4.
The "state" de nitions of the TCP onne tions in the s ript are done in the same way we de ne
the maximum window size of TCP, the slow-start initial threshold et . In our s ript we de ne the
beginning time of the session, the session and node identity and the transfer size as su h states:
$t psr ($i,$j)
$t psr ($i,$j)
$t psr ($i,$j)
$t psr ($i,$j)

set
set
set
set

starts $t
sess $j
node $i
size [expr [$RVSize value

The pro edure "done" is de ned as follows (it repla es the "Test" pro edure in the previous
approa h of the s ript shortT p.t l in Table 4.3):
Agent/TCP instpro done {} {
global t psr NodeNb NumberFlows ns RV ftp Out t p_snk RVSize
# print in $Out: node, session, start time, end time, duration,
# trans-pkts, transm-bytes, retrans-bytes, throughput
set duration [expr [$ns now - [$self set starts
puts $Out "[$self set node \t [$self set sess \t [$self set starts \t\
[$ns now \t $duration \t [$self set ndatapa k_ \t\
[$self set ndatabytes_ \t [$self set nrexmitbytes_ \t\
[expr [$self set ndatabytes_/$duration "
ountFlows [$self set node 0
}

Note that we use other states of TCP onne tions:

ndatapa k_ is the number of pa kets transmitted by the onne tion (if a pa ket is retrans-

mitted several times, it is ounted here only on e).

54

CHAPTER 4.





DESCRIPTION AND SIMULATION OF TCP/IP

ndatabytes_ is the number of data bytes transmitted by the onne tion,


nrexmitpa kets_ is the number of pa kets retransmitted by the onne tion.
nrexmitbytes_ is the number of bytes retransmitted by the onne tion.

4.6.

ADVANCED MONITORING TOOLS

55

set ns [new Simulator


# There are several sour es ea h generating many TCP sessions sharing a bottlene k
# link and a single destination. Their number is given by the paramter NodeNb
#
#
#
#
#

S(1)
.
.
.
S(NodeNb)

---|
---- ---- N -------- D(1)...D(NodeNb)
|
----

# Next file will ontain the transfer time of different onne tions
set Out [open Out.ns w
# Next file will ontain the number of onne tions
set Conn [open Conn.tr w
#Open the Tra e file
set tf [open out.tr w
$ns tra e-all $tf
# defining the topology
set N [$ns node
set D [$ns node
$ns duplex-link $N $D 2Mb 1ms DropTail
$ns queue-limit $N $D 3000
set NodeNb 6
# Number of flows per sour e node
set NumberFlows 530
#Nodes and links
for {set j 1} {$j<=$NodeNb} { in r j } {
set S($j) [$ns node
$ns duplex-link $S($j) $N 100Mb 1ms DropTail
$ns queue-limit $S($j) $N 1000
}
#TCP Sour es, destinations, onne tions
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
set t psr ($i,$j) [new Agent/TCP/Newreno
set t p_snk($i,$j) [new Agent/TCPSink
$t psr ($i,$j) set window_ 2000
$ns atta h-agent $S($i) $t psr ($i,$j)
$ns atta h-agent $D $t p_snk($i,$j)
$ns onne t $t psr ($i,$j) $t p_snk($i,$j)
set ftp($i,$j) [$t psr ($i,$j) atta h-sour e FTP
} }

56

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

# Generators for random size of files.


set rng1 [new RNG
$rng1 seed 0
set rng2 [new RNG
$rng2 seed 0
# Random inter-arrival times of TCP transfer at ea h sour e i
set RV [new RandomVariable/Exponential
$RV set avg_ 0.045
$RV use-rng $rng1
# Random size of files to transmit
set RVSize [new RandomVariable/Pareto
$RVSize set avg_ 10000
$RVSize set shape_ 1.5
$RVSize use-rng $rng2
# We now define the beginning times of transfers and the transfer sizes
# Arrivals of sessions follow a Poisson pro ess.
#
for {set i 1} {$i<=$NodeNb} { in r i } {
set t [$ns now
for {set j 1} {$j<=$NumberFlows} { in r j } {
# set the beginning time of next transfer from sour e and attributes
set t [expr $t + [$RV value
$t psr ($i,$j) set starts $t
$t psr ($i,$j) set sess $j
$t psr ($i,$j) set node $i
$t psr ($i,$j) set size [expr [$RVSize value
$ns at [$t psr ($i,$j) set starts "$ftp($i,$j) send [$t psr ($i,$j) set size"
# update the number of flows
$ns at [$t psr ($i,$j) set starts " ountFlows $i 1"
}}
for {set j 1} {$j<=$NodeNb} { in r j } {
set Cnts($j) 0
}
# The following pro edure is alled whenever a onne tion ends
Agent/TCP instpro done {} {
global t psr NodeNb NumberFlows ns RV ftp Out t p_snk RVSize
# print in $Out: node, session, start time, end time, duration,
# trans-pkts, transm-bytes, retrans-bytes, throughput
set duration [expr [$ns now - [$self set starts
puts $Out "[$self set node \t [$self set sess \t [$self set starts \t\
[$ns now \t $duration \t [$self set ndatapa k_ \t\
[$self set ndatabytes_ \t [$self set nrexmitbytes_ \t\
[expr [$self set ndatabytes_/$duration "
ountFlows [$self set node 0
}

4.6.

ADVANCED MONITORING TOOLS

# The following re ursive pro edure updates the number of onne tions
# as a fun tion of time. Ea h 0.2 it prints them into $Conn. This
# is done by alling the pro edure with the "sign" parameter equal
# 3 (in whi h ase the "ind" parameter does not play a role). The
# pro edure is also alled by the "done" pro edure whenever a onne tion
# from sour e i ends by assigning the "sign" parameter 0, or when
# it begins, by assigning it 1 (i is passed through the "ind" variable).
#
pro ountFlows { ind sign } {
global Cnts Conn NodeNb
set ns [Simulator instan e
if { $sign==0 } { set Cnts($ind) [expr $Cnts($ind) - 1
} elseif { $sign==1 } { set Cnts($ind) [expr $Cnts($ind) + 1
} else {
puts -nonewline $Conn "[$ns now \t"
set sum 0
for {set j 1} {$j<=$NodeNb} { in r j } {
puts -nonewline $Conn "$Cnts($j) \t"
set sum [expr $sum + $Cnts($j)
}
puts $Conn "$sum"
$ns at [expr [$ns now + 0.2 " ountFlows 1 3"
} }
#Define a 'finish' pro edure
pro finish {} {
global ns tf
lose $tf
$ns flush-tra e
exit 0
}
$ns at 0.5 " ountFlows 1 3"
$ns at 20 "finish"
$ns run

Table 4.4: t l s ript shortT p2.t l for short TCP onne tions

57

58

CHAPTER 4.

DESCRIPTION AND SIMULATION OF TCP/IP

4.7 Exer ises


Exer ise 4.7.1 Explain why the window size os illates mu h more than the throughput in Figures
4.1 and 4.2.

Exer ise 4.7.2 What is the average throughput and loss rate of the TCP onne tion for Example

ex1.t l?

Exer ise 4.7.3 What is the average queue size for Example ex1.t l?
Exer ise 4.7.4 Study the e e t of the pa ket loss probability in the noisy model of rdrop.t l on
TCP throughput for loss probability ranging between 0 and 40 per ent.
Exer ise 4.7.5 Modify the s ript rdrop.t l in order to study the e e t of the loss probability of

pa kets (A knowledgements) on the reverse link n3-n2. Plot the throughput as a fun tion of the
loss probabilities for loss rates ranging between 0 and 40 per ent. Is TCP more sensitive to forward
random losses of pa kets or to ba kword random losses of A knowledgements?

Exer ise 4.7.6 Simulate two symetri ompeting TCP onne tions sharing a ommon bottlene k

link. Whi h share of the bandwidth does ea h one take if


(i) only one onne tion uses the delayed ACK option and both onne tions are NewReno?
(ii) both onne tions have the simple ACK option, the rst onne tion uses the Tahoe version and
the se ond the NewReno version?

Exer ise 4.7.7 In the pro edure plotWindow at the end of the s ript ex3.t l in Table 4.2, we
passed the onne tion number as an argument of the pro edure. What would happen if we passed
it as a global variable (i.e. if we wrote "global ns j")?

Exer ise 4.7.8 Analyze the loss pro esses obtained in ex3.t l (see Table 4.2). What should the

queue size at link n2-n3 be so as to avoid losses?

Exer ise 4.7.9 Add to the s ript shortT p.t l (Table 4.3) random losses (i) at the forward link

(ii) at the ba kward link N D. Vary the pa ket loss rate between 0% to 40%. Analyaze the
average time to transfer a le and the standard deviation of this time as a fun tion of the loss
rate. Explain the results! Note: in a ontext of many users, one may expe t that if some sessions
have low throughput due to losses, there will be more available throughput to other sessions, so
that short TCP sessions are less sensitive than long ones to losses. Do the simulations on rm
this or not? If not, explain what happens.

Chapter 5

Routing and network dynami s


We shall review in this hapter both uni ast as well as multi ast routing. Routing proto ols that
x a permanent route (stati routing) will be ompared to dynami routing. The in uen e of
dynami onne tivity on the routing will be examined. A good referen e for routing over the
Internet is [23.

5.1 Uni ast routing


There are several routing possibilities over the Internet. The simplest one is the stati routing in
whi h the shortest route (in terms of number of hops) is hosen throughout the onne tion.
ns an simulate noisy links (as we saw in Se tion 4.3) or even links that be ome dis onne ted.
To simulate a dis onne tion of a link between nodes $n1 and $n4 from time 1 to 4.5, for example,
we should type
$ns rtmodel-at 1.0 down $n1 $n4
$ns rtmodel-at 4.5 up $n1 $n4

We now onsider the network depi ted in Figure 5.1 whi h has two alternative routes between

Figure 5.1: A routing example


the sour e node 0 and the destination node 5. The default stati routing, used by ns, will hoose
the route 0-1-4-5 for setting onne tions.

59

60

CHAPTER 5.

ROUTING AND NETWORK DYNAMICS

set ns [new Simulator


#Define different olors for data flows (for NAM)
$ns olor 1 Blue
$ns olor 2 Red
#Open the Tra e file
set file1 [open out.tr w
$ns tra e-all $file1
#Open the NAM tra e file
set file2 [open out.nam w
$ns namtra e-all $file2
#Define a 'finish' pro edure
pro finish {} {
global ns file1 file2
$ns flush-tra e
lose $file1
lose $file2
exe nam out.nam &
exit 0
}
# Next line should be ommented out to have the stati routing
$ns rtproto DV
#Create six
set n0 [$ns
set n1 [$ns
set n2 [$ns
set n3 [$ns
set n4 [$ns
set n5 [$ns

nodes
node
node
node
node
node
node

#Create links between the nodes


$ns duplex-link $n0 $n1 0.3Mb 10ms
$ns duplex-link $n1 $n2 0.3Mb 10ms
$ns duplex-link $n2 $n3 0.3Mb 10ms
$ns duplex-link $n1 $n4 0.3Mb 10ms
$ns duplex-link $n3 $n5 0.5Mb 10ms
$ns duplex-link $n4 $n5 0.5Mb 10ms

DropTail
DropTail
DropTail
DropTail
DropTail
DropTail

5.1.

UNICAST ROUTING

#Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n1 $n4 orient up-left
$ns duplex-link-op $n3 $n5 orient left-up
$ns duplex-link-op $n4 $n5 orient right-up
#Setup a TCP onne tion
set t p [new Agent/TCP/Newreno
$ns atta h-agent $n0 $t p
set sink [new Agent/TCPSink/DelA k
$ns atta h-agent $n5 $sink
$ns onne t $t p $sink
$t p set fid_ 1
#Setup a FTP over TCP onne tion
set ftp [new Appli ation/FTP
$ftp atta h-agent $t p
$ftp set type_ FTP
$ns rtmodel-at 1.0 down $n1 $n4
$ns rtmodel-at 4.5 up $n1 $n4
$ns at 0.1 "$ftp start"
$ns at 12.0 "finish"
$ns run

Table 5.1: t l s ript for stati and dynami routing (ex2.t l)

61

62

CHAPTER 5.

ROUTING AND NETWORK DYNAMICS

In ontrast to the stati routing, the Internet an nd an alternative route on e it dis overs
that a route is dis onne ted. This option is used in ns by adding the ommand (see Table 5.1)
$ns rtproto DV

In the Example ex2.t l given in Table 5.1, the link link 1-4 is down during the time interval
[1; 4:5. In man, we an see this link be oming red at this time. A TCP onne tion is set
between node 0 and 5. When running the s ript, with the stati routing ( ommenting out the
ommand $ns rtproto DV) we see that even though the onne tion is resumed at time 4.5, the
TCP onne tion resumes only at time 8 approximately. The reason is that timeouts had o urred
in the absen e of ACKs returning to node 0, and their duration doubles with ea h new timeout.
In the nam tra e we an see in the dynami routing ase, the signaling pa kets that are used
to determine the path, not only at the beginning, but also at onne tivity hanges.

5.2 Network dynami s


We saw in the last Se tion that we an determine link states expli itely: the link an go down and
up at presele ted times. There are however other possibilities hange dynami ally the onne tivity:
a ording to an Exponential On-O pro ess, or a deterministi On-O pro ess, or a ording to
some given tra e le.
The deterministi and exponential models have four parameters: start time (0.5se from the
beginning of the simulation by default), up interval (10se by default), down interval (1se by
default) and nish time (end of the simulation by default). In the exponential ase, the up
and down parameters orrespond to the expe ted durations. For example, the syntax for the
deterministi model applied to link n1-n2 is
$ns rtmodel Deterministi {0.8 1.0 1.0} $n1 $n2

(the nish time is the default). In a ommand of the form


$ns rtmodel Deterministi {0.8 1.0} $n1 $n2

the start and end times are the defaults, and in a ommand of the form
$ns rtmodel Deterministi {- 1.0} $n1 $n2

the only non default parameter is the down interval. The exponential onne tivity is obtained
above by repla ing "Deterministi " by "Exponential".
The ommand that orresponds to onne tivity based on a tra e le is
$ns rtmodel Tra e < onfig_file> $n0 $n1

Finally, one an also generate a sequen e of routing states in ns, and use it as an input (see [14).

Node failures There is a possibility of a node going down and up. This is done exa tly as we

saw for the ase of links, ex ept that only one node appears as argument at the end.

5.3 Multi ast proto ols


In multi ast, there may be several multi ast groups of members; the groups may overlap. In IP
multi ast, re eiver must request membership in multi ast group whereas a sender an send without
rst joing a group. Senders do not re eive feedba k from the network about the re eivers in IP

5.3.

MULTICAST PROTOCOLS

63

multi ast routing. Not all network nodes may be able to handle multi ast; in ns one an de lare
whi h nodes indeed have multi ast apabilities.
A routing proto ol de nes the me hanism by whi h the multi ast tree is omputed in the
simulation. There are two main lasses of routing lasses:
1. a "dense mode" type whi h is appropriate for the ase of a large number of multi ast users;
in that ase multi ast trees are onstru ted for any pair of sour e and its multi ast group. The
onstru tion of the trees require broad asting to all nodes in the network.
2. a "sparse mode" in whi h there is a small number of nodes. Therefore the routing an be
handled using a single shared tree.
Four multi ast routing proto ols are available in ns: the Dense Mode (DM), the Centralised
(CtrM ast), the Shared Tree Mode (ST) and the Bi-dire tional Sahred Tree mode (BST). Unfortumately, the way ns simulates the proto ols does not in lude mu h of the signaling, espe ially
in the initialization. The DM proto ol is the only one that has a dynami version in ns, alled
dynami DM.

5.3.1 The Dense mode


The DM proto ol has two modes whi h are quite similar: the proto ol pimDM (Proto ol Independant Multi ast - Dense Mode) and the dvmrp (Distan e Ve tor Multi ast Routing Proto ol)
mode [39, pimDM being somewhat simpler. They are based on an initial ooding of the network
(using the RFP approa h) and then on the omputation of the shortest reverse path. We suppose
that point-to-point routing tables are availble. This is done as follows.

If a router re eives a multipoint pa ket from a sour e S to a group G, it he ks rst (using


point-to-point routing tables) that the input re eption interfa e orresponds to pa ket S:
this means that this router is in the shortest from the sour e (this is thus alled a "shortest
reverse path" approa h). If the result is negative then it sends a message "delete(S,G)", i.e.
a message to the sour e requesting to stop sending to it pa kets from S to G.

If the result is positive then the router sends a opy of the message to the set T of all the
interfa es through whi h it has not yet re eived a request "delete(S,G)". If T is empty, then
it destroys the pa ket and sends a message "delete(S,G)" to the interfe e through whi h it
re eived the message.

5.3.2 Routinng based on a RV point


The entralized m ast (CrtM ast) is similar to the so alled PIM-SM (the Sparse Mode of PIM
[11). There is a Rendezvous Point (RP). A shared tree is built for a multi ast group rooted at this
RP. A entralized omputation agent is used to ompute the forwarding trees and set up multi ast
forwarding state, S, G (the state S orresponds to the sour e of a pa ket and G to the address of
the multi ast group that it is destinated to) at the relevant nodes as new re eivers join a group.
Data pa kets from the senders to a group are uni ast to the RP. The multi asting from the RP
to the group is done a ording to a shortest path tree.
The ST mode is a simpli ed version of the above sparse mode routing proto ol. This proto ol
has a bidire tional version in ns alled BST, whi h is used in the standard version CBT [4 and in
the BGMP proto ol for inter-domain multi ast [37.
In proto ols based on a RP point, all multi ast tra traverses the RV point, whi h is thus
a bottlene k. A failure in that node is rti al for the whole group. Another problem with this
approa h is that tra travels on non-optimal paths. The advantages of this approa h are 1. the
simpli ity in the state information: only one entry per-sour e per-group, 2. signalling does not
invlolve the whole network.

64

CHAPTER 5.

ROUTING AND NETWORK DYNAMICS

Note that in PIM-SM, there is a possibility of swit hing to optimized sour e-based trees (S,G)
instead of routingn through the RV point. This o urs if the sour e data rate ex eeds some
threshold. Thus the RV point an ease to be a bottlene k if tra rate is large. ST mode does
not simulate this feature.

5.4 Simulating multi ast routing


Multi ast requires enhan ements to the nodes and links of the network. ns has therefore spe i
requirements from the Simulator lass before reating the topology. We thus begin by the spe ial
ommand
set ns [new Simulator
$ns multi ast

In the t l s ript we de ne group addresses using the ommand set group1 [Node allo addr.
We then de ne an appli ation and a transport proto ol agent atta hed on one hand to a given
sour e node and on the other hand to a group destination.
We onsider below the DM proto ol. When a sour e S sending to a group G be omes a tive
it begins ooding the network along the atta hed tree orresponding to group G. When a leaf
that has not joined the multi ast group re eives a pa ket to that group, it sends a mesage to
the in oming interfa e to delete it from the tree (S,G) (a "prune" pa ket). This then propagate
ba kwords to the sour e: a node that re eives a message from all its output links within the tree
of (S,G) requesting to delete these links, sends ba k to its in oming interfa e a message to delete
it from the tree (S,G).
A sour e will stop ompletely sending pa kets if there are no onne ted re eivers in that group;
it will resume sending pa ket when a re eiver onne ts.
An example of a multi ast on guration with a six node network is depi ted in Figure 5.2:
We now onsider the network depi ted in Figure 5.1
3
2
5

Figure 5.2: A multi ast routing example

5.4.

65

SIMULATING MULTICAST ROUTING

set ns [new Simulator


$ns multi ast
set f [open out.tr w
$ns tra e-all $f
$ns namtra e-all [open out.nam w
$ns olor
# the nam
$ns olor
# the nam
$ns olor

1 red
olors for the prune pa kets
30 purple
olors for the graft pa kets
31 green

# allo ate a multi ast address;


set group [Node allo addr
# nod is the number of nodes
set nod 6
# reate multi ast apable nodes;
for {set i 1} {$i <= $nod} {in r i} {
set n($i) [$ns node
}
#Create links between
$ns duplex-link $n(1)
$ns duplex-link $n(2)
$ns duplex-link $n(2)
$ns duplex-link $n(2)
$ns duplex-link $n(3)
$ns duplex-link $n(4)
$ns duplex-link $n(4)
$ns duplex-link $n(5)

the nodes
$n(2) 0.3Mb
$n(3) 0.3Mb
$n(4) 0.5Mb
$n(5) 0.3Mb
$n(4) 0.3Mb
$n(5) 0.5Mb
$n(6) 0.5Mb
$n(6) 0.5Mb

10ms
10ms
10ms
10ms
10ms
10ms
10ms
10ms

DropTail
DropTail
DropTail
DropTail
DropTail
DropTail
DropTail
DropTail

# onfigure multi ast proto ol;


set mproto DM
# all nodes will ontain multi ast proto ol agents;
set mrthandle [$ns mrtproto $mproto
set udp1 [new Agent/UDP
set udp2 [new Agent/UDP
$ns atta h-agent $n(1) $udp1
$ns atta h-agent $n(2) $udp2

66

CHAPTER 5.

ROUTING AND NETWORK DYNAMICS

set sr 1 [new Appli ation/Traffi /CBR


$sr 1 atta h-agent $udp1
$udp1 set dst_addr_ $group
$udp1 set dst_port_ 0
$sr 1 set random_ false
set sr 2 [new Appli ation/Traffi /CBR
$sr 2 atta h-agent $udp2
$udp2 set dst_addr_ $group
$udp2 set dst_port_ 1
$sr 2 set random_ false
# reate re eiver agents
set r vr [new Agent/LossMonitor
# joining and leaving the group;
$ns at 0.6 "$n(3) join-group $r vr $group"
$ns at 1.3 "$n(4) join-group $r vr $group"
$ns at 1.6 "$n(5) join-group $r vr $group"
$ns at 1.9 "$n(4) leave-group $r vr $group"
$ns at 2.3 "$n(6) join-group $r vr $group"
$ns at 3.5 "$n(3) leave-group $r vr $group"
$ns at 0.4 "$sr 1 start"
$ns at 2.0 "$sr 2 start"
$ns at 4.0 "finish"
pro finish {} {
global ns
$ns flush-tra e
exe nam out.nam &
exit 0
}
$ns run

Table 5.2: Example for multi ast with DM model: pimdm.t l

5.4.

SIMULATING MULTICAST ROUTING

67

The Loss Monitor Agent We used here the LossMonitor Agent, whi h is a pa ket sink agent
that maintains statisti s about the re eived tra , su h as the amount of re eived as well as lost
information. In parti ular, we an a ess the following state variables: nlost_ (number of lost
pa kets), npkts_ (number of re eived pa kets), bytes_ (number of re eived bytes), lastPktTime_
(time at whi h the last pa ket was re eived) and expe ted_ (the expe ted sequen e number of
the next pa ket). One an use instead of the LossMonitor agent, the Null agent, as we did before,
i.e. type set r vr [new Agent/Null instead of set r vr [new Agent/LossMonitor.

5.4.1 DM mode
The ommand set mproto DM indi tes that we use the Dense Mode proto ol. By default, the
pimDM is used. In order to use the dvmrp mode, one has to add the line
DM set Ca heMissMode dvmrp

just before the line set mproto DM.


In the DM mode, ooding o urs periodi ally so as to dete t the nodes that are onne ted
to the group. The timer value for the period is given in a variable alled PruneTimeout. It's
default value is 0.5se ; If another value is required, say 0.8 se , then one should add to the t l
s ript the ommand
DM set PruneTimeout 0.8

just before the line set mproto DM.

5.4.2 Routing with a entralized RV point


For the entralized mode one needs:
# onfigure multi ast proto ol;
set mproto CtrM ast
# all nodes will ontain multi ast proto ol agents;
set mrthandle [$ns mrtproto $mproto
# set RV and bootstrap points
$mrthandle set_ _rp $n(2)

Here we hose n(2) to be the RP point.


In both the entralized as well as in the ST mode, the signalling (prune pa kets) are not
simulated.
We present in Table 5.3 the same example as in pimdm.t l (Table 5.2) but with the BST
routing proto ol.

68

CHAPTER 5.

ROUTING AND NETWORK DYNAMICS

set ns [new Simulator -multi ast on


set f [open out.tr w
$ns tra e-all $f
$ns namtra e-all [open out.nam w
$ns olor
# the nam
$ns olor
# the nam
$ns olor

1 red
olors for the prune pa kets
30 purple
olors for the graft pa kets
31 green

# allo ate a multi ast address;


set group [Node allo addr
# nod is the number of nodes
set nod 6
# reate multi ast apable nodes;
for {set i 1} {$i <= $nod} {in r i} {
set n($i) [$ns node
}
#Create links between
$ns duplex-link $n(1)
$ns duplex-link $n(2)
$ns duplex-link $n(2)
$ns duplex-link $n(2)
$ns duplex-link $n(3)
$ns duplex-link $n(4)
$ns duplex-link $n(4)
$ns duplex-link $n(5)

the nodes
$n(2) 0.3Mb
$n(3) 0.3Mb
$n(4) 0.5Mb
$n(5) 0.3Mb
$n(4) 0.3Mb
$n(5) 0.5Mb
$n(6) 0.5Mb
$n(6) 0.5Mb

# onfigure multi ast proto ol;


BST set RP_($group) $n(2)
$ns mrtproto BST
set udp1 [new Agent/UDP
set udp2 [new Agent/UDP
$ns atta h-agent $n(1) $udp1
$ns atta h-agent $n(2) $udp2

10ms
10ms
10ms
10ms
10ms
10ms
10ms
10ms

DropTail
DropTail
DropTail
DropTail
DropTail
DropTail
DropTail
DropTail

5.4.

SIMULATING MULTICAST ROUTING

set sr 1 [new Appli ation/Traffi /CBR


$sr 1 atta h-agent $udp1
$udp1 set dst_addr_ $group
$udp1 set dst_port_ 0
$sr 1 set random_ false
set sr 2 [new Appli ation/Traffi /CBR
$sr 2 atta h-agent $udp2
$udp2 set dst_addr_ $group
$udp2 set dst_port_ 1
$sr 2 set random_ false
# reate re eiver agents
set r vr [new Agent/LossMonitor
# joining and leaving the group;
$ns at 0.6 "$n(3) join-group $r vr $group"
$ns at 1.3 "$n(4) join-group $r vr $group"
$ns at 1.6 "$n(5) join-group $r vr $group"
$ns at 1.9 "$n(4) leave-group $r vr $group"
$ns at 2.3 "$n(6) join-group $r vr $group"
$ns at 3.5 "$n(3) leave-group $r vr $group"
$ns at 0.4 "$sr 1 start"
$ns at 2.0 "$sr 2 start"
$ns at 4.0 "finish"
pro finish {} {
global ns
$ns flush-tra e
exe nam out.nam &
exit 0
}
$ns run

Table 5.3: Example for multi ast with RV point: bst.t l

69

70

CHAPTER 5.

ROUTING AND NETWORK DYNAMICS

5.5 Observations on the simulation of pimdm.t l


Dense mode: pimdm and dvmrp If we run the simulation and observe the tra e, we shall
see that in addition to the CBR pa kets, there are two other types of pa kets: the "prune" pa ket,
and the "graft" pa ket. The role of the prune pa ket sent by a node N is to signal to the node
that had sent a previous pa ket to N to stop sending pa kets to N . The "graft" pa ket is a signal
originating from a node that wishes to join the group (after it had been dis onne ted). In the
NAM display of our simulation, the graft pa kets are light green, and the prune are purple.
We an see that at time 0.4, node 0 starts sending CBR pa kets that ood the network. But
there is no re eivers at the multi ast group, so eventually, prune pa kets return to the sour e and
transmission is stopped (time 0.579). At time 0.6, a graft pa ket is sent from node 2 (who wishes
to join the group) to node 1, and then from node 1 to node 0. Node 0 then restarts transmission.
At time 0.9978, there is again an attempt to he k whether there are onne ted re eiver nodes
in the group other than 2 and the network is again ooded; prune pa kets return to stop the
trahsmission to nodes 3, 4, 5.
The entralized mode We see in the tra e en apsulated pa kets that are sent from a sour e to
the RV point of size 230 byte. The header is then removed by the RV point whi h then forwards
the pa ket (size 210 bytes) to the members of the group.

5.6 Exer ises


Exer ise 5.6.1 Run the program ex2.t l (see Table 5.1) ommenting out the ommand "$ns
rtproto DV" and explain what happens.

Exer ise 5.6.2 Run the program ex2.t l (see Table 5.1) with the ommand "$ns rtproto DV"

and explain the di eren es with the previous stati routing.

Exer ise 5.6.3 Change and run simulation ex2.t l (see Table 5.1) for a duration of 20se with

stati routing but with a dynami exponential ON-OFF onne tivity, with ON average time of
3 se and OFF average time of 0.5 se . Analyze the behavior of the TCP onne tion and the
time-out behavior.

Exer ise 5.6.4 Run the pimdm.t l s ript (see Table 5.2). How many CBR pa kets have been
transmitted from ea h sour e, and how many have been lost? How many CBR pa kets have been
re eived at nodes that did not need them (more pre isely, how many prune pa kets have been
generated)?
Exer ise 5.6.5 Consider the tra e obtained from the pimdm.t l s ript. At time 1.8375 we start

to have losses at node 0. At time 2.481 pa kets start getting lost also at node 1. Explain these
losses!

Exer ise 5.6.6 Run the program pimdm.t l with the dvmrp mode of DM. What are the di eren es
that you observe between dvmrp and the pimDM version?

Exer ise 5.6.7 Run the entralised version of the multi ast. Explain what happens when the RP

is hanged to node n(5) (in the NAM it will orrespond to node 4, sin e NAM ounts from 0).
Explain why this is less e ient than hoosing the RP node to be n(2). How an we measure
e ien y?

Chapter 6

RED: Random Early Dis ard


6.1 Des ription of RED
The RED bu er management s heme has been introdu ed on 1993 by Floyd and Ja obson [16,
and is further des ribed in the RFC 2309 [7. Many important referen es on RED an be found at
http://www.i ir.org/ oyd/red.html. The basi idea is that one should not wait till the bu er is full
in order dete t dete tion (drop pa kets), but start dete ting ongestion before the bu er over ows.
Congestion signals ould still be through pa ket dropping, but ould now also be through marking
of pa kets without the need to a tually drop them.
Some of the goals of the RED bu er management are:
1. A omodate short bursts that might be delay sensitive, but not to allow the average queue
size in rease too mu h. Using some low past ltering of the queue size, the aim is to dete t
ongestion that lasts long enough.
2. Drop tail and random drop gateways have a bias against bursty tra . Indeed in su h
bu ers, the more a tra of a onne tion is bursty, the more likely it is that the queue will
over ow during the arrival time of pa kets of that onne tion.
3. Avoid syn hronization: in drop tail bu er, many onne tions may re eive a ongestion signal
at the same time leading to undesirable os illations in the throughputs. Su h os illation
may ause lower average throughputs and high jitter. To avoid syn hronization, ongestions
signals are hosen using radomization.
4. Control the average queue size. Note that this also means ontrolling the average queueing
delay.
To a hieve these obje tives, RED monitors the average queue size avg, and he ks whether
it lies between some minimum threshold minth and a maximum threshold maxth . If it does,
then an arriving pa ket is dropped or marked with probability p = p(avg) whi h is an in reasing
fun tion of the average queue size. All arriving pa kets that arrive when avg ex eeds maxth are
marked/dropped.
The probability p(avg) is hosen as follows. As the average queue size varies between minth
and maxth , a probability pb varies linearly between 0 and some value maxp , i.e.

avg minth
:
maxth minth
This probability is used as p(avg) if at the arrival of the previous pa ket, avg  minth. Otherwize
p(avg) is set to the value p(avg)=(1 + p(avg)).
pb (avg) = maxp

71

72

CHAPTER 6.

RED: RANDOM EARLY DISCARD

The average queue size is monitored as follows. The avg paremater is intially set to zero. Then
with ea h arriving pa ket, the new value avg is assigned the value
(1 wq )avg + wq q
where q is the a tual queue size and wq is some small onstant. If the queue be omes empty some
other formula is used to update its size, whi h takes into a ount the time sin e it be ame empty
and an estimate on the number of pa kets that ould have been sent during this idle time, see
[16. For estimating the latter, we shall need in ns to give as parameter a rough estimation of the
mean pa ket size.
Examples of RED parameters studied in [16 are wq = 0:002, minth = 5pa kets, maxth =
15pa kets, maxp = 1=50 and the queue size is 100. More generally they also investigate minth
ranging between 3 to 50, and keep maxth = 3minth.
The implementation of red in ns an be found in ns-allinone-2.XXX/ns-2.XXX/queue/red.
(XXX stands for the version, e.g. 1b9a).

6.2 Setting RED parameters in ns


The parameters of RED in ns are provided in the following obje ts:
1. bytes_: takes either the value "true" if we work in the "byte mode" or "false" in the pa ket
mode (the default value). In the "byte mode", the size of an arriving pa ket a e ts the
likelihood of marking it.
2. queue-in-bytes_: the average queue size will be measured in bytes if this is set to "true".
In that ase, also thresh_ and maxthres_ are s aled by the estimated average pa ket size
parameter mean_pktsize_. It is "false" by default.
3. thres_: is the minimum queue size threshold minth.
4. maxthres_: is the maximum queue size threshold maxth .
5. mean_pktsize_: is the estimate of the average pa ket size in bytes. The default value is 500.
6. q_weight_: the weight fa tor wq in omputing the averaged queue length.
7. wait_: This is a parametter that allows to maintain an interval between dropped pa kets
when set to "true" (the default value).
8. linterm_: This is the resipro al of maxp . Its default value is 10.
9. setbit_: is "false" in the ase that RED is used to a tually drop pa kets, and is "true" if
RED marks the pa ket with a ongestion bit, instead. (The ECN version of TCP rea ts to
these ongestion bits).
10. drop-tail_: This is a parameter that allows, when setting its value to "true" (the default
value), to use the drop-tail poli y when queue over ows or when the average queue size
ex eeds maxth .
The default values of q_weight_, maxthresh_ and thres_ have been 0.002, 15 and 5 respe tively till end 2001. In the more re ent releases they a on gured automati ally.
RED has other paramters and variants that are implemented in ns. In parti ular, S. Floyd
re ommends in http://www.i ir.org/ oyd/red/gentle.html for the best behavior of RED (in simulations and in implementations), to use the gentle_ parameter set to "true" (this is the default

6.3.

73

SIMULATION EXAMPLES

sin e April, 2001). In the gentle_ modi ation to RED in ns, the pa ket-dropping probability
varies from maxp to 1 as the average queue size varies from maxthresh_ to twi e maxthresh_.
This option makes RED mu h more robust to the setting of the parameters maxthresh and max_p.
Another version is the adaptive RED that adapts the hoi e of parameters to the network
tra , as des ribed in [17.
In order to monitor a given red bu er, say one between nodes $n2 and $n3, one an type
set redq [[$ns link $n2 $n3 queue
set tra eq [open red-queue.tr w
$redq tra e urq_
$redq tra e ave_
$redq atta h $tra eq

Here urq_ is the urrent queue value and ave_ is the averaged value. This gives an output le
(in our ase "red-queue.tr") with three olumns. The rst indi ates whether it is a value of the
urrent queue size (by using the ag "Q") or the averaged queue size (using the ag "a"). Then
omes the urrent time and nally the monitored value.

6.3 Simulation examples


We onsider the following network, depi ted at Figure 6.1: We shall ompare the behavior of
2

Figure 6.1: Network setting for the study of RED


several queue management s hemes.

6.3.1 Drop tail bu er


The rst bu er management s heme is a simple drop tail me hanism. We onsider three input
links with delay 1mse ea h and bandwidth of 10Mbps ea h. The ommon bottlene k link has
20mse of delay and bandwidth of 700 kbps. We onsider three FTP onne tions using TCP and
set the maximum window sizes to 8000. The bottlene k queue size is 100. The three onne tions
start at random times, uniformly distributed between 0 and 7 se . There delay till the bottlene k
is 1mse . We hose a TCP pa ket size of 552 bytes. Note: in version 2.1b9a of ns, when we type
the ommand
$t p_sr ($j) set pa ketSize_ 552

then the a tual pa ket size reated in the simulation is 592, sin e an extra 40 bytes of header are
added. The whole simulation lasts 50 se .
Using the monitor-queue option that we saw already in Se tion 4.3, we reate a le alled
queue.tr whose rst olumn is the time and the fth olumn is the queue size in pa kets. We
shall also use a pro edure, alled plotWindow, to monitor the window sizes: it reates a le where

74

CHAPTER 6.

RED: RANDOM EARLY DISCARD

the rst olumn is time, and the other three olumns orrespond to the window sizes of the three
onne tions.

6.3.

SIMULATION EXAMPLES

75

set ns [new Simulator


set nf [open out.nam w
$ns namtra e-all $nf
set
set
set
$ns

tf [open out.tr w
windowVsTime [open win w
param [open parameters w
tra e-all $tf

#Define a 'finish' pro edure


pro finish {} {
global ns nf tf
$ns flush-tra e
lose $nf
lose $tf
exe nam out.nam &
exit 0
}
#Create bottlene k and dest nodes
set n2 [$ns node
set n3 [$ns node
#Create links between these nodes
$ns duplex-link $n2 $n3 0.7Mb 20ms DropTail
set NumbSr 3
set Duration 50
#Sour e nodes
for {set j 1} {$j<=$NumbSr } { in r j } {
set S($j) [$ns node
}
# Create a random generator for starting the ftp and for bottlene k link delays
set rng [new RNG
$rng seed 2
# parameters for random variables for begenning of ftp onne tions
set RVstart [new RandomVariable/Uniform
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng
#We define random starting times for ea h onne tion
for {set i 1} {$i<=$NumbSr } { in r i } {
set startT($i) [expr [$RVstart value
set dly($i) 1
puts $param "startT($i) $startT($i) se "
}

76

CHAPTER 6.

RED: RANDOM EARLY DISCARD

#Links between sour e and bottlene k


for {set j 1} {$j<=$NumbSr } { in r j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 20
}
#Set Queue Size of link (n2-n3) to 100
$ns queue-limit $n2 $n3 100
#TCP Sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
set t p_sr ($j) [new Agent/TCP/Reno
$t p_sr ($j) set window_ 8000
}
#TCP Destinations
for {set j 1} {$j<=$NumbSr } { in r j } {
set t p_snk($j) [new Agent/TCPSink
}
#Conne tions
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns atta h-agent $S($j) $t p_sr ($j)
$ns atta h-agent $n3 $t p_snk($j)
$ns onne t $t p_sr ($j) $t p_snk($j)
}
#FTP sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
set ftp($j) [$t p_sr ($j) atta h-sour e FTP
}
#Parametrisation of TCP sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
$t p_sr ($j) set pa ketSize_ 552
}
#S hedule events for the FTP agents:
for {set i 1} {$i<=$NumbSr } { in r i } {
$ns at $startT($i) "$ftp($i) start"
$ns at $Duration "$ftp($i) stop"
}

6.3.

SIMULATION EXAMPLES

pro plotWindow {t pSour e file k} {


global ns NumbSr
set time 0.03
set now [$ns now
set wnd [$t pSour e set wnd_
if {$k == 1} {
puts -nonewline $file "$now \t $ wnd \t"
} else {
if {$k < $NumbSr } {
puts -nonewline $file "$ wnd \t" }
}
if { $k == $NumbSr } {
puts -nonewline $file "$ wnd \n" }
$ns at [expr $now+$time "plotWindow $t pSour e $file $k" }
# The pro edure will now be alled for all t p sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns at 0.1 "plotWindow $t p_sr ($j) $windowVsTime $j"
}
set qfile [$ns monitor-queue $n2 $n3 [open queue.tr w 0.05
[$ns link $n2 $n3 queue-sample-timeout;
$ns at [expr $Duration "finish"
$ns run

Table 6.1: t l s ript drprail.t l

77

78

CHAPTER 6.

RED: RANDOM EARLY DISCARD

During the 50 se of simulation time, the sour e re eived 7211 TCP pa kets. Next we plot the
queue size (Fig. 6.2) and the window size (Fig. 6.3).
100
90
80
70
60
50
40
30
20
10
0

200
180
160
140
120
100
80
60
40
20
0

queue.tr using 1:5


0 5 10 15 20 25 30 35 40 45 50

Figure 6.2: Queue size evolution

win using 1:2


win using 1:3
win using 1:4

0 5 10 15 20 25 30 35 40 45 50

Figure 6.3: Window size of all TCP onne tions

We see from the gures that there is a high level of syn hronization between the window sizes:
they all lose pa kets at the same time. Moreover, we have high os illationos of the queue sizes
that orrespond to those of the windows, and the average queue size is around 75 pa kets. This
means that there is an additional average queueing delay whi h equals

Dq =

75  592  8
= 507:42mse
700  103

Remark 6.3.1 The drop-tail queue an be simulated using a RED bu er with minth = maxth
set on the maximum queue size and maxp set to a value lose to zero. This allows us to use
the monitoring tools for the instantaneous and average queue length of RED. Of ourse, the
drop-tail_ parameter has have the value "true".

6.3.2 RED bu er with automati parameter on guration


We run a se ond simulation with the same parmaeters. Note that we hoose for the ranndom
delay a seed 2 in all the simulations sin e unlike the seed 0, it will gurantee the same random
parameters are used in all simulations.
During the 50 se of simulation time, the sour e re eived 7310 TCP pa kets, slightly more than
with the drop tail ase (where we had 7211 pa kets). Next we plot the queue size (Fig. 6.4 and
6.5) and the window size (Fig.6.6).
We see from the gures that there is no syn hronization between the window sizes, and that
the average queue size is mu h lower than in the drop tail ase: it is around 10 (instead of 75 in
the drop tail ase). Thus the average delay of the onne tions thus also smaller, it is

Dq =

10  592  8
= 67:66mse :
700  103

We observe that instead of the large os illations of the queue size and the window sizes, we now
get mu h faster and smaller variationsn in both window size as well as queue size. We nally
noti e that during the simulation, the queue never over owed, unlike the ase of drop tail. Yet
RED did allow the queue to grow very mu h during the transient spike at the beginning of the
onne tion, whi h shows that short bursts are indeed not penalized with RED.
We provide in Table 6.2 the t l s ript we used.

6.3.

79

SIMULATION EXAMPLES

70

14
ave.tr using 2:3
cur.tr using 2:3

60

12

50

10

40

30

20

10

0
0

10

15

20

25

30

35

40

45

50

ave.tr using 2:3


cur.tr using 2:3
10

15

20

25

30

Figure 6.4: Current and Average queue size evo- Figure 6.5: Current and Average queue size evolution
lution: a zoom

14
win using 1:2
win using 1:3
win using 1:4

12
10
8
6
4
2
0
8

10

12

14

16

18

20

Figure 6.6: Window size of all TCP onne tions for Red bu er with automati parameter on guration

80

CHAPTER 6.

RED: RANDOM EARLY DISCARD

set ns [new Simulator


set nf [open out.nam w
$ns namtra e-all $nf
set
set
set
$ns

tf [open out.tr w
windowVsTime [open win w
param [open parameters w
tra e-all $tf

#Define a 'finish' pro edure


pro finish {} {
global ns nf tf
$ns flush-tra e
lose $nf
lose $tf
exe nam out.nam &
exe grep "a" red-queue.tr > ave.tr
exe grep "Q" red-queue.tr > ur.tr
exit 0
}
#Create bottlene k and dest nodes
set n2 [$ns node
set n3 [$ns node
#Create links between these nodes
$ns duplex-link $n2 $n3 0.7Mb 20ms RED
set NumbSr 3
set Duration 50
#Sour e nodes
for {set j 1} {$j<=$NumbSr } { in r j } {
set S($j) [$ns node
}
# Create a random generator for starting the ftp and for bottlene k link delays
set rng [new RNG
$rng seed 2
# parameters for random variables for begenning of ftp onne tions
set RVstart [new RandomVariable/Uniform
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng

6.3.

SIMULATION EXAMPLES

#We define random starting times for ea h onne tion


for {set i 1} {$i<=$NumbSr } { in r i } {
set startT($i) [expr [$RVstart value
set dly($i) 1
puts $param "startT($i) $startT($i) se "
}
#Links between sour e and bottlene k
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 20
}
#Set Queue Size of link (n2-n3) to 100
$ns queue-limit $n2 $n3 100
set redq [[$ns link $n2 $n3 queue
set tra eq [open red-queue.tr w
$redq tra e urq_
$redq tra e ave_
$redq atta h $tra eq
#TCP Sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
set t p_sr ($j) [new Agent/TCP/Reno
$t p_sr ($j) set window_ 8000
}
#TCP Destinations
for {set j 1} {$j<=$NumbSr } { in r j } {
set t p_snk($j) [new Agent/TCPSink
}
#Conne tions
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns atta h-agent $S($j) $t p_sr ($j)
$ns atta h-agent $n3 $t p_snk($j)
$ns onne t $t p_sr ($j) $t p_snk($j)
}
#FTP sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
set ftp($j) [$t p_sr ($j) atta h-sour e FTP
}
#Parametrisation of TCP sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
$t p_sr ($j) set pa ketSize_ 552
}

81

82

CHAPTER 6.

RED: RANDOM EARLY DISCARD

#S hedule events for the FTP agents:


for {set i 1} {$i<=$NumbSr } { in r i } {
$ns at $startT($i) "$ftp($i) start"
$ns at $Duration "$ftp($i) stop"
}
pro plotWindow {t pSour e file k} {
global ns NumbSr
set time 0.03
set now [$ns now
set wnd [$t pSour e set wnd_
if {$k == 1} {
puts -nonewline $file "$now \t $ wnd \t"
} else {
if {$k < $NumbSr } {
puts -nonewline $file "$ wnd \t" }
}
if { $k == $NumbSr } {
puts -nonewline $file "$ wnd \n" }
$ns at [expr $now+$time "plotWindow $t pSour e $file $k" }
# The pro edure will now be alled for all t p sour es
for {set j 1} {$j<=$NumbSr } { in r j } {
$ns at 0.1 "plotWindow $t p_sr ($j) $windowVsTime $j"
}
$ns at [expr $Duration "finish"
$ns run

Table 6.2: t l s ript red.t l

6.4.

83

MONITORING FLOWS

6.3.3 RED bu er with other parmaters


Suppose we wish to de ne our own parameters for RED rather than use the default ones. For
example, assume we wish to have in our previous example max_{th}=60, min_{th}=40 and
q_weight_=0.02. Then we should add the ommands
Queue/RED set thresh_ 60
Queue/RED set maxthresh_ 80
Queue/RED set q_weight_ 0.002

Important note: these ommands should be put at the beginning, before the links are de ned!
The resulting window and queue size pro esses are given in Figures 6.8 and 6.7 respe tively.
100
ave.tr using 2:3
cur.tr using 2:3
80

60

40

20

0
0

10

15

20

25

30

35

40

45

50

200
180
160
140
120
100
80
60
40
20
0

win using 1:2


win using 1:3
win using 1:4

0 5 10 15 20 25 30 35 40 45 50

Figure 6.7: Current and Average queue size evolution


Figure 6.8: Window size of all TCP onne tions
for Red bu er
Note that with the parameters that we hose, the queue lengths are kept aroud an average of
50. The number of TCP pa kets re eived during the simulation was 7212.

6.4 Monitoring ows


We introdu e in this se tion the ow monitor, whi h is an e ient way to monitor per- ow
quantities su h as losses and amount of transmitted tra . We shall modify the ns s ript of
shortT p2.t l (Table 4.4) to in lude a RED bu er with monitoring.
A ow monitors a simplex link, so we rst de ne the link we wish to monitor: be de ned, e.g.
set flink [$ns simplex-link $N $D 2Mb 1ms RED

and then the ow-monitor is de ned as follows with respe t to this link:
set monfile [open mon.tr w
set fmon [$ns makeflowmon Fid
$ns atta h-fmon $flink $fmon
$fmon atta h $monfile

When we a tivate the monitoring, we get the statisti s up to the a tiviation time in a le. This is
done as follows:
$ns at $time "$fmon dump"

We next present in Table 6.3 the full s ript shortRed.t l that allows us to study short TCP
sessions intera ting with a RED bu er.

84

CHAPTER 6.

RED: RANDOM EARLY DISCARD

set ns [new Simulator


# There are several sour es ea h generating many TCP sessions sharing a bottlene k
# link and a single destination. Their number is given by the paramter NodeNb
#
#
#
#
#

S(1)
.
.
.
S(NodeNb)

set
set
set
$ns

---|
----N --------------- D
|
----

Out [open Out.ns w; # file ontaining transfer times of different onne tions
Conn [open Conn.tr w; # file ontaining the number of onne tions
tf [open out.tr w;
#Open the Tra e file
tra e-all $tf

set NodeNb
6; # Number od sour e nodes
set NumberFlows 253; # Number of flows per sour e node
set sduration
50; # Duration of simulation
#
#
#
#
#

When the following parameters are ommented, the RED is


onfigured automati ally.
Queue/RED set thresh_ 5
Queue/RED set maxthresh_ 15
Queue/RED set q_weight_ 0.002

# defining the topology


set N [$ns node
set D [$ns node
set flink [$ns simplex-link $N $D 2Mb 1ms RED
$ns simplex-link $D $N 1Mb 1ms DropTail
$ns queue-limit $N $D 50
# queue monitoring, RED
set redq [[$ns link $N $D queue
set tra eq [open red-queue.tr w
$redq tra e urq_
$redq tra e ave_
$redq atta h $tra eq
#Nodes and links
for {set j 1} {$j<=$NodeNb} { in r j } {
set S($j) [$ns node
$ns duplex-link $S($j) $N 100Mb 1ms DropTail
$ns queue-limit $S($j) $N 100
}

6.4.

MONITORING FLOWS

85

# set flow monitor


set monfile [open mon.tr w
set fmon [$ns makeflowmon Fid
$ns atta h-fmon $flink $fmon
$fmon atta h $monfile
#TCP Sour es, destinations, onne tions
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
set t psr ($i,$j) [new Agent/TCP/Newreno
set t p_snk($i,$j) [new Agent/TCPSink
set k [expr $i*1000 +$j;
$t psr ($i,$j) set fid_ $k
$t psr ($i,$j) set window_ 2000
$ns atta h-agent $S($i) $t psr ($i,$j)
$ns atta h-agent $D $t p_snk($i,$j)
$ns onne t $t psr ($i,$j) $t p_snk($i,$j)
set ftp($i,$j) [$t psr ($i,$j) atta h-sour e FTP
} }
# Generators for random size of files.
set rng1 [new RNG
$rng1 seed 0
set rng2 [new RNG
$rng2 seed 0
# Random inter-arrival times of TCP transfer at ea h sour e i
set RV [new RandomVariable/Exponential
$RV set avg_ 0.3
$RV use-rng $rng1
# Random size of files to transmit
set RVSize [new RandomVariable/Pareto
$RVSize set avg_ 10000
$RVSize set shape_ 1.5
$RVSize use-rng $rng2
# We now define the beginning times of transfers and the transfer sizes
# Arrivals of sessions follow a Poisson pro ess.
#
for {set i 1} {$i<=$NodeNb} { in r i } {
set t [$ns now
for {set j 1} {$j<=$NumberFlows} { in r j } {
# set the beginning time of next transfer from sour e and attributes
set t [expr $t + [$RV value
$t psr ($i,$j) set starts $t
$t psr ($i,$j) set sess $j
$t psr ($i,$j) set node $i
$t psr ($i,$j) set size [expr [$RVSize value
$ns at [$t psr ($i,$j) set starts "$ftp($i,$j) send [$t psr ($i,$j) set size"
# update the number of flows
$ns at [$t psr ($i,$j) set starts " ountFlows $i 1"
}}

86

CHAPTER 6.

RED: RANDOM EARLY DISCARD

for {set j 1} {$j<=$NodeNb} { in r j } {


set Cnts($j) 0
}
# The following pro edure is alled whenever a onne tion ends
Agent/TCP instpro done {} {
global t psr NodeNb NumberFlows ns RV ftp Out t p_snk RVSize
# print in $Out: node, session, start time, end time, duration,
# trans-pkts, transm-bytes, retrans-bytes, throughput
set duration [expr [$ns now - [$self set starts
puts $Out "[$self set node \t [$self set sess \t [$self set starts \t\
[$ns now \t $duration \t [$self set ndatapa k_ \t\
[$self set ndatabytes_ \t [$self set nrexmitbytes_ \t\
[expr [$self set ndatabytes_/$duration "
ountFlows [$self set node 0
}
# The following re ursive pro edure updates the number of onne tions
# as a fun tion of time. Ea h 0.2 it prints them into $Conn. This
# is done by alling the pro edure with the "sign" parameter equal
# 3 (in whi h ase the "ind" parameter does not play a role). The
# pro edure is also alled by the "done" pro edure whenever a onne tion
# from sour e i ends by assigning the "sign" parameter 0, or when
# it begins, by assigning it 1 (i is passed through the "ind" variable).
#
pro ountFlows { ind sign } {
global Cnts Conn NodeNb
set ns [Simulator instan e
if { $sign==0 } { set Cnts($ind) [expr $Cnts($ind) - 1
} elseif { $sign==1 } { set Cnts($ind) [expr $Cnts($ind) + 1
} else {
puts -nonewline $Conn "[$ns now \t"
set sum 0
for {set j 1} {$j<=$NodeNb} { in r j } {
puts -nonewline $Conn "$Cnts($j) \t"
set sum [expr $sum + $Cnts($j)
}
puts $Conn "$sum"
$ns at [expr [$ns now + 0.2 " ountFlows 1 3"
} }
pro finish {} {
global ns tf
$ns flush-tra e
lose $tf
exe grep "a" red-queue.tr > ave.tr
exe grep "Q" red-queue.tr > ur.tr
exit 0
}
$ns at 0.5 " ountFlows 1 3"
$ns at [expr $sduration - 0.01 "$fmon dump"
$ns at $sduration "finish"
$ns run

Table 6.3: t l s ript shortRed.t l

6.4.

MONITORING FLOWS

87

The ow monitor le in ludes more detailed information on the drop type. It allows to distinguish between Early drops (ED) due to early dis ard of pa kets, and a tual drops due to bu er
overvlow. The le has the following format:
1. Column 1: the time at whi h "dump" was performed.
2. Columns 2 and 5: both give the ow id.
3. Column 3: null (a zero entry).
4. Column 4: ow type.
5. Columns 6 and 7: sour e and destination of the ow.
6. Columns 8 and 9: total number of arrivals of the ow in pa kets and in bytes, respe tively.
7. Columns 10 and 11: amount of early drops of the ow in pa kets and in bytes, respe tively.
8. Columns 12 and 13: total number of arrivals of all ows in pa kets and in bytes, respe tively.
9. Columns 14 and 15: amount of early drops of all ows in pa kets and in bytes, respe tively.
10. Columns 16 and 17: total amount of drops of all ows in pa kets and in bytes, respe tively.
11. Columns 18 and 19: total amount of drops of the parti ular ow in pa kets and in bytes,
respe tively.
Note: in order to apply the ow monitor, ea h TCP onne tion that we wish to monitor should
have a ow id. In our ase, we initially identnify a ow by its number and its sour e node (e.g.
the third TCP onne tion that starts at node 4). We transform this into a one dimensional ve tor
as follows:
set k [expr $i*1000 +$j;
$t psr ($i,$j) set fid_ $k

The simulation produ ed the following output les:


1. ur.tr and ave.tr that monitor the evolution of the queue size and its averaged version;
2. Conn.tr for monitoring the number of a tive onne tions from ea h of the six sour es (the
number six is given as parameter in the s ript to the variable NumberFlows) as well as the
sum of a tive sessions, as a fun tion of time
3. Out.ns for monitoring for ea h session (identi ed with the sour e node and the session
number originating from that node), start time, end time and duration of the onne tion,
the number of transmitted pa kets, transmitted bytes and retransmitted bytes, and the
throughput experien ed by the session.
4. mon.tr is the tra e produ ed by the ow monitor, that ontains number of transmitted
pa kets and bytes and number of losses per onne tion.
5. out.tr is the global tra e of all events.
We used in the above s ript with the RED version withi automati on guration. We plot the
queue size and its averaged dynami s in Fig. 6.9-6.10. We see that the queue length pro ess is
mu h more bursty and variable than in the ase of persistant TCP onne tions (whi h we saw in
Fig. 6.4 and 6.5). The number of a tive onne tion is given in Fig. 6.11.

88

CHAPTER 6.

50

RED: RANDOM EARLY DISCARD

50
ave.tr using 2:3
cur.tr using 2:3

45

ave.tr using 2:3


cur.tr using 2:3

45

40

40

35

35

30

30

25

25

20

20

15

15

10

10

0
0

10

15

20

25

30

35

40

45

50

Figure 6.9: Evolution of the queue size and of its


average

16

18

20

22

24

Figure 6.10: Queue size and averaged size evolution: a zoom

25
Conn.tr using 1:8
20
15
10
5
0
0

5 10 15 20 25 30 35 40 45 50

Figure 6.11: Number of a tive onne tions as a fun tion of time


We in luded in the above s ript various ways of monitoring. The dire t way of monitoring the
number of retransmissions and arrivals of pa kets through the pro edure "done" has the is global:
it gives all the data related to the onne tion. The ow monitor gives on the other hand lo al
information on losses at a parti ular link. If the onne tion traverses several bottlene k links, the
rst method is thus more advantageous. The se ond method has the advantage of giving more
detayled lo al information whi h an be useful to understand the ontribution of ea h of several
nodes to ongestion su ered by a session.

6.5 Exer ises


Exer ise 6.5.1 Consider the s ript shortRed.t l (Table 6.3) and modify the program to have manual adjustment of the parameters thresh_, maxthresh_, q_weight_. How should these parameters, as well as the queue size on link N -D be hosen so as to maximize the throughput? Study
this by simulation and explain the tradeo s.
Exer ise 6.5.2 One of the obje tives of RED is to allow more fairness to short bursts. Analyze
the throughput and the loss probability of a onne tion as a fun tion of its size with RED and
ompare it to Drop-Tail. Use the s ript shortRed.t l (Table 6.3). Try various parameters for RED
to get better fairness. The exer ise is based on [2.

Chapter 7

Di erentiated Servi es
In traditional Internet, all onne tions get the same treatment in the network. This is in ontrast
with other networking on epts, su h as the ATM (Asyn hronous Transfer Mode), that an o er
quality of servi e requirements to onne tions at the pri e of mu h higher signalling and pro essing related to the a eptan e of new onne tions and maintaining the guarantees of ongoing
onne tions. Moreover, sin e network resour es are limitted, o ering guarantees on performan e
measures requires to reje t new onne tions if resour es are not available. This is in ontrast with
the best e ort nature of todays the Internet where no admission ontrol is performed.
Yet, it has been re ognized it is important to di erentiate between onne tion lasses and to
be able to allo ate resour es to onne tions a ording to their lass. Thus a subs riber that is
willing to pay more ould bene t of smaller delays and larger throughputs. This is in parti ular
of interest for real time appli ations over the Internet (voi e, video).
For that reason, the Di serv has been introdu ed. It is based on marking pa kets at the edge
of the network a ording to the performan e level that the network wishes to provide them; then
a ording to the marks, the pa kets are treated di erently at the network's nodes. A ommon way
to di erentiate pa kets is by using RED bu ers using di erent parameters for di erent pa kets.
The ns module that handles di serv has been developed in Nortel Networks, and this Chapter
is based in large part on the ex ellent Nortel Report [32.

7.1 Des ription of assured forwarding Di serv


The Di serv implemented in ns follows the \Assured forwarding" approa h standardized in [19.
A pa ket belonging to a ow may re eive three possible priority levels within the ow. These
are alled sometime "drop pre eden es". This an be used, for example to provide a lower loss
probability to syn pa kets in a TCP onne tion, sin e unlike other pa kets, the losses of syn
pa kets result in very long time-outs [27. In addition to di erentiation within ea h ow, all ows
are lassi ed to several lasses (at most four), and di erent treatment an be given to the di erent
lasses.
Moreover, it is possible to di erentiate between ows. Four lasses of ows are de ned, and
pa kets of a given lass are queued in a lass-dependent queue. In order to di erentiate between
pa kets belonging to the same lass, three virtual queues are implemented in ea h of the four
queues. To ea h of the 12 ombinations of the four ow lass and the three internal priority levels
within a ow orrespond a ode point that a pa ket is given when entering the network. In pra tive
not all queues and all priority groups need to be implemented.
Di serv ar hite ture has three omponents:
1. Poli y and resour e manager: it reates poli ies and distributes them to di serv routers. A
89

90

CHAPTER 7.

DIFFERENTIATED SERVICES

poli y determines whi h level of servi es in the network are assigned to whi h pa kets. This
assignment may depend on the behavior of the sour e of the ow (e.g. its average rate and
its burstiness) and spe ial network elements are therefore added at the edge of the network
so as to measure the sour e behavior. In ns simulation, the poli y is fully determined in the
t l s ript.
2. Edge routers: are responsible to assign the ode points to the pa kets a ording to the poli y
spe i ed by the network administrator. To do so they measure parameters of the input tra
of ea h ow.
3. Core routers: the basi approa h of di serv is to keep the intelligen e in the edge of the
network; routers within the network have simply to assign the appropriate priority to pa kets
a ording to their ode mark. The priority translates to parameters of the s heduling and
of the dropping de isions in the ore routers.

7.2 MRED routers


7.2.1 General des ription
The fa t that there are three virtual RED bu ers ( alled MRED - Multi RED) in ea h physi al
queue allows to enhan e its behavior and to reate dependen e between their operation. One way
to do that is through the RIO C (Rio Coupled) version of MRED, in whi h the probability of
dropping low priority pa kets ( alled "out-of-pro le pa kets") is based on the weighted average
lengths of all virtual queues, whereas the probability of dropping a high priority ("in-pro le")
pa ket is based only on the weighted average length of its own virtual queue.
In ontrast, in RIO-D (RIO De- oupled) the probability of dropping ea h pa ket is based on the
size of its virtual queue. Another version is the WRED (Weighted Red) in whi h all probabilities
are based on a single queue length [8. It is possible to use also the dropTail queue.

7.2.2 Con guration of MRED in ns


To determine the number of physi al queues, we use the ommand
$dsredq set numQueues_ $m

where m an take values between 1 and 4.


Con guring queue 0 to be a RIO-C is done with the ommand
$dsredq setMREDMode RIO-C 0

If the last argument is not given then all queues are set to be RIO-C. Similarly, types other than
RIO-C an be de ned. To spe ify the number $n of virtual queues, we use the ommand:
$dsredq setNumPre $n

Red parameters are then ongidured using the ommand


$dsredq onfigQ $queueNum $virtualQueueNum $minTh $maxTh $maxP

It thus has 5 parameters: the queue number, virtual queue number, minth, maxth and maxp . The
parameter qw an also be given (as the 6th parmaeter) and if it is not stated then it is taken to
be 0.002 by default.
The droptail queue an also be used with the ommand

7.3.

DEFINING POLICIES

91

$dsredq setMREDMode DROP

The on guation then is given as before with only the rst three parameters:
$dsredq onfigQ $queueNum $virtualQueueNum $minTh

All arriving pa kets are dropped when the minth value is rea hed.
As we saw in the hapter on RED, for omputing the drop probability we need an estimate of
the pa ket size. For a pa ket of size 1000 bytes this ommand is given by the ommand
$dsredq meanPktSize 1000

S heduling Parti ular s heduling regimes an be de ned. for example the weighted round robin
with queue weights 5 and 1 respe tively will be de ned through
$dsredq setS hedularMode WRR
$dsredq addQueueWeights 1 5

Other possible s heduling are Weighted Interleaved Round Robin (WIRR), Round Robin (RR)
whi h is the default s heduling, and the stri t priorities (PRI).

PHB table The set of four queues along with the virtual queues is supplemented with a PHB

(Per Hop Behavior) table. Its entries are de ned by (i) the ode point (ii) the lass (physi al
queue) and (iii) the "pre eden e" (virtual queue). An entry is assigned with the ommand of the
form
$dsredq addPHBEntry 11 0 1

whi h means that ode point 11 is mapped to the virtual queue 1 of the physi al queue 0.

7.2.3 TCL querying


The following three ommands result in pringing respe tively (i) the PHB table, (ii) the number
of physi al and virtual queues and (iii) the RED weighted average size of the spe i ed physi al
queues (0 in our ase):
$dsredq printPHBTable
$dsredq printStats
$dsredq getAverage 0

7.3 De ning poli ies


7.3.1 Des ription
All ows having the same sour e and destination are subje t to a ommon poli y. A poli y de nes
a poli er type, a target rate, and other poli y spe i parameters. It spe i es at least two ode
points. The hoi e between them depends on the omparison between the ow's target and its
urrent sending rate, and possibly on the poli y-dependent parmaeters (su h as burstiness). The
poli y spe i es meter types that are used for measuring the relevant input tra parameters. A
pa ket arriving at the edge devi e auses the meter to update the state variables orresponding
to the ow, and the pa ket is then marked a ording to the poli y. The pa ket has an initial
ode point orresponding to the required servi e level; the marking an result in downgrading the
servi e level with respe t to the initial required one.
A poli y table is used in ns to store the poli y type of ea h ow. Not all entries are a tually
used. The entries are

92

CHAPTER 7.

DIFFERENTIATED SERVICES

1. Sour e node ID
2. Destination node ID
3. Poli er type
4. Meter type
5. Initial ode point
6. CIR ( ommitted information rate)
7. CBS ( ommitted burst size)
8. C bu ket ( urrent size of the ommitted bu ket)
9. EBS (ex ess burst size)
10. E bu ket ( urrent size of the ex ess bu ket)
11. PIR (peak information rate)
12. PBS (peak burst size)
13. P bu ket ( urrent size of the peak bu ket)
14. Arrival time of last pa ket
15. Average sending rate
16. TSW window length (TSW is a poli er based on average transmission rates and the averaging
is performed over the window length, in se onds, of data). The default value is 1se .
The following are the possible poli er types:
1. TSW2CM (TSW2CMPoli er): uses a CIR and two drop pre eden es. The lower one is
used probabilisti ally when the CIR is ex eeded.
2. TSW3CM (TSW3CMPoli er) [15: uses a CIR, a PIR and three drop pre eden es. The
medium priority level is used probabilisti ally when the CIR is ex eeded, and the lowest one
is used probabilisti ally when the PIR is ex eeded.
3. Token Bu ket (TokenBu ketPoli er): uses CIR and a CBS, and two drop pre eden es.
4. Single Rate Three Color Marker (srTCMPoli er) [21: uses CIR, CBS and EBS to
hoose from three drop pre eden es.
5. Two Rate Three Color Marker (trTCMPoli er) [21: uses CIR, CBS, EBS and PBS
to hoose from three drop pre eden es.
Ea h of the above poli er type de nes the meter it uses. A poli er table de nes for ea h poli y
type the initial ode point as well as one or two downgraded ode points. The initial ode point is
often alled "green ode" and the lowest downgraded ode is "red". If there is another ode point
inbetween, it is alled "yellow".

7.4.

SIMULATION OF DIFFSERV: PROTECTION OF VULNERABLE PACKETS

93

7.3.2 Con guration


To update the poli y table, the "addPoli yEntry" ommand is used whi h ontains the edge queue
variable denoting the edge queue, the sour e and destination nodes of the ow, the poli er type,
its initial ode point, and then the values of the parameters that it uses; these are some or all of
CIR, CBS, PIR and PBS as stated above. CIR and PIR are given in bps, and CBS, EBS and PBS
in bytes. An example is:
$edgeQueue addPoli erEntry [$n1 id [$n8 id trTCM 10 200000 1000 300000 1000

Here we added a poli y for the ow that originates in $n1 and ends at $n8. If the TSW poli ers
are used, one an add at the end the TSW window length. If not added, it is taken to be 1se by
default.
Then another "addPoli yEntry" ommand spe i to the poli y and to the initial ode point
(and not to a parti ular ow) de nes the downgraded ode points whi h are ommon to all ows
that use the poli y with the same initial ode point. An example is:
$edgeQueue addPoli erEntry srTCM 10 11 12

7.3.3 TCL querying


The following three ommands result in pringing respe tively (i) the entire poli y table, (ii) the
entire poli er table and (iii) the urrent size in bytes of the C bu kets:
$edgeQueue printPoli yTable
$edgeQueue printPoli erTable
$edgeQueue getBu ket

7.4 Simulation of di serv: prote tion of vulnerable pa kets


In TCP onne tions, the loss of some segments has more impa t than others on the performan e of
the onne tion. These segments are (i) the onne tion establishment segments, (ii) the segments
sent when the onne tion has a small window, and (iii) the segments sent after a timeout or a fast
retransmit. We all these "vulnerable" segments, or pa kets. In a re ent paper [27, the authors
show that by marking these segments with a higher priority and implementing the priority using a
di serv ar hite ture, the performan e of the TCP onne tion onsiderably improves. This marking
requires, however, that network layer elements be aware of transport layer information, i.e. of the
state of the TCP onne tion. The goal of the simulation example we introdu e is to show that one
an a hieve prioritization of sensitive segments without any use of transport layer information,
thus simplifying the implementation of di serv marking of TCP pa kets. This part is based on
[1.

7.4.1 The simulated s enario


Perliminaries on the servi e di erentiation Two priority levels are de ned. The higher

"In pa kets" or "green pa kets" and the lower "Out pa kets" or "red pa kets". We fo us on the
simplest poli er available in ns: the time-sliding window (TSW2CM). A CIR is de ned for ea h
edge router. As long as the onne tion's rate is below CIR, all pa kets are marked as high priority.
When the rate ex eeds CIR, pa kets are marked probabilisti ally su h that at the average, the rate
of pa kets marked with high priority orresponds to the CIR. The transmitted rate is omputed
as the rate averaged over the "TSW window"; in our simulation its duration is 20mse .
In our experimentations we vary the CIR level at the sour e edge nodes and study its impa t
on performan e.

94

CHAPTER 7.

DIFFERENTIATED SERVICES

The topology We onsnider the simple network topology with a signle bottlene k, depi ted in
Fig. 7.1.

Source
Node
Source
Node

Source
Node

Source
Node
Source
Node

Edge Node
Edge Node
11
00
00
11
00
11
00
11
00
11
00
11

Edge Node

Edge Node
11
00
00
11
00
11
00
11
00
11
00
11

Destination
Node

Core
Node
Edge Node
Edge Node

Figure 7.1: Network topology


Ea h sour e node is onne ted to a orresponding edge node where the tra is marked a ording to parameters that will be spe i ed. The edge routers are onne ted to a bottlene k
orerouter, and then through another edge router, to a destination node.
There are 20 sour e nodes, and ea h one of them generates TCP onne tions.
We experiment with a high-speed lo al area type network (short propagation delays) with
ompletely symetri links:

Links between the edge nodes and the orresponding sour e nodes have delays of 10 se
and 6Mbps bandwidth.

Links between the edge node and the orresponding destination node has 10 se delay and
10Mbps bandwidth.

Links between the ore node and edge nodes that are atta hed to the sour es have 0.1mse
delay and 6Mbps bandwidth.

The link between the ore node and edge node atta hed to the destination has 1mse delay
and 10Mbps bandwidth.

The tra model A transfered le has a Pareto distribution with shape parameter 1.25 and
an average size of 10kbytes (see [6, 35 for similar parameters).
Files to be transmitted arrive at ea h sour e node a ording to a Poisson pro ess with an
average rate of 5 les per se ond. Several sessions from the same sour e node an be a tive
simultaneously.
Queueing management parameters Queue an build up only at the bottlene k router, i.e.

at the link between the ore node and the edge node that onne ts to the destination. We hose
its size to be of 100 pa kets. Thus the qeueue management parameters at other nodes did not
have an in uen e on the results. In the bottlene k queue at the ore node, a multi-RED queue
management is used with a RIO-D version; we hoose the same parameters for both priority
levels (more details will be given below). Our aim in hoosing the parameters was not to obtain
ne essarily an optimal performan e but rather to reate onditions that allow us to study the
e e t of di serv on diminishing the loss probabilities of vulnerable segments, and the impa t

7.4.

SIMULATION OF DIFFSERV: PROTECTION OF VULNERABLE PACKETS

95

of this a tion on TCP performan e (delay, throughput). For that reason, we hoose the same
parameters for the two priority levels (this will be explained below).
For ea h olor of pa kets (red, green), the averaged queue sized is monitored (this is done using
the standard exponential averaging with parameter wq = 0:01). Pa kets of a given olor start to
be dropped when the averaged number of queued pa kets of this olor ex eeds minw ; we hoose
minw = 15; this drop probability in reases linearly with the averaged queue size until it rea hes
the value maxw = 45, where the drop probability is taken to be maxp = 0:5. When this value is
ex eeded, the drop probability is 1.
Note that often the di erentiation between the priorities is done using di erent sets of parameters: drops are performed at a larger queue size for green pa kets (e.g. [34). We prefer not to
use this approa h, sin e with reje tion at a larger window size we also get larger delays, whi h in
some experimented parameters result in a lower throughput for green pa kets than for red pa kets
and in global degradation of performan e! By giving the same parameters to both priorities, we
an learn about the dire t e e t of prote ting vulnerable pa kets on the TCP performan e. The
di erentiation is then done by using the RIO-D approa h, in whi h the reje tion probability of
ea h type of olor depends on the average number of pa kets of that type. Thus to have green
pa kets dropped less than red ones, we simply hoose their throughput (and onsequently also the
orresponding averge queue size) to be lower; this is done by the proper hoi e of the CIR value
whi h determines the fra tion of pa kets that will be marked green.
Simulations are 80se long. The rate of arrival of bits to the bottlene k is
20  1:04  104  8
= 7:563Mbps
0:22
This is obtained as follows: An average pa ket size is 1040 bytes of whi h 1000 are data and 40
bytes are an extra header. An average ftp le is assumed to ontain 104 104 bytes of data, whi h
means that its total average size (in luding the extra headers) is approximately 1:04  104  8 bits.
The result is obtained by multiplying by the number of sour e nodes and dividing by the average
time between arrivals of les at a node.
The ns s ript is given in Table 7.1.

96

CHAPTER 7.

DIFFERENTIATED SERVICES

set ns [new Simulator


# There are several sour es ea h generating many TCP sessions sharing a bottlene k
# link and a single destination. Their number is given by the paramter NodeNb
#
#
#
#
#
set
set
set
set
set
set

S(1) ----- E(1) ---.


|
.
---- E(i) ---Core---- Ed -------- D
.
|
S(NodeNb)- E(NodeNb) ir0
100000; # poli ing parameter
ir1
100000; # poli ing parameter
pktSize
1000
NodeNb
20; # Number of sour e nodes
NumberFlows 360 ; # Number of flows per sour e node
sduration 60 ; # Duration of simulation

#Define different olors for data flows (for NAM)


$ns olor 1 Blue
$ns olor 2 Red
$ns olor 3 Green
$ns olor 4 Brown
$ns olor 5 Yellow
$ns olor 6 Bla k
set Out [open Out.ns w;

# file ontaining transfer


# times of different onne tions
set Conn [open Conn.tr w; # file ontaining the number of onne tions
set tf [open out.tr w; # Open the Tra e file
$ns tra e-all $tf
#Open the NAM tra e file
set file2 [open out.nam w
# $ns namtra e-all $file2
# defining the topology
set D
[$ns node
set Ed [$ns node
set Core [$ns node

7.4.

set
$ns
$ns
$ns

SIMULATION OF DIFFSERV: PROTECTION OF VULNERABLE PACKETS

flink [$ns simplex-link $Core $Ed 10Mb 1ms dsRED/ ore


queue-limit $Core $Ed 100
simplex-link $Ed $Core 10Mb 1ms dsRED/edge
duplex-link $Ed $D 10Mb 0.01ms DropTail

for {set j 1} {$j<=$NodeNb} { in r j } {


set S($j) [$ns node
set E($j) [$ns node
$ns duplex-link $S($j) $E($j) 6Mb 0.01ms DropTail
$ns simplex-link $E($j) $Core 6Mb 0.1ms dsRED/edge
$ns simplex-link $Core $E($j) 6Mb 0.1ms dsRED/ ore
$ns queue-limit $S($j) $E($j) 100
}
#Config Diffserv
set qEdC
[[$ns link $Ed $Core queue
$qEdC
meanPktSize 40
$qEdC set numQueues_ 1
$qEdC
setNumPre
2
for {set j 1} {$j<=$NodeNb} { in r j } {
$qEdC addPoli yEntry [$D id [$S($j) id TSW2CM 10 $ ir0 0.02
}
$qEdC addPoli erEntry TSW2CM 10 11
$qEdC addPHBEntry 10 0 0
$qEdC addPHBEntry 11 0 1
$qEdC onfigQ 0 0 10 30 0.1
$qEdC onfigQ 0 1 10 30 0.1
$qEdC printPoli yTable
$qEdC printPoli erTable
set qCEd
[[$ns link $Core $Ed queue
# set qCEd
[$flink queue
$qCEd
meanPktSize $pktSize
$qCEd set numQueues_ 1
$qCEd set NumPre
2
$qCEd addPHBEntry 10 0 0
$qCEd addPHBEntry 11 0 1
$qCEd setMREDMode RIO-D
$qCEd onfigQ 0 0 15 45 0.5 0.01
$qCEd onfigQ 0 1 15 45 0.5 0.01

97

98

CHAPTER 7.

DIFFERENTIATED SERVICES

for {set j 1} {$j<=$NodeNb} { in r j } {


set qEC($j) [[$ns link $E($j) $Core queue
$qEC($j) meanPktSize $pktSize
$qEC($j) set numQueues_ 1
$qEC($j) setNumPre
2
$qEC($j) addPoli yEntry [$S($j) id [$D id TSW2CM 10 $ ir1 0.02
$qEC($j) addPoli erEntry TSW2CM 10 11
$qEC($j) addPHBEntry 10 0 0
$qEC($j) addPHBEntry 11 0 1
# $qEC($j) onfigQ 0 0 20 40 0.02
$qEC($j) onfigQ 0 0 10 20 0.1
$qEC($j) onfigQ 0 1 10 20 0.1
$qEC($j) printPoli yTable
$qEC($j) printPoli erTable
set qCE($j) [[$ns link $Core $E($j) queue
$qCE($j) meanPktSize
40
$qCE($j) set numQueues_ 1
$qCE($j) setNumPre
2
$qCE($j) addPHBEntry 10 0 0
$qCE($j) addPHBEntry 11 0 1
# $qCE($j) onfigQ 0 0 20 40 0.02
$qCE($j) onfigQ 0 0 10 20 0.1
$qCE($j) onfigQ 0 1 10 20 0.1
}
# set flow monitor
set monfile [open mon.tr w
set fmon [$ns makeflowmon Fid
$ns atta h-fmon $flink $fmon
$fmon atta h $monfile
#TCP Sour es, destinations, onne tions
for {set i 1} {$i<=$NodeNb} { in r i } {
for {set j 1} {$j<=$NumberFlows} { in r j } {
set t psr ($i,$j) [new Agent/TCP/Newreno
set t p_snk($i,$j) [new Agent/TCPSink
set k [expr $i*1000 +$j;
$t psr ($i,$j) set fid_ $k
$t psr ($i,$j) set window_ 2000
$ns atta h-agent $S($i) $t psr ($i,$j)
$ns atta h-agent $D $t p_snk($i,$j)
$ns onne t $t psr ($i,$j) $t p_snk($i,$j)
set ftp($i,$j) [$t psr ($i,$j) atta h-sour e FTP
} }

7.4.

SIMULATION OF DIFFSERV: PROTECTION OF VULNERABLE PACKETS

99

# Generators for random size of files.


set rng1 [new RNG
$rng1 seed 22
# Random inter-arrival times of TCP transfer at ea h sour e i
set RV [new RandomVariable/Exponential
$RV set avg_ 0.22
$RV use-rng $rng1
# Random size of files to transmit
set RVSize [new RandomVariable/Pareto
$RVSize set avg_ 10000
$RVSize set shape_ 1.25
$RVSize use-rng $rng1
# dummy ommand
set t [$RVSize value
# We now define the beginning times of transfers and the transfer sizes
# Arrivals of sessions follow a Poisson pro ess.
#
for {set i 1} {$i<=$NodeNb} { in r i } {
set t [$ns now
for {set j 1} {$j<=$NumberFlows} { in r j } {
# set the beginning time of next transfer from sour e and attributes
$t psr ($i,$j) set sess $j
$t psr ($i,$j) set node $i
set t [expr $t + [$RV value
$t psr ($i,$j) set starts $t
$t psr ($i,$j) set size [expr [$RVSize value
$ns at [$t psr ($i,$j) set starts "$ftp($i,$j) send [$t psr ($i,$j) set size"
$ns at [$t psr ($i,$j) set starts " ountFlows $i 1"
}}
for {set j 1} {$j<=$NodeNb} { in r j } {
set Cnts($j) 0
}
# The following pro edure is alled whenever a onne tion ends
Agent/TCP instpro done {} {
global t psr NodeNb NumberFlows ns RV ftp Out t p_snk RVSize
# print in $Out: node, session, start time, end time, duration,
# trans-pkts, transm-bytes, retrans-bytes, throughput
set duration [expr [$ns now - [$self set starts
set i [$self set node
set j [$self set sess
set time [$ns now

100

CHAPTER 7.

DIFFERENTIATED SERVICES

puts $Out "$i \t $j \t $time \t\


$time \t $duration \t [$self set ndatapa k_ \t\
[$self set ndatabytes_ \t [$self set nrexmitbytes_ \t\
[expr [$self set ndatabytes_/$duration "
# update the number of flows
ountFlows [$self set node 0

# The following re ursive pro edure updates the number of onne tions
# as a fun tion of time. Ea h 0.2 it prints them into $Conn. This
# is done by alling the pro edure with the "sign" parameter equal
# 3 (in whi h ase the "ind" parameter does not play a role). The
# pro edure is also alled by the "done" pro edure whenever a onne tion
# from sour e i ends by assigning the "sign" parameter 0, or when
# it begins, by assigning it 1 (i is passed through the "ind" variable).
#
pro ountFlows { ind sign } {
global Cnts Conn NodeNb
set ns [Simulator instan e
if { $sign==0 } { set Cnts($ind) [expr $Cnts($ind) - 1
} elseif { $sign==1 } { set Cnts($ind) [expr $Cnts($ind) + 1
} else {
puts -nonewline $Conn "[$ns now \t"
set sum 0
for {set j 1} {$j<=$NodeNb} { in r j } {
puts -nonewline $Conn "$Cnts($j) \t"
set sum [expr $sum + $Cnts($j)
}
puts $Conn "$sum"
$ns at [expr [$ns now + 0.2 " ountFlows 1 3"
} }
#Define a 'finish' pro edure
pro finish {} {
global ns tf qsize qbw qlost file2
$ns flush-tra e
lose $file2
exit 0
}
$ns
$ns
$ns
$ns
$ns

at 0.5 " ountFlows 1 3"


at [expr $sduration - 0.01 "$fmon dump"
at [expr $sduration - 0.001 "$qCEd printStats"
at $sduration "finish"
run

Table 7.1: di s.t l S ript

7.5.

101

SIMULATION RESULTS

CIR
10kbps 30kbps 100kbps 200kbps 300kbps 1Mbps 10Mbps
lost SYN pa kets
120
95
53
45
17
78
114
First pa kets lost
125
119
90
56
37
73
115
Total losses
1699
1612
1476
1286
1088
1290
1577
Table 7.2: Prote tion of vulnerable pa kets as a fun tion of CIR

7.5 Simulation results


Losses We he k the in uen e of the CIR marking rate on the loss probabilities of the SYN

pa kets and of the rst data pa ket in a onne tion, as before.


We see that we manage to de rease the losses of SYN pa kets by a fa tor of seven, and the
losses of the rst data pa ket of a onne tion by a fa tor of around 3.4, both obtained at CIR of
300kbps.

Throughput and Goodput The number of data pa kets that were su essfully transmitted

during the simulations was quite independent on the CIR: it was in the average 58285, with a
standard deviation of 395 pa kets. This is due to the fa t that arrival rate of sessions does not
depend on the CIR. In view of the low loss probabilities, the throughput too, is almost onstant
as a fun tion of CIR.

The number of sessions The total number of sessions as a fun tion of time is given in Fig.
7.2 for the CIR of 200kbps (the optimal) and for the ase of no prioritization (CIR of 10Mbps).
We see from the simulation result that our marking s heme with CIR of 300kbps gives a better
60
CIR 300kbps
CIR 10Mbps

50
40
30
20
10
0
0

10

20

30

40

50

60

Figure 7.2: Evolution of total number of sessions


performan e: less number of a tive sessions are present under this marking. This is related to the
fa t that the session duration in our marking is shorter, as we show in the next se tion. Indeed,
sin e the arrival rate of sessions is the same independently of CIR the average number of session
should be proportional to the average duration of a session (the proportionality fa tor being the
arrival rate of sessions).

Session duration In Table 7.3 we present the average duration of a session as a fun tion the
CIR. We see that in the range of 100kbps till 300kbps the average duration de reases by a fa tor
between 1/3 (for 100kbps) and 1/2 (for 300kbps) with respe t to the ase of no prioritization.

102

CHAPTER 7.

DIFFERENTIATED SERVICES

CIR
10kbps
30kbps 100kbps 200kbps 300kbps 1Mbps 10Mbps
sess. duration 0.252616 0.231077 0.167948 0.149478 0.119509 0.203202 0.225075
Table 7.3: Average duration of a session as a fun tion of CIR

7.6 Dis ussions and on lusions


There a few limitation of the marking approa h. The signi ant improvement that we obtain
would not be obtained in any s enario, and we propose a few guidelines, whi h we validated
through further simulations, to des ribe its limitations.
1. Vulnerable pa kets deteriorate onsiderably performan e sin e they ause long time-outs.
This is espe ially the ase for the loss of a syn that results in a timeout of 3se or of 6se . In
high speed networks the duration of a le transfer is short (often the whole transfer is mu h
shorter than timeout), so we an expe t to gain mu h by eliminating these long timeouts. In
low speed networks, this is no more the ase so the gains in our approa h be ome marginal.
2. In our simulation, an average le size is 10kbytes, whi h is the avereaged measured le
size in the Internet [35. This means that around 10% of the pa kets is a SYN pa ket and
further, another 10% of the pa kets are rst in a transfer. Thus in the absen e of our
approa h, around 20% of lost pa kets would orrespond to these types of vulnerable pa kets,
so elliminating these losses an result in a onsiderable improvement in performan e. If we
were to use our approa h to mu h longer les, the fra tion of vullnerable pa kets would be
mu h smaller, so that the added value of our approa h would be smaller.

7.7 Exer ises


1. Our simulations have restri ted to FTP type tra . In this exer ise we shall onsider HTTP
type tra : The time between the end of transmission of a le till the beginning of the next
transmission is exponentially distributed with a mean of 0.1 se . This is alled a "thinking
time". Thus from ea h sour e node there an be only one le transmitted at the same
time (at most one a tive session). Write a t l program for this tra model and he k its
performan e as a fun tion of the CIR. Compare with FTP type tra

Chapter 8

Lo al area networks
8.1 Ba kground
The obje tive of lo al area networks is to share resour es that are either ostly or that are not
monopolized by a single user. Examples are memory hard disks and printers. Lo al area networks
simpli es message ex hanges, sharing of les and distributed omputing. They allow to share
instalation and operational osts.
Four main topologies of lo al area networks exist: the star, the meshed, the ring and the bus.
In a star topology, terminals are onne ted to a entral hub through point-to-point links.
This allows to ontrol in a entralized way on i ts and allows to handle easily broad ast. The
drawba k is the reliability of its operation that is limitted due to the dependen e on the entral
hub. Furthermore, the apa ity of the entral hub limits the number of stations that an be
onne ted.
The meshed topology allows for several possible routes between two users. An example is the
telephone system.
The ring network onsists of repeaters linked through point-to-point unidire tional links so as
to form a losed loop. Examples are the IBM token ring, IEEE 802.5 and the FDDI. It is simple,
and allows to transmit on one link while re eiving from the other. In order to avoid ollisions only
one station an transmit at a time, whi h means ine ient use of the resour es.
indexEthernet The bus topology onsists of a single segment of able to whi h stations are
onne ted; the onne tion is of the multipoint type: all the stations onneted to the bus here the
signal, and if two stations transmit at the same time there is a ollision. Examples are the token
bus (IEEE 802.4) and the Ethernet (IEEE 802.3, IEEE802.9, IEEE802.12 and IEEE802.14). The
bus itself is passive (it does not regenerate nor amplify the signal), whi h results in a limitted
range. In order to extend the range one needs to use a repeaters whi h an onne t several buses
to a able.
In topologies that are other than stars, distributed MAC (Multiple AC ess) proto ols to the
hannel need to be implemented. The a ess proto ols are divided into three ategories: stati
sharing, random a ess, and a ess by demand
In stati sharing proto ols, some resour e is shared in a xed way between users. The main
proto ols are
1. TDMA (Time Devision Multiple A ess) in whi h time is slotted and di erent slots are
allo ated to di erent users.
2. FDMA (Frequen y Devision Multiple A ess) in whi h several users an transmit simultanuously using di erent frequen ies ea h. The a ess to satellites is frequently based on a
103

104

CHAPTER 8.

LOCAL AREA NETWORKS

ombination of TDMA and FDMA.


3. CDMA (Code Devision Multiple A ess) several users an transmit at the same time and
using the same frequen ies, but ea h using another ode. Codes are often orthogonal whi h
de reases interferen e. Used in the third generation mobile networks su h as the Universal
Mobiles Tele ommuni ations System (UMTS).
In random a ess proto ols, a ess is attempted at random whi h may ause ollisions
and a need of retransmissions. Examples are the Aloha used in satellite ommuni ations and
the Ethernet. In order to redu e ollisions, one an rst listen if there is no other signal being
transmitted on the ommon hannel, and if there is, transmission is delayed. This is alled "Carrier
Sense Multiple A ess" (CSMA). Moreover, one an avoid transmission a long tram if during the
transmission, a ollision is dete ted. This is alled "Collision Dete tion" (CD). This version of
CSMA is denoted CSMA/CD and CSMA is implemented in ns, and in parti ular the CSMA/CD.
The Ethernet. A MAC proto ol based on CSMA/CD is the Ethernet, and various versions
of it are standarised, e.g. IEEE802.3 (10Mbps), IEEE802.9 (multimedia), IEEE802.11 (wireless
Ethernet), IEEE802.12 ("AnyLan" high-speed 100Mbps, ompatible with di erent types of LANs)
and IEEE802.14 (high speed). The Ethernet in ludes a ba ko algorithms for the retransmissions.
A number M is hosen randomly, 0  M < 2k where k = min(n; 10), and where n is the total
number of ollisions already experien ed by the pa ket. The time before retransmission is taken
to be M times the ollision window (whi h is twi e the maximum propagation time of the signal
in the lo al area network). When n = 16, the transmission is abandoned.
The IEE802.3 is implemented in ns. The ollision window is bounded by 51.2 se and the
lo al area network is limitted to 5km. It has several versions, e.g. 10base5, 10base2, 10broad36 nd
others; The rst number stands for the throughput in Mbps, the se ond for the modulation (with
"broad" meaning no modulation). The silen e period between transmitted frames in 10base5 is
of 9.6se . When using a faster Ethernet, this silen e time as well as the maximum propagation
time redu e, and so does the maximum physi al range of the network.
There exists another Ethernet te hnology based on swit hing where larger maximum throughputs an be obtained and where there are less ollisions.

8.2 Simulating LANs with ns


ns simulator simulates three the levels related to a lo al area network: link layer proto ols (su h
as the ARQ (Automati Repeat reQuest proto ol), the MAC proto ol (e.g. Ethernet or token
ring) and the physi al hannel.
The basi way to de ne a LAN through whi h a group of nodes is onne ted is by the ommand
set lan [$ns newLan <arguments>

There are seven arguments:


1. A group of nodes, e.g. "$n3 $n4 $n5",
2. the delay,
3. the bandwidth
4. a link layer type (e.g. "LL"),
5. the interferen e queue type, e.g. "QueueDrop Tail",
6. the MAC type (e.g. "Ma /Csma/Cd" or "Ma /802_3")

8.2.

105

SIMULATING LANS WITH NS

7. the Channel type (e.g. "Channel")


As an example, onsider the network in Fig. 8.1 whi h is a modei ation of the network studied
in Chapter 2 (Fig. 2.2) in whi h nodes n3, n4 and n5 are put on a ommon LAN. This means

$n4

$n0
2Mbps
10ms

300kbps
100ms

LAN
$n3

$n2
2Mbps
$n1 10ms

300kbps
100ms

$n5

Figure 8.1: A LAN example


that TCP pa kets destinated to node n4 arrive also at node n5 (and area dropped there), TCP
a knowledgements sent by node n4 to node n0 also arrive at node n5 (and are dropped there) and
UDP pa kets destinated to node n5 also arrive at node n4 (and are dropped there).
The s ript le is then the same as ex1.t l (Table 2.4) but where we repla e the ommands
$ns duplex-link $n3 $n4 0.5Mb 40ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 30ms DropTail

by the ommand
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel

106

CHAPTER 8.

LOCAL AREA NETWORKS

Chapter 9

Mobile networks
There are two approa hes for wireless ommuni ation between two hosts. The rst is the entralized ellular network in whi h ea h mobile is onne ted to one or more xed base stations
(ea h base station is responsible for another ell), so that a ommuni ation between two mobile
stations require the to involve one or more base stations. A se ond de entralized approa h onsists
based of an ad-ho network between users that wish to ommuni ate between ea h other. due to
the more limited range of a mobile terminal (with respe t to a xed base station), this approa h
requires mobile nodes not only to be sour es or destination of pa kets but also to forward pa kets
between other mobiles. Cellular station has a mu h larger range than ad-ho networks. However,
ad-ho networks have the advantage of being qui kly deployable as they do not require an existing
infrastru ture.
In ellular networks, the wireless part is restri ted only to the a ess to a network, and within
the network lassi al routing proto ols an be used. Ad-ho network in ontrast rely on spe ial
routing proto ols that have to be adapted to frequent topology hanges.
To model well ellular networks, often sophisti ated simulation tools of the physi al radio
hannel are needed, as well as the simulation of power ontrol me hanisms. ns does not have
an advan ed physi al layer module (although it ontains some simple modeling features of radio
hannels).
In ad-ho networks, in ontrast, the routing proto ols are entral. ns allows to simulate the
main existing routing as well as transport and appli ations that use them. Moreover, it allows to
take into a ount the MAC and link layer, the mobility, and some basi features of the physi al
layer.
The urrent routing proto ols implemented by ns are





DSDV - Destination Sequen ed Distan e Ve tor [31,

AODV - Ad-ho On Demand Distan e Ve tor [30.

DSR - Dynami Sour e Routing [25,


TORA/IMPE - Temporally Ordered Routing Algorithm / Internet MANET En apsulation
Proto ol [9, 28, 29,

9.1 The routing algorithms


There are several approa hes in onventional routing algorithms in traditional wireline networks,
and some ideas from these are also used in ad-ho networks. Among the traditional approa hes
we shall mention the following:
107

108

CHAPTER 9.

MOBILE NETWORKS

1. Link State. Ea h node maintains a view of the omplete topology with a ost per ea h link.
Ea h node periodi ally broad asts the link osts of its outgoing links to all other nodes using
ooding. Ea h node updates its view of the network and applies a shortest path algorithm
for hoosing the next-hop for ea h destination.
2. Distan e Ve tor. Ea h node only monitors the ost of its outgoing links. Instead of
broad asting the information to all nodes, it periodi ally broad asts to ea h of its neighbors
an estimate of the shortest distan e to every other node in the network. The re eiving nodes
use this information to re alu late routing tables using a shortest path algorithm. This
method is more omputation e ient, easier to implement and requires less storage spa e
than link state routing.
3. Sour e routing. Routing de isions are taken at the sour e, and pa kets arry along the
omplete path they should take.
4. Flooding. The sour e sends the information to all neighbors who ontinue to sending it to
their neighbors et . By using sequen e numbers for the pa kets, a node is able to relay a
pa ket only on e.
Next we des ribe the Ad-ho routing proto ols implemented in ns.

9.1.1 Destination Sequen ed Distan e Ve tor - DSDV


DSDV is a distan e ve tor routing proto ol. Ea h node has a routing table that indi ates for ea h
destination, whi h is the next hop and number of hops to the destination. Ea h node periodi ally
broad asts routing updates. A sequen e number is used to tag ea h route. It shows the freshness
of the route: a route with higher sequen e number is more favorable. In addition, among two
routes with the same sequen e number, the one with less hops is more favorable. If a node dete ts
that a route to a destination has broken, then its hop number is set to in nity and its sequen e
number updated (in reased) but assigned an odd number: even numbers orrespond to sequen e
numbers of onne ted paths.

9.1.2 Ad-ho On Demand Distan e Ve tor - AODV


AODV is a distan e ve tor type routing. It does not require nodes to maintain routes to destinations that are not a tively used. As long as the endpoints of a ommuni ation onne tion have
valid routes te ea h other, AODV does not play a role.
The proto ol uses di erent messages to dis over and maintain links: Route Requests (RREQs),
Route Replies (RREPs), and Route Errors (RERRs). These message types are re eived via UDP,
and normal IP header pro essing applies.
AODV uses a destination sequen e number for ea h route entry. The destination sequen e
number is reated by the destination for any route information it sends to requesting nodes.
Using destination sequen e numbers ensures loop freedom and allows to know whi h of several
routes is more "fresh". Given the hoi e between two routes to a destination, a requesting node
always sele ts the one with the greatest sequen e number.
When a node wants to nd a route to another one, it broad asts a RREQ to all the network
till either the destination is rea hed or another node is found with a "fresh enough" route to the
destination (a "fresh enough" route is a valid route entry for the destination whose asso iated
sequen e number is at least as great as that ontained in the RREQ). Then a RREP is sent ba k
to the sour e and the dis overed route is made available.
Nodes that are part of an a tive route may o er onne tivity information by broad asting
periodi ally loa l Hello messages (spe ial RREP messages) to its immediate neighbours. If Hello

9.1.

THE ROUTING ALGORITHMS

109

messages stop arriving from a neighbor beyond some given time threshold, the onne tion is
assumed to be lost.
When a node dete ts that a route to a neighbor node is not valid it removes the routing
entry and sends a RERR message to neighbors that are a tive and use the route; this is possible
by maintaining a tive neighbour lists. This pro edure is repeated at nodes that re eive RERR
messages. A sour e that re eives an RERR an reinitiate a RREQ message.
AODV does not allow to handle unidire tional links.

9.1.3 Dynami Sour e Routing - DSR


Designed for mobile ad ho networks with up to around two hundred nodes with possibly high
mobility rate. The proto ol works "on demand", i.e. without any periodi updates.
Pa kets arry along the omplete path they should take. This redu es overheads for large
routing updates at the network. The nodes store in their a he all known routes. The proto ol is
omposed of route dis overy and route maintenan e.
At route dis overy, a sour e requesting to send a pa ket to a destination broad asts a Route
Request (RREQ) pa ket. Nodes re eiving RREQ sear h in their Route Ca he for a route to the
destination. If a route is not found then the RREQ is further transmitted and the node adds its
own address to the re orded hop sequen e. This ontinues till the destination or a node with a
route to the destination are rea hed. The route ba k an be retreived by the reverse hop re ord.
As routes need not be symetri , DSR he ks the Route Ca he of the replying node and if a route
is found, it is used instead. Alternatively, one an piggyba k the reply on a RREQ targeted at
the originator. Hen e unidire tional links an be handled.
Route maintenan e: When originating or forwarding a pa ket using a sour e route, ea h
node transmitting the pa ket is responsible for on rming that data an ow over the link from
that node to the next hop. An a knowledgment an provide on rmation that a link is apable
of arrying data. A knowledgments are often already part of the MAC proto ol in use (su h as
the link-layer a knowledgment frame de ned by IEEE 802.11), or are "passive a knowledgment",
i.e. a node knows that its pa ket is re eived by an intermediate node sin e it an hear that the
intermediate node further forwards it. If su h a knowledgements are not available then a node
an request an a knowledgement (whi h an be sent dire tly to the sour e using another route).
A knowledgements may be requested several times (till some given bound), and in the persistent
absen e of a knowledgement, the route is removed from the Route Ca he and return a "Route
Error" to ea h node that has sent a pa ket routed over that link sin e an a knowledgement was last
re eived. Nodes overhearing or forwarding pa kets should make use all arried routing information
to update its own Route Pa ket.

9.1.4 Temporally Ordered Routing Algorithm - TORA


This proto ol is of the family of link reversal proto ols. It may provide several routes between a
sour e and a destination. TORA ontains three parts: reating, maintaining and erasing routes.
At ea h node, a separate opy of TORA is is run per ea h destination. TORA builds a dire ted
a y li graph rooted at the destination. It asso iates a height with ea h node in the network (with
respe t to a ommon destination). Messages ow from nodes with heigher height to those with
lower heights. Routes are dis overed using Query (QRY) and Update (UPD) pa kets.
When a node with no downstream links needs a route to a destination, it broad asts a QRY
pa ket that propagates till it either nds a node with a route to the destination or the destination
itself. That node will respond by broad asting a UPD pa ket ontaining the node's height. A
node re eiving the UPD pa ket updates its height a ordingly and broad asts another UPD. This
may result in a number of dire ted paths from the sour e to the destination.

110

CHAPTER 9.

MOBILE NETWORKS

If a node dis overs a parti ular destination to be unrea hable, it sets the orresponding lo al
height to a maximum value. In ase the node annot nd any neighbour with nite height w.r.t.
this destination, it attempts to nd a new route. In ase there is no route to a destination (i.e. of
a network partition), the node broad asts a Clear (CLR) message resetting all routing states and
removing invalid routes from its part of the network.
TORA operates on top of IMEP (Internet MANET En apsulation Proto ol) that provides
reliable delivery of route-messages and that informs the routing proto ol of hanges of the links
to its neighbours. IMEP tries to aggregate IMEP and TORA messages to a single pa ket ( alled
blo k) so as to redu e overhead. To get information on the status of neighborinig links, IMEP
periodi ally sends BEACON messages answered by HELLO response messages.

9.2 Simulating mobile networks


9.2.1 Simulation s enario
We start by presenting simple s ript that runs a single TCP onne tion over a 3-nodes network
over an area of a size of 500m over 400m depi ted in Fig 9.1. The lo ation pro ess is as follows.

1
2

Figure 9.1: Example of a three node ad-ho network

The initial lo ations of nodes 0, 1, and 2 are respe tively (5,5), (490,285) and (150,240) (the
z oordinate is assumed throughout to be 0).

At time 10, node 0 statrts moving towords point (250,250) at a speed of 3m/se .
At time 15, node 1 statrts moving towords point (45,285) at a speed of 5m/se .
At time 10, node 0 statrts moving towords point (480,300) at a speed of 5m/se .
Node 2 is still throughout the simulation.

The simulation lasts 150se . At time 10, a TCP onne tion is initiated between node 0 and node
1.
We shall use below the DSDV ad-ho routing proto ol and the IEEE802.11 MAC proto ol.

9.2.2 Writing the t l s ript


We begin by spe ifying some basi parameters for the simulations, providing information for the
di erent layers. This is done as follows:
set val( han)

Channel/WirelessChannel

;# hannel type

9.2.

set
set
set
set
set
set
set
set
set
set
set
set

111

SIMULATING MOBILE NETWORKS

val(prop)
val(netif)
val(ma )
val(ifq)
val(ll)
val(ant)
val(ifqlen)
val(nn)
val(rp)
val(x)
val(y)
val(stop)

Propagation/TwoRayGround
Phy/WirelessPhy
Ma /802_11
Queue/DropTail/PriQueue
LL
Antenna/OmniAntenna
50
3
DSDV
500
400
150

;#
;#
;#
;#
;#
;#
;#
;#
;#
;#
;#
;#

radio-propagation model
network interfa e type
MAC type
interfa e queue type
link layer type
antenna model
max pa ket in ifq
number of mobilenodes
routing proto ol
X dimension of topography
Y dimension of topography
time of simulation end

These parameters are used in the on guring of the nodes, whidh is done with the help of the
following ommand
$ns node- onfig -adho Routing $val(rp) \
-llType $val(ll) \
-ma Type $val(ma ) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
- hannelType $val( han) \
-topoInstan e $topo \
-agentTra e ON \
-routerTra e ON \
-ma Tra e OFF \
-movementTra e ON
for {set i 0} {$i < $val(nn) } { in r i } {
set node_($i) [$ns node
}

The four last options in the node- on g an ea h be given a value of ON or OFF. The agentTra e
will give in our ase the tra e of TCP, routerTra e provides tra ing of pa kets involved in the
routing, ma Tra e is related to tra ing MAC proto ol pa kets, and movementTra e is used to
allow tra ing the motion of nodes (for nam).
The initial lo ation of node 0 is given as follows:
$node_(0) set X_ 5.0
$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0

and similarly we provide the initial lo aation of other nodes.


A linear momvement of a node is generated by spe ifying the time in whi h it starts, the x and
y values of the target point and the speed. For eaxmple, node's 1 movement will be written as
$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"

We need to reate the initial node position for nam using

112

CHAPTER 9.

MOBILE NETWORKS

for {set i 0} {$i < $val(nn)} { in r i } {


# 30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}

We tell nodes when the simulation ends with


for {set i 0} {$i < $val(nn) } { in r i } {
$ns at $val(stop) "$node_($i) reset";
}

We then reate the TCP onne tion and the ftp appli ation over it as usual, see e.g. Chapter
4. Ending the simulation is also as usual, ex ept for an additional ommand for ending nam:
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

The omplete tra e of our program is given in Table 9.1.

9.3 Tra e format


An example of a line in the output tra e is
r 40.639943289 _1_ AGT --- 1569 t p 1032 [a2 1 2 800 ------[0:0 1:0 32 1 [35 0 2 0

The rst eld is a letter that an have the values r,s,f,D for "re eived", "sent", "forwarded"
and "dropped", respe tively. It an also be M for giving a lo ation or a momvement indi ation, this is des ribed later.





The se ond eld is the time.


The third eld is the node number.
The fourth eld is MAC to indi ate if the pa ket on erns a MAC layer, it is AGT to indi ate
a the transport layer (e.g. t p) pa ket, or RTR if it on erns the routed pa ket. It an also
be IFQ to indi ate events related to the interferen e priority queue (like drop of pa kets).

After the dahses ome the global sequen e number of the pa ket (this is not the t p sequen e
number).





At the next eld omes more information on the pa ket type (e.g. t p, a k or udp).
Then omes the pa ket size in bytes.
The 4 numbers in the rst square barkets on ern ma layer information. The rst hexade imal number, a2 (whi h equals 162 in de imal) spe i es the expe ted time in se onds
to send this data pa ket over the wireless hannel. The se ond number, 1, stands for the
MAC-id of the sending node, and the third, 2, is that of the re eiveing node. The fourth
number, 800, spe i es that the MAC type is ETHERTYPE_IP.

The next numbers in the se ond square bra kets on ern the IP sour e and destination
addresses, then the ttl (Time To Live) of the pa ket (in our ase 32),

The third bra kets on ern the t p information: its sequen e number and the a knowledgement number.

9.3.

113

TRACE FORMAT

There are other formats related to other routing me hanisms and/or pa ket types.
A movement ommand has the form:
M 10.00000 0 (5.00, 5.00, 0.00), (250.00, 250.00), 3.00

where the rst number is the time, the se ond is the node number, then omes the origin and
destination lo ations, and nally is given the speed.
# A 3-node example for ad-ho simulation with DSDV
# Define options
set val( han)
set val(prop)
set val(netif)
set val(ma )
set val(ifq)
set val(ll)
set val(ant)
set val(ifqlen)
set val(nn)
set val(rp)
set val(x)
set val(y)
set val(stop) 150
set
set
set
set

Channel/WirelessChannel
;# hannel type
Propagation/TwoRayGround ;# radio-propagation model
Phy/WirelessPhy
;# network interfa e type
Ma /802_11
;# MAC type
Queue/DropTail/PriQueue
;# interfa e queue type
LL
;# link layer type
Antenna/OmniAntenna
;# antenna model
50
;# max pa ket in ifq
3
;# number of mobilenodes
DSDV
;# routing proto ol
500
;# X dimension of topography
400
;# Y dimension of topography
;# time of simulation end

ns [new Simulator
tra efd
[open simple.tr w
windowVsTime2 [open win.tr w
namtra e
[open simwrls.nam w

$ns tra e-all $tra efd


$ns namtra e-all-wireless $namtra e $val(x) $val(y)
# set up topography obje t
set topo
[new Topography
$topo load_flatgrid $val(x) $val(y)
reate-god $val(nn)
#
# Create nn mobilenodes [$val(nn) and atta h them to the hannel.
#

114

CHAPTER 9.

# onfigure the nodes


$ns node- onfig -adho Routing $val(rp) \
-llType $val(ll) \
-ma Type $val(ma ) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
- hannelType $val( han) \
-topoInstan e $topo \
-agentTra e ON \
-routerTra e ON \
-ma Tra e OFF \
-movementTra e ON
for {set i 0} {$i < $val(nn) } { in r i } {
set node_($i) [$ns node
}
# Provide
$node_(0)
$node_(0)
$node_(0)

initial lo ation of mobilenodes


set X_ 5.0
set Y_ 5.0
set Z_ 0.0

$node_(1) set X_ 490.0


$node_(1) set Y_ 285.0
$node_(1) set Z_ 0.0
$node_(2) set X_ 150.0
$node_(2) set Y_ 240.0
$node_(2) set Z_ 0.0
# Generation of movements
$ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"
$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
$ns at 110.0 "$node_(0) setdest 480.0 300.0 5.0"
# Set a TCP onne tion between node_(0) and node_(1)
set t p [new Agent/TCP/Newreno
$t p set lass_ 2
set sink [new Agent/TCPSink
$ns atta h-agent $node_(0) $t p
$ns atta h-agent $node_(1) $sink
$ns onne t $t p $sink
set ftp [new Appli ation/FTP
$ftp atta h-agent $t p
$ns at 10.0 "$ftp start"
# Printing the window size
pro plotWindow {t pSour e file} {
global ns
set time 0.01
set now [$ns now

MOBILE NETWORKS

9.3.

TRACE FORMAT

set wnd [$t pSour e set wnd_


puts $file "$now $ wnd"
$ns at [expr $now+$time "plotWindow $t pSour e $file" }
$ns at 10.1 "plotWindow $t p $windowVsTime2"
# Define node initial position in nam
for {set i 0} {$i < $val(nn)} { in r i } {
# 30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}
# Telling nodes when the simulation ends
for {set i 0} {$i < $val(nn) } { in r i } {
$ns at $val(stop) "$node_($i) reset";
}
# ending nam and the simulation
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "stop"
$ns at 150.01 "puts \"end simulation\" ; $ns halt"
pro stop {} {
global ns tra efd namtra e
$ns flush-tra e
lose $tra efd
lose $namtra e
}
$ns run

Table 9.1: t l s ript wrls-dsdv.t l for TCP over an ad-ho network

115

116

CHAPTER 9.

MOBILE NETWORKS

9.4 Analysis of simulation results


At the beginning the nodes are too far away and a onne tion annot be set. The rst TCP
signaling pa ket is transmitted at time 10 but the onne tion annot be opened. Meanwhile nodes
0 and nodes 1 start moving towards node 2. After 6 se ond (timeout) a se ond reatempt o urs
but still the onne tion annot be established and the timeout value is doubled to 12se . At time
28 another transmission attempt o urs. The timeout value is doubled again to 24 se and again
to 48 se . Thus only at time 100 se the onne tion has been established. The nodes 1 and 0 are
lose to ea h other so there is a dire t onne tion established. The mobiles get further apart till
the dire t link brakes. The routing proto ol is too slow to rea t and to reate an alternative route.
The window evolution is given in Fig. 9.2 and a snap-shot of nam at time 124.15 se is given in
Fig. 9.4.
70
win.tr

60
50
40
30
20
10
0
0

20 40 60 80 100 120 140 160

Figure 9.2: TCP window size in a three node


s enario with DSDV routing proto ol

100
90
80
70
60
50
40
30
20
10
0

win.tr

20 40 60 80 100 120 140 160

Figure 9.3: TCP window size in a three node


s enario with DSDV routing proto ol with
both two and a single hop path

Next we slightly hange the parameters of the simulation. The only hange is in fa t that the
ftp transfer will start now at time 12 instead of at time 10. This will ause both nodes 0 as well
as node 1 to be within the radio of node 2 when the timeout at around 53 se expires so that
when t p onne tion is reattempted at that time a two hop path is established between node 0
and node 1. This is illustarted in Fig. 9.5. At time 66 there noeds 0 and 1 are su iently lose so
a dire t onne tion is established. The window size evolution is given in Fig 9.3. At the moment
of the path hange there is a single TCP pa ket loss that auses the window to de rease.
At time 125.5 nodes 0 and 1 are too far apart for the onne tion to be maintained and the
onne tion brakes.

9.5 Comparison with other ad-ho routing


9.5.1 TCP over DSR
We rst hange the routing proto ol to DSR by hanging in wrls-dsdv.t l the orresponding line
to
set val(rp) DSR ;# routing proto ol

When performing the simulation, we observe ve phases of operation. In the rst and last, the
nodes are too far away and there is no onne tivity. During phase 2 and 4, onne tion between

9.5.

117

COMPARISON WITH OTHER AD-HOC ROUTING

1
2

Figure 9.4: TCP in a three node s enario with


DSDV routing proto ol, time 124.14 se , a single hop path

Figure 9.5: TCP in a three node s enario with


DSDV routing proto ol, time 58 se : a 2 hop
path

nodes 0 and 1 use node 2 as a relay, whereas in the 3rd phase, there is a dire t path between node
0 and 1.
Phase 2 starts at around time 40. Phase 3 starts at around 60 se . At time 125.50 the fourth
phase starts and at time 149 se it ends, whi h ends the whole onne tion. This is des ribed in
Figure 9.6.
90

160
140
120
100
80
60
40
20
0

win.tr

AODV, 3 nodes

80
70
60
50
40
30
20
10

20 40 60 80 100 120 140 160

Figure 9.6: Window size evolution of the TCP


onne tion for DSR

0
0

20

40

60

80

100 120 140 160

Figure 9.7: Window size evolution of the TCP


onne tion for AODV

Here are some further observations:

We note that in the DSDV, the system was not able to provide the 4th phase, so the
onne tion was ended mu h earlier.

The total number of TCP pa kets transfered using DSR is mu h larger than in DSDV. In
DSR, 6770 TCP (data) pa kets have been re eived during the simulation, whereas in DSDV
with the same parameters ( orresponding to the s ript wrls-dsdv.t l) it is 2079. (We an
obtain this information by typing
grep "^r" simple.tr | grep "t p" | grep "_1_ AGT" > t p.tr

and then ounting the number of lines. Or we an be more pre ise and look at the sequen e
number of the last re eived t p pa ket.)

118

CHAPTER 9.

MOBILE NETWORKS

If we follow the tra e of a TCP pa ket, say the one with sequen e number 6, we see that it
appears various times:
s
r
s
f
r
f
r
r

40.298003207
40.298003207
40.298003207
40.310503613
40.310528613
40.310528613
40.348863637
40.348863637

_0_
_0_
_0_
_2_
_2_
_2_
_1_
_1_

AGT
RTR
RTR
RTR
RTR
RTR
RTR
AGT

-----------------

1507
1507
1507
1507
1507
1507
1507
1507

t p
t p
t p
t p
t p
t p
t p
t p

1040
1040
1060
1060
1060
1068
1068
1040

[0 0
[0 0
[0 0
[13a
[13a
[13a
[13a
[13a

0
0
0
2
2
2
1
1

0 ...
0 ...
0 ...
0 800
0 800
0 800
2 800
2 800

...
...
...
...
...

It is rst sent by the TCP agent at node 0, then re eived by the routing proto ol of the same node
and sent from there with an additional header. It is then re eived and forwarded by node 2, till
nally it is re eived at node 1 at the routing level and then by the TCP agent. The above tra e
was obtained by enabeling the tra ing of agentTra e and routerTra e. 4 other lines on erning
the same pa ket will appear if we enable also the tra ing of ma Tra e.

9.5.2 TCP over AODV


The simulations with the same parameters as before is repeated with AODV. The window size
is given in Figure 9.7. The onne tion transfered altogether 3924 TCP data pa kets. It had
throughout a long single phase in whi h the same two hop path was used, in whi h node 2 relayed
the pa kets.
Due to the fa t that hanges in paths were avoided, there were no losses so the window remained
high. However, we see that it rea hes values less than DSR. This is due to the fa t that the round
trip time (needed to in rease the window by one unit) is longer sin e a dire t path is not used
here. This explains the fa t that it transfers less data during the simulation than DSR. We thus
see that nding a shorter path results in a better TCP performan e.

9.5.3 TCP over TORA


With the same parameters as the previous simulations, i.e. wrls-dsdv.t l, TORA gave no pa ket
transfers at all! To in rease onne tivity, we added another xed node at point (250,240) whi h
only serves to relay pa kets. The window size evolution is given in Fig 9.8.
60

45
40
35
30
25
20
15
10
5
0

win.tr

win.tr
50
40
30
20
10

20 40 60 80 100 120 140 160

Figure 9.8: Window size of TCP over Tora


with 4 nodes

0
0

20

40

60

80

100 120 140 160

Figure 9.9: TCP over AODV with large value


of maximum window

9.6.

119

THE INTERACTION OF TCP WITH THE MAC PROTOCOL

We from the nam animation (or from the output tra e) the following evolution. At the beginning there is no onne tivity. When onne tivity starts, a path is established using all nodes:
0-2-3-1 (see Fig. 9.10 that des ribes the situation at time 33). At time 34.5se a shorter forward
path is established: 0-2-1, but the path of ACKs remains un hanged. Then at time 44 the ACK
path hanges to 1-3-0 (e.g. Fig. 9.11).

1
2

0
0

Figure 9.10: TCP over Tora with 4 nodes,


time 33

Figure 9.11: TCP over Tora with 4 nodes,


time 56

9.5.4 Some omments


In the examples that we onsidered, losses o urred either when the geographi al range was too
far for re eption or when there was a route hange, and there were no losses due to bu er over ow.
This is due to the fa t that we used the default value of the maximum window size of TCP of 20.
Thus the a tual window that is used is the minimum between the ongestion window and 20. In
Fig. 9.9 we present the window size ovultion of TCP using AODV under the same onditions as
those that were used to obtain Fig. 9.7 but with a maximum window size of 2000. We see that
we obtain also losses due to over ow.

9.6 The intera tion of TCP with the MAC proto ol


9.6.1 Ba kground
In the previous se toins we onsidered a small number of mobiles, and saw how mobility phenomena
in uen ed the performan e of TCP. When there are a large number of terminals, new parti ular
phenomena due to the MAC and physi al layers may have a riti al in uen e on TCP performan e.
To understand this intera tion we rst des ribe some aspe ts of the operation of the IEEE802.11
MAC layer and of the physi al layer.
Ea h transmission of a DATA pa ket at the MAC level is part of a four-way handshake proto ol.
The mobile that wishes to send a pa ket, whi h we all M1, rst sends an RTS (Request to Send)
pa ket. If the destination mobile, whi h we all M2, an re eive the pa ket, it sends a CTS (Clear
to Send) pa ket. If M1 re eives the CTS it an then send the DATA pa ket (e.g. TCP data or
ACK pa ket). Finally, M2 sends a (MAC layer) ACK so that M1 knows that the data pa ket has
been well re eived.
This handshake proto ol is intended to redu e the ollision probability. Collisions may o ur
sin e a mobile, say M3, may wish to send a pa ket to M2 at the same time as M1 does; M3 may
be out of range to sense the transmission from M1, so a ollision of M1's and M3's pa kets may
o ur at M2. This phenomenon is alled the "hidden terminal phenomenon". With the handshake

120

CHAPTER 9.

MOBILE NETWORKS

proto ol, M3 will not attempt to send any pa ket when it hears the CTS pa ket sent by M2 to
M1.
If a sender M1 does not re eive a CTS pa ket then it di ers its transmission and makes later
attempts of sending an RTS. A sender drops the DATA pa ket if it has resent the RTS message
seven times and has not heard a CTS reply from the re eiver. A DATA pa ket is also dropped
after four retransmissions without re eveing a (MAC layer) ACK.
Although the handshake redu es the probability of "hidden terminal" ollisions, it does not
elliminate them. To understand how su h ollisoins may o ur, we should take into a ount the
geographi al range of interferen e and re eption. Current hardware spe i es that transmission
range is aobut 250m and the arrier sensing range as well as the interferen e range are about
550m. Consider the hain topology in Figure 9.12, where the distan e between noes is 200m.
Although nodes that are two hops apart are not hidden from ea h other, nodes that are three
hops apart are, and may reate ollisions. Indeed, if node M4 wishes to send a pa ket to M5
during a transmission from node M1 to M2, it annot hear the CTS from node M2 sin e it is out
of the 250m for good re eption. It annot hear M1's RTS or DATA pa ket sin e it is more than
550m away from M1. Therefore M4 may initiate transmission to M5 that will ollide at node M2
with transmissions from M1. We shall study in this Se tion the impa t of this types of ollisions
on TCP performan e using ns simulations, restri ting to the hain topology. We shall not onsider
mobility aspe ts here. We refer to [3, 18, 36 for more details.
M1

M2

M3

M4

M5

TCP
SOURCE

TCP
DESTINATION

Figure 9.12: The hain topology


The phenomenon that we just des ribed limits the number of pa kets that an be simultaneously transmitted in an ad-ho network without ollisions. This spatial onstraint turns out to be
the main fa tor limitting the performan e of TCP in su h environment and not bu er over ow.
It is shown in [18 that for our hain topology, it is bene tial to limit the maximum window size
of TCP to around n=4; further in rease in the maximum window size auses more ollisions and
a deterioration of the throughput. In this se tion we shall he k this assersion by simulations.
Moreover, sin e the number of simultaneous pa kets that an be transmitted is limitted, we shall
try to improve TCP throughput by de reasing the ACK ows, using delayed ACK. ns allows us
to simulate delayed ACKs with d = 2. We shall further show how to handle the ase of d > 2 by
making hange in ns simulator.

9.6.2 The simulated s enario


We use the standard two-ray ground propagation model, the IEEE802.11 MAC, and an omnidire tional antenna model of ns. We use the AODV routing algorithm, an interfa e queue length
of 50 at ea h node We tested the NewReno version of TCP, whi h is the most deployed one.
We tested four s enarios: 3,9,20 and 30 nodes. The ases of 3 and 9 nodes required 150 se per
simulation (to obtain stationary behavior). The other ases required 1500 se per simulation. A
TCP data pa ket is taken to be of size 1040 bytes (in luding the header). The s ript for the ase
of delayed ACK (with d = 2) is given in Table 9.2. Below, when on guring the nodes we shall
use the option "ma Tra e ON" in order to have detailed tra ing of MAC proto ols pa kets. This
will allow us to analyse the reason of ea h TCP pa ket loss that o urs.

9.6.

THE INTERACTION OF TCP WITH THE MAC PROTOCOL

# Define options
set val( han)
set val(prop)
set val(netif)
set val(ma )
set val(ifq)
set val(ll)
set val(ant)
set val(ifqlen)
set val(nn)
set val(rp)
set val(x)
set val(y)
set val(stop) 150

Channel/WirelessChannel
Propagation/TwoRayGround
Phy/WirelessPhy
Ma /802_11
Queue/DropTail/PriQueue
LL
Antenna/OmniAntenna
50
9
AODV
2200
;# X dimension
500
;# Y dimension
;# time of simulation end

;# hannel type
;# radio-propagation model
;# network interfa e type
;# MAC type
;# interfa e queue type
;# link layer type
;# antenna model
;# max pa ket in ifq
;# number of mobilenodes
;# routing proto ol
of topography
of topography

set ns [new Simulator


set tra efd
[open simple.tr w
set windowVsTime2 [open win.tr w
$ns tra e-all $tra efd
# set up topography obje t
set topo
[new Topography
$topo load_flatgrid $val(x) $val(y)
reate-god $val(nn)
#
# Create nn mobilenodes [$val(nn) and atta h them to the hannel.
#
# onfigure the nodes
$ns node- onfig -adho Routing $val(rp) \
-llType $val(ll) \
-ma Type $val(ma ) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
- hannelType $val( han) \
-topoInstan e $topo \
-agentTra e ON \
-routerTra e ON \
-ma Tra e ON \
-movementTra e OFF
for {set i 0} {$i < $val(nn) } { in r i } {
set node_($i) [$ns node
}

121

122

CHAPTER 9.

MOBILE NETWORKS

# Provide initial lo ation of mobilenodes


for {set i
$node_($i)
$node_($i)
$node_($i)
}

0} {$i
set X_
set Y_
set Z_

< $val(nn)} { in r i } {
[expr ($i+1)*200.0
250.0
0.0

# Set a TCP onne tion between node_(0) and node_(8)


set t p [new Agent/TCP/Newreno
$t p set lass_ 2
$t p set window_ 2000
Agent/TCPSink/DelA k set interval_ 100ms
set sink [new Agent/TCPSink/DelA k
$ns atta h-agent $node_(0) $t p
$ns atta h-agent $node_(8) $sink
$ns onne t $t p $sink
set ftp [new Appli ation/FTP
$ftp atta h-agent $t p
$ns at 1.0 "$ftp start"
# Printing the window size
pro plotWindow {t pSour e file} {
global ns
set time 0.1
set now [$ns now
set wnd [$t pSour e set wnd_
puts $file "$now $ wnd"
$ns at [expr $now+$time "plotWindow $t pSour e $file" }
$ns at 1.1 "plotWindow $t p $windowVsTime2"
# Telling nodes when the simulation ends
for {set i 0} {$i < $val(nn) } { in r i } {
$ns at $val(stop) "$node_($i) reset";
}
$ns at $val(stop) "stop"
$ns at [expr $val(stop)+0.1 "puts \"end simulation\" ; $ns halt"
pro stop {} {
global ns tra efd
$ns flush-tra e
lose $tra efd
}
$ns run

Table 9.2: t l s ript t pwD.t l for TCP over a stati ad-ho network with a hain topology

9.6.

123

THE INTERACTION OF TCP WITH THE MAC PROTOCOL

9.6.3 Simulation results


Our simulation results for n = 9; 20 and 30 nodes are summarized in Tables 9.13-9.15, respe tively.
13
standard TCP
DelAck d=2
DelAck d=3
DelAck d=4

16

standard TCP
DelAck d=2
DelAck d=3
DelAck d=4

12
11

14

10
12

9
8

10

7
6

5
0

10

15

20

25

30

35

40

Figure 9.13: Throughput in pkt/se for n = 9


as a fun tion of the maximum window size

10

15

20

25

30

35

40

Figure 9.14: Throughput in pkt/se for n = 20


as a fun tion of the maximum window size

11
standard TCP
DelAck d=2
DelAck d=3
DelAck d=4

10
9
8
7
6
5
5

10

15

20

25

30

35

40

Figure 9.15: Throughput in pkt/se for n = 30 as a fun tion of the maximum window size
We see that the standard Delayed A k option (d = 2) slightly outperforms the standard TCP
(yet with another value of maximum window size) for n = 9, and largely outperforms (more than
10%) the standard TCP for n = 30. A further improvement is obtained by the Delayed A k with
d = 3 (for both n = 9 as well as n = 20). But the most important improvement that we see
is that all delayed ACK versions are better than the standard TCP for maximum window sizes
of more than 10, with the options of d = 3 or d = 4 outperforming the standard delayed ACK
option. For n = 9, the Delayed ACK version with d = 3 is seen to yield between 30% to 40%
of improvement over standard TCP for any maximum window sizes larger than 10; in that range
it also outperforms standard TCP by 20%-30% for n = 20 and by 6% 20% for n = 30. The
version d = 4 performs even better for n = 20 for maximum windows between 10 to 25. An even
better performan e of delayed ACK an be obtained by optimizing over the timer duration of the
Delayed A k options, as we shall see later.
Yet the most important on lusion from the urves is the robustness of the Delayed A k options.
In pra ti e, when we do not know the number of nodes, there is no reason to limit the maximum
window size to a small value, sin e this ould deteriorate the throughput onsiderably. When
hoosing large maximum window, the delayed ACK versions onsiderably outperform standard

124

CHAPTER 9.

MOBILE NETWORKS

TCP. They a hieve almost the optimal value that the standard TCP ould a hieve if it knew the
number of nodes and ould hoose a ordingly the maximum window.
For a xed small size of maximum window size, the Delayed A k option does not outperform
the standard TCP version sin e most of the time, the window size limits the number of transmitted
TCP pa kets to less than d, whi h means that the delayed ACK option has to wait until the timer
(of 100ms by default) expires before generating an ACK; during that time the sour e annot
transmit pa kets.
Next, we plot the window size evolution for n = 9 for standard TCP and for TCP with delayed
ACK option with d = 3. The window size is sampled every 0.1 se . We see that although the
14

10
simple TCP

12

DelAck d=3

9
8

10

5
4

3
2

1
0

20

40

60

80

100 120 140 160

Figure 9.16: Window size evolution for standard TCP with maximum window of 2000

20

40

60

80

100 120 140 160

Figure 9.17: Window size evolution for


DelA k TCP with d = 3, with maximum window of 2000

maximum window size is 2000, the a tual ongestion window does not ex eed the value of 13. We
see that from the gures that in standard TCP, losses are more frequent and more severe (resulting
in timeouts) whereas the d = 3 version of delayed ACK does not give rise to timeouts.
In Figure 9.18 we present the evolution of the ongestion window size for standard TCP with
maximum window size of 3 for the ase of 9 nodes. We know from [18 that a maximum size of
between 2 and 3 should indeed give optimal performan e (and this is on rmed in Figure 9.13).
We see in Figure 9.18 that there are almost no losses. Note that the a tual window size is the
minimum between the ongestion window (depi ted in the Figure) and the maximum window size
(whose value here is 3).
In the previous Figures, all versions using delayed A ks had the default interval of 100mse
(as explained in the Introdu tion). Next, we vary the interval length and he k its impa t on
throughput, see Fig. 9.19. We onsider the delayed ACK version with d = 3. We see that the
default value performs quite well, although for small maximum windows, shorter intervals perform
slightly better, whereas with large maximum window, a larger interval (130ms) is slightly better.
We tried to further in rease the time interval beyond 130ms but then the throughput de reased.
Finally, we onsider the ase of n = 3 nodes. In that ase the hidden terminal phenomenon
does not o ur anymore, so we do not observe TCP losses for any value of window size. Even
then, delayed ACKs an be used to improve onsiderably the performan e. This is illustrated in
Table 9.3 that gives the number of TCP pa kets su essfully re eived within 149 se for n = 3.
Sin e there are no losses, then as long as d is greater than the max window, we expe t to improve
the performan e as d gets larger, sin e TCP pa kets ompete with less ACKs. This is indeed
on rmed in Table 9.3. The improvement that in reases from 10% to 15% as d grows from 2 to
4, does not depend on the maximum window (as long as it is greater than d). However for d = 4
we see, as an be expe ted, that we get a bad performan e for a maximum window of 3, sin e the

9.6.

125

THE INTERACTION OF TCP WITH THE MAC PROTOCOL

40
win.tr

35
30

Int=30ms
Int=80m
Int=100ms
Int=130ms

16

14

25
20

12

15
10

10
5

0
0

20

40

60

80

100 120 140 160

Figure 9.18: Window size evolution for standard TCP (delayed ACK disabled) with 9
nodes and maximum window size of 3
WinMax
3
2000

10

15

20

25

30

35

40

Figure 9.19: The in uen e of Delayed A k interval on TCP throughput, as a fun tion of
the maximum window size. d = 3

Standard TCP Delayed A k Versions


Standard
d=2 d=3 d=4
6068
6602 6763 2699
6094
6565 6779 6888

Table 9.3: Number of transmitter pa kets during 149se for n = 3 as a fun tion of the maximum
window size
destination always needs to wait till the 100ms interval of the Delayed A k option expires in order
to send an ACK (sin e the windows allows for sending only 3 data pa kets).

9.6.4 Modi ation of ns for the ase d > 2

126

CHAPTER 9.

MOBILE NETWORKS

Chapter 10

Classi al queueing models


ns simulator an be used to simulate lassi al queueing models. In the simplest lassi al models,
the time between pa kets arrival is random and has some general probability distribution, and
the time it takes to transmit a pa ket is random as well distributed a ording to some other
distribution. The fa t that the transmission time varies may re e t a situation of a onstant
transmission rate but a varying size of a pa ket. The mathemati al analysis of queueing example
we present here as well as many others an be found [26.

10.1 Simulating an M/M/1, M/D/1 and D/M/1 queues


The queueing example whi h is the simplest for mathemati al analysis is the M=M=1 queue:
interarrival times are exponentially distributed with some parameter, say , and the transmission
duration of a pa ket has an exponential distributioin with another parameter, say . One pa ket
an be transmitted at a time, and the bu er size is in nite. If we denote  = =, the time average
number of pa kets in the system is given by

E [Q =

1 

(10.1)

In Table 10.1 we present a simulation of this queue. The simulation produ es a tra e le out.tr
with all events, and also a monitor-queue tra e alled qm.out, as dis ussed in Se tion 4.3. By
plotting olumns 5 (queue size in pa kets) against olumn 1 (time) we obtain (see Fig. 10.1)
the queue length evolution. The average simulated queue size over 1000se is 9.69117, a good
approximation of the value 10 obtained by (10.1).
Note that we use a simpler way to de lare and manipulate random variables than the one
des ribed in Se tion 2.7: we do not de lare generators and seeds.
It is quite interesting to analyze the simulation results and try to nd the possible reasons for
the di eren e. On e we do so we may nd several reasons for the simulation's impressisions (and
use the on lusions to improve the simulations):

127

128

CHAPTER 10.

CLASSICAL QUEUEING MODELS

set ns [new Simulator


set tf [open out.tr w
$ns tra e-all $tf
set lambda 30.0
set mu
33.0
set n1 [$ns node
set n2 [$ns node
# Sin e pa ket sizes will be rounded to an integer
# number of bytes, we should have large pa kets and
# to have small rounding errors, and so we take large bandwidth
set link [$ns simplex-link $n1 $n2 100kb 0ms DropTail
$ns queue-limit $n1 $n2 100000
# generate random interarrival times and pa ket sizes
set InterArrivalTime [new RandomVariable/Exponential
$InterArrivalTime set avg_ [expr 1/$lambda
set pktSize [new RandomVariable/Exponential
$pktSize set avg_ [expr 100000.0/(8*$mu)
set sr [new Agent/UDP
$ns atta h-agent $n1 $sr
# queue monitoring
set qmon [$ns monitor-queue $n1 $n2 [open qm.out w 0.1
$link queue-sample-timeout
pro finish {} {
global ns tf
$ns flush-tra e
lose $tf
exit 0
}
pro sendpa ket {} {
global ns sr InterArrivalTime pktSize
set time [$ns now
$ns at [expr $time + [$InterArrivalTime value "sendpa ket"
set bytes [expr round ([$pktSize value)
$sr send $bytes
}
set
$ns
$ns
$ns
$ns

sink [new Agent/Null


atta h-agent $n2 $sink
onne t $sr $sink
at 0.0001 "sendpa ket"
at 1000.0 "finish"

$ns run

Table 10.1: t l s ript mm1.t l for simulating an MM1 queue

10.2.

129

FINITE QUEUE

the formula (10.1) ounts the whole pa ket that is being transmitted, where as the simulation
ounts only the fra tion of the transmitted pa ket that is still in the queue. This di eren e
should make the simulated result lower than the exa t one by about 0.5 a pa ket.

On the other hand, the simulated pa kets turn out to be trun ated at the value of 1kbyte,
whi h is the default size of a UDP pa ket. Thus transmission times are a little shorter than
we intended them to be. To orre t that, one should hange the default maximum pa ket
size, for example to 100000. This is done by adding the line
$sr set pa ketSize_ 100000

after the ommand set sr [new Agent/UDP.

The simulation time is not su iently long. With a duration of 20000, we get a mu h more
pre ise value.
80
qm.out using 1:5

70
60
50
40
30
20
10
0
0

100 200 300 400 500 600 700 800 900 1000

Figure 10.1: Evolution of an M/M/1 queue size


The M/D/1 queue is is one where inter-arrival times are exponentially distgributed but transmission times of pa kets are onstant. To simulate it, simply repla e the random variable pktSize
by its average. Similarly, a D/M/1 queue is one where transmission duration has an exponential distribution and interarrival times are onstant. To simulate that, we should repla e the
InterarrivalTime random variable by its average.

10.2 Finite queue


In the above simulation, we used very large bu ers to avoid losses. One an use smaller bu ers
and observe losses. For M/M/1/K queue with K bu ers, the loss probability is given by

K
P (loss) = PK i :
i=0 
The way to ompute the loss probability from the simulation is simply to divide the total number
of losses by the total number of arrivals, both given in the last line of the monitor-queue le.

130

CHAPTER 10.

CLASSICAL QUEUEING MODELS

set ns [new Simulator


set tf [open out.tr w
$ns tra e-all $tf
set
set
set
set

lambda
mu
qsize
duration

30.0
33.0
2
2000

set
set
set
$ns

n1 [$ns node
n2 [$ns node
link [$ns simplex-link $n1 $n2 100kb 0ms DropTail
queue-limit $n1 $n2 $qsize

# generate random interarrival times and pa ket sizes


set InterArrivalTime [new RandomVariable/Exponential
$InterArrivalTime set avg_ [expr 1/$lambda
set pktSize [new RandomVariable/Exponential
$pktSize set avg_ [expr 100000.0/(8*$mu)
set sr [new Agent/UDP
$sr set pa ketSize_ 100000
$ns atta h-agent $n1 $sr
# queue monitoring
set qmon [$ns monitor-queue $n1 $n2 [open qm.out w 0.1
$link queue-sample-timeout
pro finish {} {
global ns tf
$ns flush-tra e
lose $tf
exit 0
}
pro sendpa ket {} {
global ns sr InterArrivalTime pktSize
set time [$ns now
$ns at [expr $time + [$InterArrivalTime value "sendpa ket"
set bytes [expr round ([$pktSize value)
$sr send $bytes
}
set
$ns
$ns
$ns
$ns

sink [new Agent/Null


atta h-agent $n2 $sink
onne t $sr $sink
at 0.0001 "sendpa ket"
at $duration "finish"

$ns run

Table 10.2: t l s ript mm1k.t l for simulating an MM1 queue

10.2.

FINITE QUEUE

131

Adding the ommand $sr set pa ketSize_ 100000 as mentioned in the previous Se tion,
we get very good agreement between the simulation and the formula. For example, for K = 2
we get P (loss) = 0:298 by simulation of duration of 2000se and P (loss) = 0:3025 through the
above formula. For K = 5 we obtain 0.131 and 0.128 by simulation and through the formula,
respe tively. The s ript is given in Table 10.2.
Remark: For K = 1, the simulation does not work well; in that ase all arriving pa kets are
lost!

132

CHAPTER 10.

CLASSICAL QUEUEING MODELS

Chapter 11

Appendix I: Random variables:


ba kground
Random variables with di erent distributions an be reated in ns. Due to its import role in tra
modeling and in network simulation we brie y re all the de nitions and moments of main random
variables in Appendix 11. For more ba kground, one an onslut e.g. http://www.xy oon. om/.
For a random variable (RV) X , we denote Fx (s) = P (X  s), F x (s) = P (X > s) bnd y fx (s)
we denote its density. (We often omit the subs ript x.)
1. Pareto distribution. A Pareto RV is de ned through

F (s) = (k=s) ;
where k is the minimum size and > 0 is the so alled "shape parameter". It is de ned on
the range X  k. The density is given by

k
f (s) = +1 :
s
The expe tation and other moments are

k
;
1
kn
E [X n =
;
n
E [X =

1<

n<

The nth moment is in nite if n  .


The size of les transferred over the Internet is often hara terized with a Pareto distribution
with 1 <  2, see [35, 10. A typi al value is = 1:2 [6. A typi al value for the expe ted
size of a le in Internet transfers is 10Kbits. In the ontext of WEB transfers, typi al values
are = 1:1 and k = 81:5Kbytes (see [13, p.34-35.)
2. The exponential Random variable. An exponentially distributed RV with parameter
is de ned through
F (s) = exp( s); f (s) = exp( s):
All its moments exist and are given by

n!
E [X n = n :

133

134

CHAPTER 11.

APPENDIX I: RANDOM VARIABLES: BACKGROUND

In a WEB transfer, Pareto distributed transfers are typi ally separated with Exponentially
distributed silen e times ("thinking times") with average duriation of 1 = 5se [22.
3. Normal distribution. It is hara terized by two parameters (; 2 ). Its probability density
is given by
" 
#
1
1 s  2
f (s) = exp
2
2

and its rst moments by

E [X = ; E [X 2 = 2 + 2 :

This distribution is mostly used to dis ribe thermal noise that should be taken into a ount
when omputing the signal to noise ratio in radio links.
4. Lognormal distribution. It is hara terized by two parameters (; 2 ). Its density fun tion is given by
" 
#
1 ln(s)  2
exp
2

p 22
:
f (s) =
2 s
and its moments are given by


1
E [X n = exp j + (j)2 :
2

X is lognormally distributed with parameters (; 2 ) if and only if ln(X ) is normally distributed with the same parameters. It an thus be written as X = exp(Y ) where Y 
N (; 2 ). In CDMA wireless ommuni ations, the re eived power from power ontrolled
sour es with fading hannels have lognormal distribution where  is typi ally between 0.3
and 3dB [38.
5. Gamma distribution A Gamma distributed RV with parameters ( ; r) has a probability
density of
r r 1 r
f (s) =
s e
[r
where

is the -fun tion whi h satis es (r) = (r

r
E [X = ;

1)! for r integers. The moments are

nY1
E [X n = n (r + i); n > 1:
i=0

The distribution is de ned on the range 0  s  1, and its parameters are de ned for > 0
and r > 0. In the spe ial ase where r is an integer, this distribution is alled the Erlang
distribution.

Chapter 12

Appendix II: Con den e intervals


In this Appendix we brie y re all the notion of on den e intervals that addresses the question of
how to estimate the orre tness of a simulated result.
A standard way to obtain a better pre ision of performan e measures obtained from simulations
is to take the average of several "independent" runs (independen e an be obtained by using
di erent seeds and generators). Indeed, by the strong law of large number, the average X of n
independent and identi ally distributed values Xi , i = 1; :::; n approa hes the expe tation E [X
whi h we may wish to estimate.
Our goal is to he k how a urate X is as an estimator of hE [X . In parti ular,i we wish to
establish some onstant d su h that the probability that X 2 E [X d; E [X + d be at least
1- , where is some small error probability (say 5%).
The varian e of X is given by
2
V ar(X ) =
n
2
Let  be the varian e of Xi . If we knew , we ould estimate the a ura y of X as a predi tion
of E [X by using the entral limit theorem, whi h implies that

pn X E [X  N (0; 1):


If (x) is the probability that a standard Gaussian RV is not greater than x, then this suggests
that
 p 
 p 
h
i

d n
d n
P X 2 E [X d; E [X + d =

:
(12.1)



h
i

For example, if = 5% then the onstant d that gurantees that P X 2 E [X d; E [X +d 
p
1 = 0:95 is given by d = 1:96= n.
In pra ti e,  is typi ally unknown and has to be estimated together with E [X . One ould
P
use ni=1 (Xi X i )2 =n as an estimator for 2 , but this would give a biased estimator, i.e. an
estimator whose expe ted value di ers from 2 . Instead, the estimator
Pn
(X X i )2
2
S = i=1 i
n 1
turns out to be unbiased, i.e. E [S 2 = 2 , see [33, p. 111. It is alled the sample varian e.
One then uses (12.1) with S repla ing  as an approximation of the probability that X is
within the on den e interval.

135

136

CHAPTER 12.

APPENDIX II: CONFIDENCE INTERVALS

The next s ript in awk an be used to ompute the sample average of an output le, where we
average over the numbers appearing in the 3rd olumn:
BEGIN { FS = "\t"} { nl++ } { s = s + $3 } END {print "del : " s/nl}

If this s ript is written in a le alled "thpR.awk" and the values of Xi 's are given in the third
olumn of a le alled "a40n" then one should type
awk -f thpR.awk a40n

in order to get X .
The following then omputes the on den e itnerval related to = 5%:
BEGIN { FS = "\t"} {ln++}{ d = $3 - t } { s2 = s2 + d*d } END \
{s=sqrt(s2/(ln-1)); print "sample varian e: " s " \
Conf. Int. 95%: " t "+/-" 1.96*s/sqrt(ln)}

If "ConfInt.awk" is the name of the le ontainig this s ript, type


awk -v t=XXX -f ConfInt.awk a40n

where instead of XXX one should put the value of X . This will give both the sample varian e as
well as the required on den e interval.

Bibliography
[1 E. Altman, "A stateless approa h for improving TCP performan e using Di serv", submitted.
[2 E. Altman and T. Jimenez, \Simulation analysis of RED with short lived TCP onne tions",
submitted.
[3 E. Altman and T. Jimenez, \Improving TCP over multihop networks using delayed ACK",
submitted.
[4 A. Ballardie, "Core Based Trees (CBT) Multi ast Routing Ar hite ture", Internet RFC 2201
(Experimental), September 1997.
[5 S. Blake, D. Bla k, M. Carlson, E. Davies, Z. Wang and W. Weiss, \An ar hite ture for
di erentiated servi es", RFC 2475, De . 1998.
[6 T. Bonald and J. Roberts, "Performan e modeling of elasti tra in overload", ACM Sigmetri s, pp. 342-343, 2001.
[7 B. Braden et al., \Re ommendations on Queue Management and Congestion Avoidan e in
the Internet", April 1998. Available as RFC 2309 at ftp://ftp.isi.edu/in-notes/rf 2309.txt.
[8 D. D. Clark and W. Fang. Expli it Allo ation of Best-E ort Pa ket Delivery Servi e.
IEEE/ACM Trans on Networking, 6(4), 362-373, August 1998.
[9 M. S. Corson, S. Papademetriou, P. Papadopolous, V. D. Park and A. Qayyum, \An Internet
Manet En apsulation Proto ol (IMEP) Spe i ation", Internet draft, draft-ietf-manet-imepspe 01.txt, August 1998.
[10 M. Crovella and A. Bestravos, "Self-similarity in World Wide Web tra : Eviden e and
possible ause", ACM Sigmetri s, 1996.
[11 S. Deering, D. Estrin, D. Farina i, V. Ja obson, Ching-Gung Liu, and L. Wei. An ar hite ture for wise-area multi ast routing. Te hni al Report USC-SC-94-565, Computer S ien e
Department, University of Southern California, Los Angeles, CA 90089., 1994.
[12 C. Diot, W. Dabbous, and J. Crow roft. Multipoint ommuni ation:a survey of proto ols,
fun tions and me hanisms. IEEE Journal on Sele ted Areas in Communi ations, 15(3), Apr
1997.
[13 ETSI, Universal Mobile Tele ommuni ation System (UMTS); Sele tion pro edures for the
hoi e of radio transmission te hnologies of the UMTS, UMTS 30.03 Version 3.2.0, 1998-04.
Available (publi domain) at
http://www.etsi.org/getastandard/home.htm
[14 K. Fall and K. Varadhan, The ns Manual, available at http://www.isi.edu/nsnam/ns/.
137

138

BIBLIOGRAPHY

[15 W. Fang, N. Seddigh and B. Nandy, A Time Sliding Window Three Colour Marker
(TSWTCM), RFC 2859, http://rf .sunsite.dk/rf /rf 2859.html, June 2000.
[16 Floyd, S., and V. Ja obson, \Random Early Dete tion gateways for
Congestion Avoidan e" V.1 N.4, August 1993, p. 397-413. Available at
http://www.i ir.org/ oyd/papers/red/red.html
[17 S. Floyd, R. Gummadi and S. Shenker, \Adaptive Red: an algorithm for in reasing the
robustness of RED's a tive queue management", submitted.
[18 Z. Fu, P. Zerfos, H. Luo, S. Lu, L. Zhang, M. Gerla, \The impa t of multihop wireless hannel on TCP throughput and loss", Pro . of IEEE INFOCOM, 2003. Available at
www. s.u la.edu/wing/publi ation/publi ation.html
[19 J. Heinanen, F. Baker, W. Weiss, J. Wro lawski, \Assured forwarding PHB group", RFC
2597, June 1999.
[20 J. Heinanen and R. Guerin, "A single rate three olor marker", RFC 2697,
http://rf .sunsite.dk/rf /rf 2697.html Sept. 1999.
[21 J. Heinanen and R. Guerin, "A two rate three olor marker", RFC 2698,
http://rf .sunsite.dk/rf /rf 2698.html Sept. 1999.
[22 D. P. Heyman, T. V. Lakshman and A. L. Neidhardt, \A new method for analysing feedba kbased proto ols with appli ations to engineering web tra over the Internet", Pro . ACM
Sigmetri s, Seattle, 1997.
[23 Christian Huitema. Routing in the Internet, Prenti e Hall, April 1995. 2nd Edition: 1999.
[24 V. Ja obson. Congestion avoidan e and ontrol. In ACM SIGCOMM 88, pages 273{288,
1988.
[25 D. B. Johnson, D. A. Maltz, Y.-C. Hu, J. G. Jet heva, \The Dynami Sour e Routing Proto ol for Mobile Ad Ho Networks (DSR)", IETF MANET Working Group
INTERNET-DRAFT, available at http://www.ietf.org/internet-drafts/draft-ietf-manet-dsr07.txt 21 February, 2002.
[26 L. Kleinro k. Queueing systems. John Wiley, New York, 1976.
[27 W. Noureddine and F. Tobagi, \Improving the Performan e of Intera tive TCP Appli ations
using Servi e Di erentiation", Pro eedings of IEEE Info om, New-York, USA, June 2002.
[28 V. D. Park and M. S. Corson, \Temporally-Ordered Routing Algorithm (TORA) version 1:
fun tional spe i ations", Internet draft, draft-ietf-manet-tora-spe -01.txt, August 1998.
[29 V. D. Park and M. S. Corson, \A performan e onparison of the temporally-ordered routing
algorithm and ideal link-state routing", Pro eedings of IEEE Symposium on Computers and
Communi ation, June 1998.
[30 C. E. Perkins and S. R. Das, \Ad ho On-Demand Distan e Ve tor (AODV) Routing", IETF
MANET Working Group INTERNET-DRAFT, available on http://www.ietf.org/internetdrafts/draft-ietf-manet-aodv-11.txt, 19 June, 2002.
[31 C. E. Perkins and P. Bhagwat, \Highly dynami destination-sequen ed distan e-ve tor routing (DSDV) for mobile omputers", Pro eedings of SIGCOMM, pp. 234-244, 1994.

BIBLIOGRAPHY

139

[32 P. Pieda, J. Ethridge, M. Baines and F. Shallwani, \A network simulator di erentiated servi es implementation", Open IP, Nortel Networks, July 26, 2000.
[33 S. M. Ross, Simulation, 3rd Edition, A ademi Press, San-Diego, London, Boston, New York,
Sydney, Tokyo, Toronto, 2002.
[34 S. Sahu, P. Nain, C. Diot, V. Firoiu and D. F. Towsley", "On a hievable servi e di erentiation
with token bu ket marking for TCP", Pro . ACM SIGMETRICS'00, Santa Clara, CA, June
2000.
[35 B. Sikdar, S. Kalyanaraman and K. S. Vastola, \An Integrated Model for the Laten y
and Steady-State Throughput of TCP Conne tions", Performan e Evaluation, v.46, no.23, pp.139-154, September 2001.
[36 P. Sinha, Routing and transport layer proto ols for wireless networks, Ph.D. Thesis, Univ. of
Illinois at Urbana-Champaign, Computer S ien e, 2001.
[37 D. Thaler, D. Estrin, D. Meyer (Editors), "Border Gateway Multi ast Proto ol (BGMP):
Proto ol Spe i ation", Internet Draft <draft-ietf-bgmp-spe -02>, work in progress, November
2000.
[38 A. J. Viterbi, A. M. Viterbi and E. Zehavi. Performan e of power- ontrolled wideband terrestrial digital ommuni ation. IEEE Transa tions on Communi ations, 41(4):559{69, April
1993.
[39 D. Waitzman, C. Partridge, and S.E. Deering. Distan e Ve tor Multi ast Routing Proto ol,
RFC 1075 edition, 1988.

Index
ad-ho networks, 107
Ad-ho proto ols
AODV, 108
DSDV, 108
DSR, 109
TORA, 109
Agent
LossMonitor, 67
AODV, 107, 108
awk, 29
omputing averages, 29
standard deviation, 29

grep, 30
in t l, 34
IEEE 802.12, 103
IEEE 802.14, 103
IEEE 802.3, 103
IEEE 802.9, 103
IEEE802.11, 119
ACK, 119
CTS, 119
DATA, 119
RTS, 119
Lo al area networks, 103
loop, 43
LossMonitor, 67

BST, 67
CBR, 17
entralized, 67
multi ast, 63
on den e intervals, 135
CrtM ast, 63, 67
CSMA/CD, 104

MAC
IEEE802.11, 119
proto ols, 103
monitor
ow, 83
number of sessions, 47
queue, 38
queue size, 47
queue, NAM, 23
queue, RED, 73
window, 19
monitor-queue, 47
MRED, 90
multi ast
BST, 67
entralized, 63, 67
CrtM ast, 63, 67
Dense Mode, 63, 67
DM proto ol, 64
DVMRP, 63, 67
PIM-DM, 63, 67
PIM-SM, 63
PruneTimeout, 67
Rendezvous Point, 63
routing, 62

defaults parameters, 7
Dense Mode, 63, 67
di erentiated servi es, 89
di serv, 89
DM proto ol, 64
done instpro , 53
DSDV, 107, 108
DSR, 107, 109
DVMRP, 63, 67
error model, 38
Ethernet, 104
Exponential On-O , 18
failure
of links, 62
of nodes, 62
ow monitor, 83
FTP, 16
gnuplot, 33
140

141

INDEX

Sparse Mode, 63
NAM
queue monitoring, 23
ndatabytes, 54
ndatapa k, 53
network dyami s, 62
nrexmitbytes, 54
nrexmitpa kets, 54
number of sessions
monitor, 47
open, 8, 13
Pareto On-O , 18
perl, 31
throughput example, 31
PHB table, 91
PIM-DM, 63, 67
PIM-SM, 63
print, 9
prune, 64
PruneTimeout, 67
queue
DM1, 129
MD1, 129
MM1, 127
queue monitor, 38
queue-size
monitor, 47
random, 43
random variable
generator, 26
seed, 26
random variables, 26, 127, 133
distribution, 133
Exponential, 133
gamma, 134
lognormal, 134
moments, 133
normal, 134
Pareto, 133
RED, 71
Rendezvous Point, 63
RIO, 90

bst.t l, 67
di s.t l, 101
drptail.t l, 78
ex1.t l, 19
ex2.t l, 59
ex3.t l, 43
pimdm.t l, 64
rdrop.t l, 39
red.t l, 83
rv1.t l, 27
shortRed.t l, 83
shortT p.t l, 47
shortT p2.t l, 54
t pwD.t l, 120
wrls-dsdv.t l, 113
t l s ripts
mm1.t l, 127
mm1k.t l, 129
TCP, 16
a knowledgements, 35
ongestion window, 36
des ription, 35
done, 53
losses, 36
obje tives, 35
syn pa kets, 37
threshold Wth , 37
throughput, 42
timer, 36
window, 35
throughput
TCP, 42
TORA, 109
TORA/IMPE, 107
tra e
grep, 34
tra e driven tra , 19
tra e-all, 13
tra e-queue, 26
window size, 43
tra
Exponential On-O , 18
Pareto On-O , 18
tra e driven, 19

Sparse Mode, 63

UDP, 17
unix
in t l, 34

t l les

window

142

INDEX

monitor, 19
xgraph, 34

Potrebbero piacerti anche