You are on page 1of 27

1.

Introduction
NS (Version 2) is an open source network simulation tool. It is an object oriented,
discrete event driven simulator written in C++ and tcl. !"e primar# use o$ NS is in
network researc"es to simulate various t#pes o$ wired%wireless local and wide area
networks& to implement network protocols suc" as !C' and ('), tra$$ic source be"avior
suc" as *!', !elnet, +eb, C,- and V,-, router .ueue mana/ement mec"anism suc" as
)rop !ail, -0) and C,1, routin/ al/orit"ms suc" as )ijkstra, and man# more.
Ns2 is written in C++ and tcl to separate t"e control and data pat" implementations.
!"e simulator supports a class "ierarc"# in C++ (t"e compiled "ierarc"#) and a
correspondin/ "ierarc"# wit"in t"e tcl interpreter (interpreted "ierarc"#).
!"e reason w"# ns2 uses two lan/ua/es is t"at di$$erent tasks "ave di$$erent
re.uirements2 *or e3ample simulation o$ protocols re.uires e$$icient manipulation o$
b#tes and packet "eaders makin/ t"e run4time speed ver# important. n t"e ot"er "and,
in network studies w"ere t"e aim is to var# some parameters and to .uickl# e3amine a
number o$ scenarios t"e time to c"an/e t"e model and run it a/ain is more important.
In ns2, C++ is used $or detailed protocol implementation and in /eneral $or suc" cases
w"ere ever# packet o$ a $low "as to be processed. *or instance, i$ #ou want to implement
a new .ueuin/ discipline, t"en C++ is t"e lan/ua/e o$ c"oice. tcl, on t"e ot"er "and, is
suitable $or con$i/uration and setup. tcl runs .uite slowl#, but it can be c"an/ed ver#
.uickl# makin/ t"e construction o$ simulations easier. In ns2, t"e compiled C++ objects
can be made available to t"e tcl interpreter. In t"is wa#, t"e read#4made C++ objects
can be controlled $rom t"e !cl level.
1.1. Otcl basics
!"is c"apter introduces t"e s#nta3 and some basic commands o$ t"e tcl lan/ua/e
t"at are used b# ns2. It is important to understand "ow tcl works be$ore movin/ to t"e
part t"at deals wit" t"e creation o$ t"e actual simulation scenario.
1.1.1. Assigning values to variables
5
In tcl, values can be stored to variables and t"ese values can be $urt"er used in
commands2
set a 5
set b [expr $a/5]
In t"e $irst line, t"e variable a is assi/ned t"e value 678. In t"e second line, t"e result
o$ t"e command 9e3pr :a%7;, w"ic" e.uals 5, is t"en used as an ar/ument to anot"er
command, w"ic" in turn assi/ns a value to t"e variable b. !"e 6:8 si/n is used to obtain a
value contained in a variable and s.uare brackets are an indication o$ a command
substitution.
1.1.2. Procedures
ne can de$ine new procedures wit" t"e proc command. !"e $irst ar/ument to proc is
t"e name o$ t"e procedure and t"e second ar/ument contains t"e list o$ t"e ar/ument
names to t"at procedure. *or instance a procedure t"at calculates t"e sum o$ two numbers
can be de$ined as $ollows2
proc sum {a b} {
expr $a + $b
}
!"e ne3t procedure calculates t"e $actorial o$ a number2
proc factorial a {
if {$a <= 1} {
return 1
}
#here the procedure is called aain
expr $x ! [factorial [expr $x"1]]
}
It is also possible to /ive an empt# strin/ as an ar/ument list. <owever, in t"is case
t"e variables t"at are used b# t"e procedure "ave to be de$ined as /lobal. *or instance2
proc sum {} {
lobal a b
expr $a + $b
2
}
1.1.3. Files and lists
In tcl, a $ile can be opened $or readin/ wit" t"e command2
set testfile [open test#dat r]
!"e $irst line o$ t"e $ile can be stored to a list wit" a command2
ets $testfile list
Now it is possible to obtain t"e elements o$ t"e list wit" commands (numberin/ o$
elements starts $rom =) 2
set first [lindex $list $]
set second [lindex $list 1]
Similarl#, a $ile can be written wit" a puts command2
set testfile [open test#dat %]
puts $testfile &testi'
1.1.4. Calling subprocesses
!"e command e3ec creates a subprocess and waits $or it to complete. !"e use o$ e3ec
is similar to /ivin/ a command line to a s"ell pro/ram. *or instance, to remove a $ile2
exec rm $testfile
!"e e3ec command is particularl# use$ul w"en one wants to call a tcl4script $rom
wit"in anot"er tclscript. *or instance, in order to run t"e tcl4script e3ample.tcl multiple
times wit" t"e value o$ t"e parameter 6test8 ran/in/ $rom 5 to 5=, one can t#pe t"e
$ollowin/ lines to anot"er tcl4script2
for {set ind 1} {$ind <= 1$} {incr ind} {
set test $ind
exec ns example#tcl test
}
>
1.2. Creating the topology
!o be able to run a simulation scenario, a network topolo/# must $irst be created. In
ns2, t"e topolo/# consists o$ a collection o$ nodes and links.
,e$ore t"e topolo/# can be set up, a new simulator object must be created at t"e
be/innin/ o$ t"e script wit" t"e command2
set ns [ne% (imulator]
!"e simulator object "as member $unctions t"at enable creatin/ t"e nodes and t"e
links, connectin/ a/ents etc. ?ll t"ese basic $unctions can be $ound $rom t"e class
Simulator. +"en usin/ $unctions belon/in/ to t"is class, t"e command be/ins wit" 6:ns8,
since ns was de$ined to be a "andle to t"e Simulator object.
1.2.1. Nodes
New node objects can be created wit" t"e command2
set n$ [$ns node]
set n1 [$ns node]
set n) [$ns node]
set n* [$ns node]
!"e member $unction o$ t"e Simulator class, called 6node8 creates $our nodes and
assi/ns t"em to t"e "andles n=, n5, n2 and n>. !"ese "andles can later be used w"en
re$errin/ to t"e nodes. I$ t"e node is not a router but an end s#stem, tra$$ic a/ents (!C',
()' etc.) and tra$$ic sources (*!',C,- etc.) must be set up, i.e, sources need to be
attac"ed to t"e a/ents and t"e a/ents to t"e nodes, respectivel#.
1.2.2. Agents applications and tra!!ic sources
!"e most common a/ents used in ns2 are ()' and !C' a/ents. In case o$ a !C'
a/ent, several t#pes are available. !"e most common a/ent t#pes are2
?/ent%!C' @ a !a"oe !C' sender
?/ent%!C'%-eno @ a -eno !C' sender
?/ent%!C'%Sack5 @ !C' wit" selective acknowled/ement
A
!"e most common applications and tra$$ic sources provided b# ns2 are2
?pplication%*!' @ produces bulk data t"at !C' will send
?pplication%!ra$$ic%C,- @ /enerates packets wit" a constant bit rate
?pplication%!ra$$ic%03ponential @ durin/ o$$4periods, no tra$$ic is sent. )urin/ on4
periods, packets are /enerated wit" a constant rate. !"e len/t" o$ bot" on and o$$4
periods is e3ponentiall# distributed.
?pplication%!ra$$ic%!race @ !ra$$ic is /enerated $rom a trace $ile, w"ere t"e siBes
and interarrival times o$ t"e packets are de$ined.
In addition to t"ese read#4made applications, it is possible to /enerate tra$$ic b# usin/
t"e met"ods provided b# t"e class ?/ent. *or e3ample, i$ one wants to send data over
()', t"e met"od
send+int nb,tes-
can be used at t"e tcl4level provided t"at t"e udp4a/ent is $irst con$i/ured and
attac"ed to some node.
,elow is a complete e3ample o$ "ow to create a C,- tra$$ic source usin/ ()' as
transport protocol and attac" it to node n=2
set udp$ [ne% .ent//01]
$ns attach"aent $n$ $udp$
set cbr$ [ne% .pplication/2raffic/345]
$cbr$ attach"aent $udp$
$cbr$ set pac6et7si8e7 1$$$
$udp$ set pac6et7si8e7 1$$$
$cbr$ set rate7 1$$$$$$
?n *!' application usin/ !C' as a transport protocol can be created and attac"ed to
node n5 in muc" t"e same wa#2
set tcp1 [ne% .ent/231]
$ns attach"aent $n1 $tcp1
set ftp1 [ne% .pplication/921]
$ftp1 attach"aent $tcp1
$tcp1 set pac6et7si8e7 1$$$
7
!"e ()' and !C' classes are bot" c"ild4classes o$ t"e class ?/ent. +it" t"e
e3pressions 9new ?/ent%!C'; and 9new ?/ent%()'; t"e properties o$ t"ese classes can
be combined to t"e new objects udp= and tcp5. !"ese objects are t"en attac"ed to nodes
n= and n5. Ne3t, t"e application is de$ined and attac"ed to t"e transport protocol. *inall#,
t"e con$i/uration parameters o$ t"e tra$$ic source are set. In case o$ C,-, t"e tra$$ic can
be de$ined b# parameters rateC (or e.uivalentl# intervalC, determinin/ t"e interarrival
time o$ t"e packets), packetSiBeC and randomC . +it" t"e randomC parameter it is
possible to add some randomness in t"e interarrival times o$ t"e packets. !"e de$ault
value is =, meanin/ t"at no randomness is added.
1.2.3. "ra!!ic #in$s
I$ t"e in$ormation $lows are to be terminated wit"out processin/, t"e udp and tcp
sources "ave to be connected wit" tra$$ic sinks. ? !C' sink is de$ined in t"e class
?/ent%!C'Sink and an ()' sink is de$ined in t"e class ?/ent%Null.
? ()' sink can be attac"ed to n2 and connected wit" udp= in t"e $ollowin/ wa#2
set null [ne% .ent/:ull]
$ns attach"aent $n) $null
$ns connect $udp$ $null
? standard !C' sink t"at creates one acknowled/ement per a received packet can be
attac"ed to n> and connected wit" tcp5 wit" t"e commands2
set sin6 [ne% .ent/(in6]
$ns attach"aent $n* $sin6
$ns connect $tcp1 $sin6
!"ere is also a s"orter wa# to de$ine connections between a source and t"e destination
wit" t"e command2
$ns create"connection <srct,pe; <src; <dstt,pe; <dst; <p6tclass;
*or e3ample, to create a standard !C' connection between n5 and n> wit" a class I)
o$ 52
$ns create"connection 231 $n1 231(in6 $n* 1
D
ne can ver# easil# create several tcp4connections b# usin/ t"is command inside a
$or4loop.
1.2.4. %in$s
Einks are re.uired to complete t"e topolo/#. In ns2, t"e output .ueue o$ a node is
implemented as part o$ t"e link, so w"en creatin/ links t"e user also "as to de$ine t"e
.ueue4t#pe.
9iure ) <in6 in ns)
*i/ure 2 s"ows t"e construction o$ a simple3 link in ns2. I$ a duple34link is created,
two simple3 links will be created, one $or eac" direction. In t"e link, packet is $irst
en.ueued at t"e .ueue. ?$ter t"is, it is eit"er dropped, passed to t"e Null ?/ent and $reed
t"ere, or de.ueued and passed to t"e )ela# object w"ic" simulates t"e link dela#. *inall#,
t"e !!E (time to live) value is calculated and updated.
Einks can be created wit" t"e $ollowin/ command2
$ns duplex/simplex"lin6 endpoint1 endpoint) band%idth dela, =ueue"t,pe
*or e3ample, to create a duple34link wit" )rop!ail .ueue mana/ement between n=
and n22
$ns duplex"lin6 $n$ $n) 15>b 1$ms 0rop2ail
Creatin/ a simple34link wit" -0) .ueue mana/ement between n5 and n>2
$ns simplex"lin6 $n1 $n* 1$>b 5ms 5?0
F
!"e values $or bandwidt" can be /iven as a pure number or b# usin/ .uali$iers k
(kilo), G (me/a), b (bit) and , (b#te). !"e dela# can also be e3pressed in t"e same
manner, b# usin/ m (milli) and u (mikro) as .uali$iers. !"ere are several .ueue
mana/ement al/orit"ms implemented in ns2, but in t"is e3ercise onl# )rop!ail and -0)
will be needed.
1.3. "racing and &onitoring
In order to be able to calculate t"e results $rom t"e simulations, t"e data "as to be
collected some"ow. NS2 supports two primar# monitorin/ capabilities2 traces and
monitors. !"e traces enable recordin/ o$ packets w"enever an event suc" as packet drop
or arrival occurs in a .ueue or a link. !"e monitors provide a means $or collectin/
.uantities, suc" as number o$ packet drops or number o$ arrived packets in t"e .ueue. !"e
monitor can be used to collect t"ese .uantities $or all packets or just $or a speci$ied $low
(a $low monitor).
1.3.1. "races
?ll events $rom t"e simulation can be recorded to a $ile wit" t"e $ollowin/
commands2
set trace7all [open all#dat %]
$ns trace"all $trace7all
$ns flush"trace
close $trace7all
*irst, t"e output $ile is opened and a "andle is attac"ed to it. !"en t"e events are
recorded to t"e $ile speci$ied b# t"e "andle. *inall#, at t"e end o$ t"e simulation t"e trace
bu$$er "as to be $lus"ed and t"e $ile "as to be closed. !"is is usuall# done wit" a separate
$inis" procedure. I$ links are created a$ter t"ese commands, additional objects $or tracin/
(0n.!, )e.!, )rp! and -ecv!) will be inserted into t"em.
H
9iure * <in6 in ns) %hen tracin is enabled
!"ese new objects will t"en write to a trace $ile w"enever t"e# receive a packet. !"e
$ormat o$ t"e trace $ile is $ollowin/2
+ 1.84375 0 2 cbr 210 ------- 0 0.0 3.1 225 610
- 1.84375 0 2 cbr 210 ------- 0 0.0 3.1 225 610
r 1.84471 2 1 cbr 210 ------- 1 3.0 1.0 195 600
r 1.84566 2 0 ack 40 ------- 2 3.2 0.1 82 602
+ 1.84566 0 2 tcp 1000 ------- 2 0.1 3.2 102 611
- 1.84566 0 2 tcp 1000 ------- 2 0.1 3.2 102 611
+ 2 en.ueue
4 2 de.ueue
d 2 drop
r 2 receive
!"e $ields in t"e trace $ile are2 t#pe o$ t"e event, simulation time w"en t"e event
occurred, source and destination nodes, packet t#pe (protocol, action or tra$$ic source),
packet siBe, $la/s, $low id, source and destination addresses, se.uence number and packet
id. In addition to tracin/ all events o$ t"e simulation, it is also possible to create a trace
object between a particular source and a destination wit" t"e command2
$ns create"trace <t,pe; <file; <src; <dest;
w"ere t"e t#pe can be, $or instance,
0n.ue @ a packet arrival ($or instance at a .ueue)
)e.ue @ a packet departure ($or instance at a .ueue)
)rop @ packet drop
-ecv @ packet receive at t"e destination
!racin/ all events $rom a simulation to a speci$ic $ile and t"en calculatin/ t"e desired
.uantities $rom t"is $ile $or instance b# usin/ perl or awk and Gatlab is an eas# wa# and
I
suitable w"en t"e topolo/# is relativel# simple and t"e number o$ sources is limited.
<owever, wit" comple3 topolo/ies and man# sources t"is wa# o$ collectin/ data can
become too slow. !"e trace $iles will also consume a si/ni$icant amount o$ disk space.
1.3.2. 'onitors
+it" a .ueue monitor it is possible to track t"e statistics o$ arrivals, departures and
drops in eit"er b#tes or packets. ptionall# t"e .ueue monitor can also keep an inte/ral o$
t"e .ueue siBe over time.
*or instance, i$ t"ere is a link between nodes n= and n5, t"e .ueue monitor can be set
up as $ollows2
set =mon$ [$ns monitor"=ueue $n$ $n1]
!"e packet arrivals and b#te drops can be tracked wit" t"e commands2
set parr [$=mon$ set parri@als7]
set bdrop [$=mon$ set bdrops7]
,esides assi/nin/ a value to a variable t"e set command can also be used to /et t"e
value o$ a variable. *or e3ample "ere t"e set command is used to /et t"e value o$ t"e
variable 6parrivals8 de$ined in t"e .ueue monitor class.
? $low monitor is similar to t"e .ueue monitor but it keeps track o$ t"e statistics $or a
$low rat"er t"an $or a//re/ated tra$$ic. ? classi$ier $irst determines w"ic" $low t"e packet
belon/s to and t"en passes t"e packet to t"e $low monitor.
!"e $lowmonitor can be created and attac"ed to a particular link wit" t"e commands2
set fmon [$ns ma6eflo%mon 9id]
$ns attach"fmon [$ns lin6 $n1 $n*] $fmon
Notice t"at since t"ese commands are related to t"e creation o$ t"e $low4monitor, t"e
commands are de$ined in t"e Simulator class, not in t"e *lowmonitor class. !"e variables
and commands in t"e *lowmonitor class can be used a$ter t"e monitor is created and
attac"ed to a link. *or instance, to dump t"e contents o$ t"e $lowmonitor (all $lows)2
$fmon dump
5=
I$ #ou want to track t"e statistics $or a particular $low, a classi$ier must be de$ined so
t"at it selects t"e $low based on its $low id, w"ic" could be $or instance 52
set fclassifier [$fmon classifier]
set flo% [$fclassifier loo6up auto $ $ 1]
1.4. Controlling the si&ulation
?$ter t"e simulation topolo/# is created, a/ents are con$i/ured etc., t"e start and stop
o$ t"e simulation and ot"er events "ave to be sc"eduled. !"e simulation can be started
and stopped wit" t"e commands
$ns at $simtime &finish'
$ns run
!"e $irst command sc"edules t"e procedure $inis" at t"e end o$ t"e simulation, and
t"e second command actuall# starts t"e simulation. !"e $inis" procedure "as to be
de$ined to $lus" t"e trace bu$$er, close t"e trace $iles and terminate t"e pro/ram wit" t"e
e3it routine. It can optionall# start N?G (a /rap"ical network animator), post process
in$ormation and plot t"is in$ormation.
!"e $inis" procedure "as to contain at least t"e $ollowin/ elements2
proc finish {} {
lobal ns trace7all
$ns flush"trace
close $trace7all
exit $
}
t"er events, suc" as t"e startin/ or stoppin/ times o$ t"e clients can be sc"eduled in
t"e $ollowin/ wa#2
$ns at $#$ &cbr$ start'
$ns at 5$#$ &ftp1start'
$ns at $simtime &cbr$ stop'
$ns at $simtime &ftp1 stop'
55
I$ #ou "ave de$ined #our own procedures, #ou can also sc"edule t"e procedure to start
$or e3ample ever# 7 seconds in t"e $ollowin/ wa#2
proc example {} {
lobal ns
set inter@al 5
A#
A
$ns at [expr $no% + $inter@al] &example'
}
2. #i&ple #i&ulation ()a&ple
!"is section presents a simple NS simulation script and e3plains w"at eac" line does.
03ample > is an !cl script w"ic" creates t"e simple network con$i/uration and runs t"e
simulation scenario in *i/ure A. !o run t"is simulation, cop# t"e code in 03ample > in a
$ile named Jns4simple.tclJ and t#pe Jns ns4simple.tclJ at s"ell prompt.
9iure B# ? Simple Network !opolo/# and Simulation Scenario
!"e network consists o$ A nodes (n=, n5, n2, n>) as s"own in above $i/ure. !"e
duple3 links between n= and n2, and n5 and n2 "ave 2 Gbps o$ bandwidt" and 5= ms o$
dela#. !"e duple3 link between n2 and n> "as 5.F Gbps o$ bandwidt" and 2= ms o$ dela#.
0ac" node uses a )rop!ail .ueue, o$ w"ic" t"e ma3imum siBe is 5=. ? JtcpJ a/ent is
52
attac"ed to n=, and a connection is establis"ed to a tcp JsinkJ a/ent attac"ed to n>. ?s
de$ault, t"e ma3imum siBe o$ a packet t"at a JtcpJ a/ent can /enerate is 5K,#te. ? tcp
JsinkJ a/ent /enerates and sends ?CK packets to t"e sender (tcp a/ent) and $rees t"e
received packets. ? JudpJ a/ent t"at is attac"ed to n5 is connected to a JnullJ a/ent
attac"ed to n>. ? JnullJ a/ent just $rees t"e packets received. ? J$tpJ and a JcbrJ tra$$ic
/enerator are attac"ed to JtcpJ and JudpJ a/ents respectivel#, and t"e JcbrJ is con$i/ured
to /enerate 5 K,#te packets at t"e rate o$ 5 Gbps. !"e JcbrJ is set to start at =.5 sec and
stop at A.7 sec, and J$tpJ is set to start at 5.= sec and stop at A.= sec.
#Create a simulator object
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
gloal ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Eecute NAM on the trace file
e!ec nam out.nam "
e!it #
}
#Create four nodes
set n# [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n$ [$ns node]
#Create lin!s between the nodes
$ns duple!-lin% $n# $n2 2& 1#ms 'rop(ail
$ns duple!-lin% $n1 $n2 2& 1#ms 'rop(ail
$ns duple!-lin% $n2 $n$ 1.)& 2#ms 'rop(ail
#"et #ueue "i$e of lin! (n%&n') to ()
$ns *ueue-limit $n2 $n$ 1#
+,i-e node position .for /0&1
$ns duple!-lin%-op $n# $n2 orient right-down
$ns duple!-lin%-op $n1 $n2 orient right-up
$ns duple!-lin%-op $n2 $n$ orient right
5>
#Monitor the *ueue for lin! (n%&n')+ (for NAM)
$ns duple!-lin%-op $n2 $n$ *ueue2os #.3
#"etup a ,C- connection
set tcp [new 0gent4(52]
$tcp set class6 2
$ns attach-agent $n# $tcp
set sin% [new 0gent4(52Sin%]
$ns attach-agent $n$ $sin%
$ns connect $tcp $sin%
$tcp set fid6 1
#"etup a .,- o/er ,C- connection
set ftp [new 0pplication47(2]
$ftp attach-agent $tcp
$ftp set t8pe6 7(2
#"etup a 0D- connection
set udp [new 0gent49'2]
$ns attach-agent $n1 $udp
set null [new 0gent4/ull]
$ns attach-agent $n$ $null
$ns connect $udp $null
$udp set fid6 2
#"etup a C12 o/er 0D- connection
set cr [new 0pplication4(raffic45BR]
$cr attach-agent $udp
$cr set t8pe6 5BR
$cr set pac%et6si:e6 1###
$cr set rate6 1m
$cr set random6 false
#"chedule e/ents for the C12 and .,- a3ents
$ns at #.1 ;$cr start;
$ns at 1.# ;$ftp start;
$ns at <.# ;$ftp stop;
$ns at <.3 ;$cr stop;
#Detach tcp and sin! a3ents (not reall4 necessar4)
$ns at <.3 ;$ns detach-agent $n# $tcp = $ns detach-agent
$n$ $sin%;
#Call the finish procedure after 5 seconds of simulation
time
$ns at 3.# ;finish;
#-rint C12 pac!et si$e and inter/al
puts ;5BR pac%et si:e > [$cr set pac%et6si:e6];
puts ;5BR inter-al > [$cr set inter-al6];
#2un the simulation
$ns run
5A
?xample *# ? Simple NS Simulation Script
!"e $ollowin/ is t"e e3planation o$ t"e script above. In /eneral, an NS script starts
wit" makin/ a Simulator object instance.
set ns 9new Simulator;2 /enerates an NS simulator object instance, and assi/ns it
to variable ns (italics is used $or variables and values in t"is section). +"at t"is
line does is t"e $ollowin/2
o Create a sc"eduler (de$ault is calendar sc"eduler)
!"e JSimulatorJ object "as member $unctions t"at do t"e $ollowin/2
o Create compound objects suc" as nodes and links (described later)
o Connect network component objects created (e3. attac"4a/ent)
o Set network component parameters (mostl# $or compound objects)
o Create connections between a/ents (e3. make connection between a JtcpJ
and JsinkJ)
o Speci$# N?G displa# options
o 0tc.
Gost o$ member $unctions are $or simulation setup and sc"edulin/, "owever some o$
t"em are $or t"e N?G displa#. !"e JSimulatorJ object member $unction implementations
are located in t"e Jns42%tcl%lib%ns4lib.tclJ $ile.
$ns color fid color2 is to set color o$ t"e packets $or a $low speci$ied b# t"e $low id
($id). !"is is $or t"e N?G displa#, and "as no e$$ect on t"e actual simulation.
$ns namtrace4all file-descriptor2 It tells t"e simulator to record simulation traces
in N?G input $ormat. It also /ives t"e $ile name t"at t"e trace will be written to
later b# t"e command $ns $lus"4trace. Similarl#, t"e member $unction trace4all is
$or recordin/ t"e simulation trace in a /eneral $ormat.
proc finish LM2 is called a$ter t"is simulation is over b# t"e command $ns at 7.=
JfinishJ. In t"is $unction, post4simulation processes are speci$ied.
set n0 9$ns node;2 !"e member $unction node creates a node.
$ns duple34link node1 node2 bandwidth delay queue-type2 creates two simple3
links o$ speci$ied bandwidt" and dela#, and connects t"e two speci$ied nodes. In
NS, t"e output .ueue o$ a node is implemented as a part o$ a link, t"ere$ore users
s"ould speci$# t"e .ueue4t#pe w"en creatin/ links. In t"e above simulation script,
)rop!ail .ueue is used.
$ns .ueue4limit node1 node2 number2 !"is line sets t"e .ueue limit o$ t"e two
simple3 links t"at connect node5 and node2 to t"e number speci$ied.
57
$ns duple34link4op node1 node2 ...2 !"e ne3t couple o$ lines are used $or t"e
N?G displa#. !"is line o$ code is used to monitor t"e .ueue $or t"e link between
t"e nodes node1 and node2. (ser can see t"e packets in t"e .ueue, and a$ter a
w"ile t"e user can even see "ow t"e packets are bein/ dropped.
Now t"at t"e basic network setup is done, t"e ne3t t"in/ to do is to setup tra$$ic
a/ents suc" as !C' and ()', tra$$ic sources suc" as *!' and C,-, and attac" t"em to
nodes and a/ents respectivel#.
set tcp 9new Agent/T!;2 !"is line creates a !C' a/ent. !o create a/ents or tra$$ic
sources, a user s"ould know t"e class names t"ese objects (?/ent%!C',
?/net%!C'Sink, ?pplication%*!' and so on).
$ns attac"4a/ent node agent2 !"e attac"4a/ent member $unction attac"es an a/ent
object created to a node object. ?ctuall#, t"is $unction calls t"e attac" member
$unction o$ speci$ied node, w"ic" attac"es t"e /iven a/ent to itsel$. !"ere$ore, a
user can do t"e same t"in/ b#, $or e3ample, :n= attac" :tcp.
$ns connect agent1 agent22 ?$ter two a/ents t"at will communicate wit" eac"
ot"er are created, t"e ne3t t"in/ is to establis" a lo/ical network connection
between t"em.
?ssumin/ t"at all t"e network con$i/uration is done, t"e ne3t t"in/ to do is write a
simulation scenario (i.e. simulation sc"edulin/). !"e Simulator object "as man#
sc"edulin/ member $unctions. <owever, t"e one t"at is mostl# used is t"e $ollowin/2
$ns at time "string"2 !"is member $unction o$ a Simulator object makes t"e
sc"eduler (sc"edulerC is t"e variable t"at points t"e sc"eduler object created b#
9new Sc"eduler; command at t"e be/innin/ o$ t"e script) to sc"edule t"e
e3ecution o$ t"e speci$ied strin/ at /iven simulation time. *or e3ample, $ns at 0.1
"$cbr start" will make t"e sc"eduler call a start member $unction o$ t"e C,-
tra$$ic source object, w"ic" starts t"e C,- to transmit data.
?$ter all network con$i/urations, sc"edulin/ and post4simulation procedure speci$ications
are done, t"e onl# t"in/ le$t is to run t"e simulation. !"is is done b# $ns run.
5D
3. ()tending N#* Creating a ne+ Agent
ne can e3tend NS b# addin/ new protocols. !"is section will discuss about "ow a
new a/ent can be created in NS usin/ an e3ample. !"e code in t"is section implements
some sort o$ simple Npin/O protocol. ne node will send n user de$ined number packets,
one at a time at re/ular intervals, to anot"er node w"ic" will return t"e packet
immediatel#. *or eac" packet t"e sender will t"en calculate t"e round trip time.
3.1. "he header !ile
*irst we "ave to create a "eader $ile #my!ing.h$ in w"ic" we will de$ine t"e data
structure $or t"e m#'in/ packet "eader.
struct hdr6m82ing {
char ret=
doule send6time=
44 ?eader access methods
static int offset6= 44 re*uired 8 2ac%et?eader&anager
inline static int" offset.1 { return offset6= }
inline static hdr6m82ing@ access.const 2ac%et@ p1 {
return .hdr6m82ing@1 p-Aaccess.offset61=
}
}=
!"e c"ar NretO is /oin/ to be set to P=P i$ t"e packet is on its wa# $rom t"e sender to t"e
node w"ic" is bein/ pin/ed, w"ile it is /oin/ to be set to P5P on its wa# back. !"e double
PsendCtimeP is a time stamp t"at is set on t"e packet w"en it is sent. !"is time is later used
b# t"e sender to calculate t"e round4trip4time. !"e rest o$ t"e part o$ pro/ram codes o$ t"e
"eader are used to access t"e packet "eader $rom an# packet re$erence.
!"e $ollowin/ piece o$ code declares t"e class N%y!ingAgentO as a subclass o$ t"e
class N?/entO.
class &82ing0gent B pulic 0gent {
pulicB
&82ing0gent.1=
int command.int argcC const char@const@ arg-1=
5F
-oid rec-.2ac%et@C ?andler@1=
-oid send6pac%ets.1=
protectedB
int num6pac%ets6=
doule wait6inter-al6=
&82ing0gent(imer timer6=
int count=
}=
!"e Nnum&pac'ets&O variable "olds t"e total number o$ packets t"at will be sent b# t"e
sender and Nwait&inter(al&O is t"e time interval between two successive packets. !"e
variable NcountO keeps t"e count o$ packets sent so $ar. +e also "ave to de$ine a timer
"andler (%y!ingAgentTimer) $or t"e sender so t"at it can resc"edule itsel$ eac" time a$ter
sendin/ a packet. G#'in/?/ent will use a variable Ntimer&O o$ t#pe %y!ingAgentTimer
to keep track o$ time. !"e source code $or t"e "eader $ile 6my!ing.h8 is /iven below2
4@ m82ing.h @4
+ifndef ns6m82ing6h
+define ns6m82ing6h
+include ;agent.h;
+include ;tclcl.h;
+include ;pac%et.h;
+include ;address.h;
+include ;ip.h;
class &82ing0gent=
struct hdr6m82ing {
char ret=
doule send6time=
44 ?eader access methods
static int offset6= 44 re*uired 8 2ac%et?eader&anager
inline static int" offset.1 { return offset6= }
inline static hdr6m82ing@ access.const 2ac%et@ p1 {
return .hdr6m82ing@1 p-Aaccess.offset61=
}
}=
class &82ing0gent(imer B pulic (imer?andler {
5H
pulicB
&82ing0gent(imer.&82ing0gent @t1 B (imer?andler.1
{ t6 > t= }
protectedB
-irtual -oid e!pire.D-ent @e1=
&82ing0gent @t6=
}=
class &82ing0gent B pulic 0gent {
pulicB
&82ing0gent.1=
int command.int argcC const char@const@ arg-1=
-oid rec-.2ac%et@C ?andler@1=
-oid send6pac%ets.1=
protectedB
int num6pac%ets6=
doule wait6inter-al6=
&82ing0gent(imer timer6=
int count=
}=
+endif
2able 1# >,1in#h
3.2. The C++ code for new Agent
*irst t"e linka/e between t"e C++ code and !cl code "as to be de$ined.
static class %ang0?eader5lass B pulic 2ac%et?eader5lass {
pulicB
%ang0?eader5lass.1 B 2ac%et?eader5lass
.;2ac%et?eader4&82ing;C si:eof.hdr6m82ing11 {
ind6offset."hdr6m82ingBBoffset61=
}
} class6%ang0hdrSnd=
static class &82ing0gent5lass B pulic (cl5lass {
pulicB
&82ing0gent5lass.1 B (cl5lass.;0gent4&82ing;1 {}
(clEFect@ create.intC const char@const@1 {
return .new &82ing0gent.11=
}
} class6m82ing=
!"e ne3t piece o$ code is t"e constructor $or t"e class NG#'in/?/entO. It binds t"e
variables w"ic" "ave to be accessed bot" in !cl and C++.
5I
&82ing0gentBB&82ing0gent.1 B 0gent.2(6&G2H/,1C timer6.this1 C
count.#1
{
ind.;pac%etSi:e6;C"si:e61=
ind.;num6pac%ets6;C"num6pac%ets61=
ind.;wait6inter-al6;"wait6inter-al61=
}
!"e $unction Ncommand)*O is called w"en a !cl command $or t"e class
NG#'in/?/entO is e3ecuted. In our case t"at would be J:sender sendJ (assumin/ NsenderO
is an instance o$ t"e ?/ent%G#'in/ class), because we want to send pin/ packets $rom t"e
?/ent to anot"er pin/ a/ent. +e "ave to parse t"e command in t"e Ncommand()O $unction.
I$ t"e command matc"es, it will in turn t"e Nsend&pac'ets)*O $unction w"ic" sends one
packet at a time and resc"edules itsel$ a/ain to send t"e ne3t packet a$ter t"e wait
interval. I$ no matc" is $ound, it is passed to t"e to t"e Ncommand()O $unction o$ t"e base
class (in t"is case P?/ent22command()P) wit" its ar/uments
int &82ing0gentBBcommand.int argcC const char@const@ arg-1
{
if .argc >> 21 {
if .strcmp.arg-[1]C ;send;1 >> #1 {
send6pac%ets.1=
44 return (5I6EJC so the calling function %nows that
44 the command has een processed
return .(5I6EJ1=
}
}
return .0gentBBcommand.argcC arg-11=
}
-oid &82ing0gentBBsend6pac%ets.1
{
if.countKK L num6pac%ets61
{
2ac%et @p%t > allocp%t.1=
hdr6m82ing @hdr > hdr6m82ingBBaccess.p%t1=
44 Set the MretM field to #C so the recei-ing node %nows
44 that it has to generate an echo pac%et
hdr-Aret > #=
44 Store the current time in the Msend6timeM field
hdr-Asend6time > SchedulerBBinstance.1.cloc%.1=
44 Send the pac%et
send.p%tC #1=
}
2=
if.count L num6pac%ets61
timer6.resched.wait6inter-al61=
}
!"e $unction Nrecv()O de$ines t"e actions to be taken w"en a packet is received. I$ t"e
NretO $ield is =, a packet wit" t"e same value $or t"e PsendCtimeP $ield, but wit" t"e NretO
$ield set to 5 "as to be returned. I$ NretO is 5, t"e roundtrip time o$ t"e packet is calculated
and printed. !"e complete source code $or 6my!ing.cc8 is /iven below2
4@ m82ing.cc @4
+include ;m82ing.h;
int hdr6m82ingBBoffset6=
static class %ang0?eader5lass B pulic 2ac%et?eader5lass {
pulicB
%ang0?eader5lass.1 B
2ac%et?eader5lass.;2ac%et?eader4&82ing;C
si:eof.hdr6m82ing11 {
ind6offset."hdr6m82ingBBoffset61=
}
} class6%ang0hdrSnd=
static class &82ing0gent5lass B pulic (cl5lass {
pulicB
&82ing0gent5lass.1 B (cl5lass.;0gent4&82ing;1 {}
(clEFect@ create.intC const char@const@1 {
return .new &82ing0gent.11=
}
} class6m82ing=
4@ constructor@4
&82ing0gentBB&82ing0gent.1 B 0gent.2(6&G2H/,1C timer6.this1C
count.#1
{
ind.;pac%etSi:e6;C"si:e61=
ind.;num6pac%ets6;C"num6pac%ets61=
ind.;wait6inter-al6;C"wait6inter-al61=
}
4@ if timer e!pires Fust do a timeout @4
-oid &82ing0gent(imerBBe!pire.D-ent@1
{
t6-Asend6pac%ets.1=
}
int &82ing0gentBBcommand.int argcC const char@const@ arg-1
25
{
if .argc >> 21 {
if .strcmp.arg-[1]C ;send;1 >> #1 {
send6pac%ets.1=
44 return (5I6EJC so the calling function %nows that
44 the command has een processed
return .(5I6EJ1=
}
}
return .0gentBBcommand.argcC arg-11=
}
-oid &82ing0gentBBsend6pac%ets.1
{
if.countKK L num6pac%ets61
{
2ac%et @p%t > allocp%t.1=
hdr6m82ing @hdr > hdr6m82ingBBaccess.p%t1=
44 Set the MretM field to #C so the recei-ing node %nows
44 that it has to generate an echo pac%et
hdr-Aret > #=
44 Store the current time in the Msend6timeM field
hdr-Asend6time > SchedulerBBinstance.1.cloc%.1=
44 Send the pac%et
send.p%tC #1=
}
if.count L num6pac%ets61
timer6.resched.wait6inter-al61=
}
-oid &82ing0gentBBrec-.2ac%et@ p%tC ?andler@1
{
hdr6m82ing @hdr>hdr6m82ingBBaccess.p%t1=
if .hdr-Aret >> #1 {
44 Send an MechoM. 7irst sa-e the old pac%etMs send6time
doule stime > hdr-Asend6time=
44 'iscard the pac%et
2ac%etBBfree.p%t1=
44 5reate a new pac%et
2ac%et@ p%tret > allocp%t.1=
44 0ccess the 2ing header for the new pac%etB
hdr6m82ing@ hdrret > hdr6m82ingBBaccess.p%tret1=
44 Set the MretM field to 1
hdrret-Aret > 1=
44 Set the send6time field to the correct -alue
hdrret-Asend6time > stime=
44 Send the pac%et
send.p%tretC #1=
}
else {
44 ,et the recei-ing time of the pac%et
22
doule rc-6time > SchedulerBBinstance.1.cloc%.1=
printf.;R(( > NlfOn;Crc-6time-hdr-Asend6time1=
44 'iscard the pac%et
2ac%etBBfree.p%t1=
}
}
2able )# m,1in#cc
Now save t"ese two $iles 6my!ing.h8 and 6my!ing.cc8 in t"e 6Q.%ns4allinone4
2.>5%ns42.>5%8 $older. *or /ood practice create a separate director# $or all pro/rams $or
user de$ined protocols. In our e3ample we "ave kept t"ese two $iles in 6Q.%ns4allinone4
2.>5%ns42.>5%bwtools%G#'in/8 director#.
3.3. Necessary changes in NS
Ne3t step is to modi$# some o$ t"e NS s#stem $iles so t"at t"e newl# written protocol
or a/ent can work wit" t"e simulator. !"e $iles t"at are needed to be modi$ied are s"own
wit"in red bubbles in *i/ure 5.
9iure 1# :( director, structure
3.3.1. (dit pac$et.h !ile
2>
+e need a new packet t#pe $or our G#'in/ a/ent, t"ere$ore t"e $irst step is to modi$#
t"e 6$+,/common/packet.h8 $ile (assumin/ t"at t"e :NS environment variable points t"e
Q.%ns4allinone42.>5%ns42.>5 location). !"ere #ou can $ind t"e de$initions $or t"e packet
protocol I)s (i.e. '!C!C', '!C!0EN0!, etc.). ?dd a new de$inition $or '!C'INR t"ere.
In m# edited version o$ packet.", t"e last $ew lines o$ enum pac6et7t{} looks like t"e
$ollowin/ code (it mi/"t look a bit di$$erent in di$$erent NS releases).
enum pac%et6t {
2(6(52C
2(69'2C
......
44 insert new pac%et t8pes here
2(6(7R5C
2(6(7R5605JC
-,6M7-8N9: 44 pac%et protocol H' for &82ing agent
2(6/(G2D 44 (his &9S( e the I0S( one
}=
Sou also "ave to edit t"e p7info+- in t"e same $ile to include JG#'in/J.
class p6info {
pulicB
p6info.1 {
name6[2(6(52]> ;tcp;=
name6[2(69'2]> ;udp;=
...........
name6[2(6(7R5]> ;tcp7riend;=
name6[2(6(7R5605J]> ;tcp7riend5tl;=
name6;-,6M7-8N9<=>M4-in3>?
name6[2(6/(G2D]> ;undefined;=
}
.....
}
3.3.2. (dit ns,pac$et.tcl !ile
Now in 6$+,/tcl/lib/ns-pac'et.tcl8 $ile searc" $or t"e part foreach prot { ## }. +it"in
t"is part add an entr# $or MyPing. It will look like $ollowin/2
2A
foreach prot {
+ 5ommonB
5ommon
7lags
H2 + H2
P P P
2ushac% + 2ushac%C router-to-router
M4-in3
+ &ulticastB
aSR& + mcast4srm.cc
P P P
+ EtherB
Dncap + common4encap.cc
H2inH2 + H2 encapsulation
?'I5 + ?igh Ie-el 'ata Iin% 5ontrol
} {
add-pac%et-header $prot
}
3.3.3. (dit ns,de!ault.tcl
!"e 6$+,/tcl/lib/ns-default.tcl8 $ile is t"e $ile w"ere all de$ault values $or t"e !cl
objects are de$ined. Insert t"e $ollowin/ line to set t"e de$ault packet siBe, packet number
and wait interval $or ?/ent%G#'in/.
0gent4&82ing set pac%etSi:e6 2##
0gent4&82ing set num6pac%ets6 $
0gent4&82ing set wait6inter-al6 .##1
3.3.4. (dit 'a$e!ile.in
!"e last c"an/e is a c"an/e t"at "as to be applied to t"e 6$+,/%a'efile.in8. Sou "ave
to add t"e $ile 6m#'in/.o8 to t"e list o$ object $iles $or ns. In m# version t"e last lines o$
t"e edited list look like t"is2
,TCCC U V
tools%random.o tools%rn/.o tools%ranvar.o common%misc.o common%timer4"andler.o V
common%sc"eduler.o common%object.o common%packet.o V
Q Q Q Q
27
b%tools/>,1in/m,1in#o C
tools%tra$/en.o trace%tra$$ictrace.o tools%pareto.o V
Q Q Q Q
3.4. -eco&pile N#
?$ter t"e c"an/es are done in t"e NS $iles we need to recompile t"e NS simulator. !o
do so use t"e $ollowin/ command2
dro8Qaggarpc$BR$ cd $/S
dro8Qaggarpc$Bns-2.$1$ pwd
4usr4share4ns-allinone-2.$14ns-2.$1
dro8Qaggarpc$Bns-2.$1$ sudo +@confi3ure
dro8Qaggarpc$Bns-2.$1$ sudo ma!e
3... #i&ple e)a&ple using 'yPing agent
?$ter recompilin/ t"e NS simulator we can use our G#'in/ a/ent in our simulations.
*ollowin/ code is simple tcl pro/ram t"at uses t"e G#'in/ a/ent.
set ns [new Simulator]
set nf [open out.tr w]
$ns trace-all $nf
+'efine a MfinishM procedure
proc finish {} {
gloal ns nf
$ns flush-trace
+5lose the trace file
close $nf
+D!ecute nam on the trace file
e!it #
}
set n# [$ns node]
set n1 [$ns node]
$ns duple!-lin% $n# $n1 1#& 3#ms 'rop(ail
+++++Sender Side Stuff++++++++++
set sender [new 0gent4&82ing]
$ns attach-agent $n# $sender
$sender set pac%etSi:e6 13##
$sender set num6pac%ets6 3
$sender set wait6inter-al6 .#3
+++++Recei-er Side Stuff
set rec- [new 0gent4&82ing]
$ns attach-agent $n1 $rec-
2D
+++++5onnect the sender with recei-er
$ns connect $sender $rec-
+Schedule e-ents for the 5BR agent
$ns at #.# ;$sender send;
$ns at 1#.# ;finish;
$ns run
9iure )# m,1in?xample#tcl
4. -e!erences*
95; ?ltman, 0.& TimWneB, !. (2==>). +, ,imulator for beginners 9nline;. ?vailable2
citeseer.ist.psu.edu%altman=>ns."tml
92; The ns %anual )formerly ns +otes and -ocumentation* 9nline;. ?vailable2
"ttp2%%www.isi.edu%nsnam%ns%doc%inde3."tml
9>; C"un/, T.& Cla#pool, G. +, by ./ample 9nline;. ?vailable2 "ttp2%%nile.wpi.edu%NS%
9A;
Rreis, Garc. Tutorial for the +etwor' ,imulator "ns" 9nline;. ?vailable2
"ttp2%%www.isi.edu%nsnam%ns%tutorial%
Prepared by: /ebashis -oy
Submitted to: A$shai Aggar+al
2F

You might also like