Вы находитесь на странице: 1из 561

Introduction to Network Simulator NS2

Teerawat Issariyakul Ekram Hossain


Introduction to Network
Simulator NS2
Second Edition
123
Teerawat Issariyakul
TOT Public Comany !imited
"#$2 %oo 3
C&aen'wattana (d)
T&un'son'&on'* !aksi
+an'kok 1,21, T&ailand
it eer a w a t -&o t ma il) com
ns2ultimate)com
Ekram Hossain
.eartment o/ Electrical
and Comuter En'ineerin'
0ni1ersity o/ %anitoba
234 C&ancellor5s Circle 13
6innie'* %+ (3T 378
Canada
ekram-ee ) uman it oba ) ca
IS+N #2"919:81:91:,398 e9IS+N #2"919:81:91:,893
.OI 1,)1,,2$#2"919:81:91:,893
Srin'er New ;ork .ordrec&t Heidelber'
!ondon
!ibrary o/ Con'ress Control Number< 2,11#:,22,
= Srin'er Science>+usiness %edia* !!C 2,12
4ll ri'&ts reser1ed) T&is work may not be translated or coied in w&ole or in art wit&out t&e written
ermission o/ t&e ublis&er ?Srin'er Science>+usiness %edia* !!C* 233 Srin' Street* New ;ork*
N; 1,,13* 0S4@* eAcet /or brie/ eAcerts in connection wit& re1iews or sc&olarly analysis) 0se in
connection wit& any /orm o/ in/ormation stora'e and retrie1al* electronic adatation* comuter so/tware*
or by similar or dissimilar met&odolo'y now known or &erea/ter de1eloed is /orbidden)
T&e use in t&is ublication o/ trade names* trademarks* ser1ice marks* and similar terms* e1en i/ t&ey
are not identi/ied as suc&* is not to be taken as an eAression o/ oinion as to w&et&er or not t&ey are
subBect to rorietary ri'&ts)
Printed on acid9/ree aer
Srin'er is art o/ Srin'er Science>+usiness %edia ?ww w ) srin'e r) com@
To our families
Preface
Motivation for Writing This Book
Cirst o/ all* we would like to t&ank you /or your interest in t&is book) T&is book
was moti1ated by our /rustration w&en we were 'raduate students) 6e were
us&ed to work wit& NS2* w&en we did not know w&at to do) 6e looked o1er t&e
Internet* but* at t&e time* t&ere were 1ery little material on t&e Internet) 6e osted
our Duestion on e1ery mailin' list* e1ery online /orums we can t&ink o/) 6e did
not /ind most o/ w&at we were lookin' /or) 6e sent days and ni'&ts on many
oeratin' systems Bust to make NS2 run on one o/ t&e systems we &a1e) 6e sent
an endless amount o/ time* tryin' to understand t&e way NS2 mo1es a acket
/rom one node to anot&er) 6e did not succeed) So we were runnin' out o/ time
we us&ed out and submitted our roBect$t&esis as it was) Our ro'ram was as
'ood as it was necessary to close t&e roBect) 6e were not satis/ied wit& our
knowled'e about NS2)
4/ter t&e 'raduation* we re1isited NS2 and tried to understand it more) +its
by bits* we be'an to understand &ow NS2 does a certain t&in'* but er&as more
imortantly w&y NS2 does so) Crom our eAerience* it takes mont&s* i/ not years*
to truly understand NS2)
6e would not be surrised i/ our story abo1e sounds articularly /amiliar to
you) In /act* we eAected you to eAerience a art* i/ not all* o/ our unleasant
eAerience) 6e wrote t&is book to ease your ain caused by NS2) 6e &oe t&at
t&is book can reduce your NS2 learnin' cur1e /rom years to mont&s* or /rom
mont&s to weeks)
About NS2
NS2 is an oen9source e1ent9dri1en simulator desi'ned seci/ically /or researc&
in comuter communication networks) Since its incetion in 1#"#* NS2 &as
continuously 'ained tremendous interest /rom industry* academia* and
'o1ernment) Ha1in' been under constant in1esti'ation and en&ancement /or
years* NS2 now contains modules /or numerous network comonents suc& as
routin'* transort layer rotocol* and alication) To in1esti'ate network
er/ormance* researc&ers can
Preface
1ii
1iii Pre/ace
simly use an easy9to9use scritin' lan'ua'e to con/i'ure a network* and obser1e
results 'enerated by NS2) 0ndoubtedly* NS2 &as become t&e most widely used
oen source network simulator* and one o/ t&e most widely used network
simulators)
0n/ortunately* most researc& needs simulation modules w&ic& are beyond t&e
scoe o/ t&e built9in NS2 modules) Incororatin' t&ese modules into NS2 reDuires
ro/ound understandin' o/ NS2 arc&itecture) Currently* most NS2 be'inners rely
on online tutorials) %ost o/ t&e a1ailable in/ormation mainly eAlains &ow to
con/i'ure a network and collect results* but does not include su//icient in/ormation
/or buildin' additional modules in NS2) .esite its details about NS2 modules* t&e
/ormal documentation o/ NS2 is mainly written as a re/erence book* and does not
ro1ide muc& in/ormation /or be'inners) T&e lack o/ 'uidelines /or eAtendin' NS2
is er&as t&e 'reatest obstacle* w&ic& discoura'es numerous researc&ers /rom
usin' NS2) 4t t&e time o/ t&is writin'* t&ere is no o//icial 'uide book w&ic& can
&el t&e be'inners understand t&e arc&itecture o/ NS2 in det&)
About This Book
T&is book is desi'ned to be an NS2 rimer) It ro1ides in/ormation reDuired to
install NS2* run simle eAamles* modi/y t&e eAistin' NS2 modules* and create as
well as incororate new modules into NS2) To t&is end* t&e details o/ se1eral built9
in NS2 modules are eAlained in a comre&ensi1e manner)
NS2 by itsel/ contains numerous modules) 4s time elases* researc&ers kee
de1eloin' new NS2 modules) T&is book does not include t&e details o/ all NS2
modules* but does so /or selected modules necessary to understand t&e basics o/
NS2) 6e belie1e t&at once t&e basics o/ NS2 are 'rased* t&e readers can 'o
t&rou'& ot&er documentations* and readily understand t&e details o/ ot&er NS2
comonents) T&e details o/ Network 4ni%ator ?N4%@ and E'ra& are also
omitted &ere) 6e understand t&at t&ese two tools are nice to &a1e and could 'reatly
/acilitate simulation and analysis o/ comuter networks) Howe1er* we belie1e t&at
t&ey are not essential to t&e understandin' o/ t&e NS2 concet* and t&eir
in/ormation are widely a1ailable t&rou'& most o/ t&e online tutorials)
T&is teAtbook can be used by researc&ers w&o need to use NS2 /or communica9
tion network er/ormance e1aluation based on simulation) 4lso* it can be used as
a re/erence teAtbook /or laboratory works /or a senior under'raduate le1el course
or a 'raduate le1el course on telecommunication networks o//ered in Electrical
and Comuter En'ineerin' and Comuter Science Pro'rams) Potential courses
include FNetwork Simulation and %odelin'*G FComuter Networks*G F.ata Com9
munications*G F6ireless Communications and Networkin'*G and FSecial Toics
on Telecommunications)G
Pre/ace iA
Book Summary
T&is book starts o// wit& an introduction to network simulation in C&a) 1) 6e
brie/ly discuss about comuter networks and t&e layerin' concet) T&en we
'i1e board statements on system analysis aroac&es) 4s one o/ t&e two main
aroac&es* simulation can be carried out in time9dri1en and e1ent9dri1en modes)
T&e latter is t&e one NS2 was de1eloed)
C&ater 2 ro1ides an o1er1iew o/ Network Simulator 2 ?NS2@) S&own in t&is
c&ater are t&e two9lan'ua'e NS2 arc&itecture* NS2 directory* and t&e con1entions
used in t&is book* and NS2 installation 'uidelines /or 0NIE and 6indows
systems) 6e also resent a t&ree9ste simulation /ormulation as well as a simle
eAamle o/ NS2 simulation) Cinally* we demonstrate &ow to use t&e make utility
to incororate new modules into NS2)
C&ater 3 eAlains t&e details o/ t&e NS2 two lan'ua'e structure* w&ic&
consists o/ t&e /ollowin' siA main CCC classes< Tcl* Instvar* TclObject*
TclClass* TclCommand* and EmbeddedTcl) C&aters : and 3 resent t&e
1ery main simulation concet o/ NS2) 6&ile C&a) : eAlains imlementation o/
e1ent9dri1en simulation in NS2* C&a) 3 /ocuses on network obBects as well as
acket /orwardin' mec&anism)
C&aters 8H11 resent t&e /ollowin' siA most widely used NS2 modules) Cirst*
nodes ?C&a) 8@ act as routers and comuter &osts) Second* links* articularly
SimpleLink obBects ?C&a) 2@* deli1er ackets /rom one network obBect to
anot&er) T&ey model acket transmission time as well as acket bu//erin') T&ird*
ackets ?C&a) "@ contain necessary in/ormation in its &eader) Court&* a'ents
?C&as) #H1,@ are resonsible /or 'eneratin' ackets) NS2 &as two main transort9
layer a'ents< TCP and 0.P a'ents) Cinally* alications ?C&a) 11@ model t&e user
demand /or data transmission)
0 to C&a) 11* t&e book /ocuses mainly on wired networks) C&ater 12
demonstrates &ow NS2 imlements 6ireless %obile 4d Hoc Networks)
.iscussion o/ acket /orwardin' 1ia wireless links and node mobility is 'i1en in
t&is c&ater)
4/ter discussin' all t&e NS comonents* C&a) 13 demonstrates &ow a new
module is de1eloed and inte'rated into NS2 t&rou'& two /ollowin' eAamles<
4utomatic (eeat reIuest ?4(I@ and acket sc&edulers)
C&ater 1: summariJes t&e ostsimulation rocess* w&ic& consists o/ t&ree
main arts< debu''in'* 1ariable and acket tracin'* and result comilation)
C&ater 13 resents t&ree &eler modules< Timers* random number 'enerators*
and error models) It also discusses t&e concets o/ two bit9wise oerations H
namely* bit maskin' and bit s&i/tin'* w&ic& are used t&rou'&out NS2)
Cinally* 4endices 4 and + ro1ide ro'rammin' details w&ic& could be
use/ul /or t&e be'inners) T&ese details include an introduction to Tcl* OTcl* and
46K ro'rammin' lan'ua'es as well as a re1iew o/ t&e olymor&ism OOP
concet) !ast but not t&e least* 4endiA C eAlains t&e +S. link list as well as
bit le1el /unctions used t&rou'&out t&is book)
A Pre/ace
How to Rea This Book
To
Everyone
I/ you &a1e not done so* we &i'&ly recommend you to 1isit t&e /ollowin' online
websites and learn w&at you can do wit& NS2)
1
%arc Lreis5 Tutorial<
& tt <$$ww w )isi)e du $n s n a m $n s $t u tor ial
NS2 by EAamle< & tt <$$ e r/orm )w i)e du $NS
To
Beginners
Start simle) !earnin' &ow NS2 ass a acket /rom one end o/ a communication
link to anot&er is more c&allen'in' t&an w&at you mi'&t &a1e ima'ined) In /act* i/
t&ere is only one 'oal you s&ould set* it is to understand t&is seemin'ly simle
NS2 mec&anism) Once you 'ras t&is concet* you can Duickly and e//ortlessly
learn ot&er NS2 mec&anism)
In articular* t&e /ollowin' stes are su''ested /or be'inners<
Ste 1 ?T&e +asic@< !earn &ow NS2 ass ackets /rom one obBect to anot&er
/rom wit&in a Simle!ink) 7isit C&a) 2 /or Simle!ink imlementation)
;ou may need to 1isit C&as) :H3 /or details o/ sc&eduler and Network
comonent imlementation)
Ste 2 ?C+( and 0.P@< T&ese are two &i'&9layer comonents w&ic& is easy to
learn) !ook /or t&e contents about 0.P and C+( in C&as) # and 11*
resecti1ely)
Ste 3 ?New %odule@< NeAt* 1isit C&a) 13 to learn &ow to build new modules
into NS2) T&ere are two eAamles in t&is c&ater) Note t&at you may need
to learn &ow to use make utility in C&a) 2)
To
Instructors
T&is book contains 13 c&aters) .i//erent c&aters may consume di//erent amount
o/ lecturin' time) Lenerally* it reDuires more t&an 13 classes to co1er t&e entire
book) 6e su''est instructors to em&asiJe$omit t&e contents o/ t&is book at t&eir
discretion) In order to mana'e time e//iciently* t&e instructors may /ollow t&e
/ollowin' 'uidelines<
C&aters "* 1:* and 1, can be skied wit&out 'reatly imairin' t&e content o/
t&e course)
T&e instructor may ack two c&aters into one lecture< C&as) 1H2 and :H
3)
1
Some o/ t&ese contents is a1ailable in C&a) 2)
Pre/ace Ai
6e also ro1ide eAercises at t&e end o/ eac& c&ater) T&e instructors may
use t&ese eAercises to set u assi'nments* laboratory eAercises* or eAamination
Duestions)
What!s New in This Secon "ition
In t&is Second edition o/ t&is book* we correct t&e 'rammatical and tyolo'ical
errors) 6e add more materials on 'eneral comuter network simulation into C&a)
1) 6e clean u t&e terminolo'ies* include more eAamles* and rewrite C&as) 8
and 13) 4t t&e end o/ eac& c&ater* we ro1ide eAercises w&ic& can be used as
assi'nments* laboratory eAercises* and eAamination Duestions)
In 4endiA 4* we include most o/ t&e in/ormation t&at NS2 be'inners need to
know about Tcl* OTcl* and 46K) .urin' t&e NS2 learnin' rocess* readers may
encounter +S.9linked lists and bit le1el CCC /unctions) (eaders may /ind t&e
in/ormation about t&ese two basic CCC comonents in 4endiA C)
4s o/ t&is writin'* t&e latest NS2 1ersion is 2)33) T&is 1ersion is not /ully
backward9comatible wit& 1ersion 2)2# used as a re/erence in t&e /irst edition o/
t&is book) T&ere/ore* we address t&e comatibility issues on t&e link error modules
in C&a) 13 and 4(I modules in C&a) 13)
6e &a1e recei1ed numerous reDuests to deal wit& wireless networkin') In t&is
re'ard* we de1elo a new c&ater* namely* 6ireless %obile 4d Hoc Networks
?C&a) 12@) In t&is c&ater* we eAlain bot& acket /orwardin' o1er wireless links
and node mobility mec&anism) T&e in/ormation about wireless trace /ormats is
'i1en in C&a) 1:)
6e &a1e also de1eloed comanion online resources /or t&is book) T&ey
contain use/ul NS2 in/ormation suc& as udates* discussion boards* detailed
eAlanation on 1arious toics* resentation slides* Duestions and answers* book
corrections* and so on) T&e readers are &i'&ly encoura'ed to 1isit and Boin our
online community at
6ebsite< & tt <$$ n s 2u lti m ate)c o m
Cacebook Can Pa'e<
& tt <$$ww w ) / acebook)com $a'e s $T eer a w a t9 I ss a r iy a k u l$ 3 3 "2 : , " 8 1 : 1 2
Twitter /eed< & tt <$$twitte r ) c om $T +ear
!ecture notes< &tt<$$ww w )ece)ubc)ca$

teerawat$NS2)&tm
TOT Public Comany !imited Teerawat
Issariyakul
0ni1ersity o/ %anitoba Ekram Hossain
Acknow#egment
In t&is second edition* we would like to eAress our sincere 'ratitude toward
our collea'ues at TOT Public Comany !imited* and t&e 'raduate students o/
t&e F6ireless Communications* Networks* and Ser1ices (esearc& LrouG at t&e
0ni1ersity o/ %anitoba) 6e are deely obli'ed to audience and /ollowers at t&e
NS2 website* t&e Cacebook a'e* and t&e Twitter /eed* as well as t&ose w&o read
t&e re1ious edition o/ t&is book and took time contactin' us) ;our comments
and Duestions &el us imro1e t&e content o/ t&e book in a bi' way) 6e are
esecially t&ank/ul to Nestor %ic&ael C) Ti'lao w&o went so /ar to &el us locate
t&e tyo'ra&ical errors)
6e would like to t&ank Srin'er* t&e ublis&er o/ t&e book* /or 'i1in' us an
oortunity to s&are our knowled'e and skill wit& our tec&nical community)
Secial t&anks 'o to +rett KurJman* Srin'er5s a'ent* w&o &as keenly worked
wit& us /rom t&e be'innin' to t&e end)
!ast* but by no means t&e least* we would like to t&ank our /amilies and /riends
/or t&eir understandin' and continual moral suort) 6e are /ore1er indebted to
all t&e members o/ Issariyakul and Hossain /amilies) T&ank you /or 'i1in' us
lo1e* suort* encoura'ement* and most o/ all /or ne1er stoin' to belie1e in us)
T&ank you /or not abandonin' us and always bein' t&ere /or us* e1en i/ we &a1e
not 'i1en you time you deser1ed* and e1en &a1e disaeared in a ile o/ NS2
codes)
Aiii
$ontents
% Simu#ation of $om&uter Networks ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1
1)1 Comuter Networks and t&e !ayerin' Concet ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1
1)1)1 !ayerin' Concet ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2
1)1)2 OSI and TCP$IP (e/erence %odels ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :
1)2 System %odelin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3
1)2)1 4nalytical 4roac& ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 8
1)2)2 Simulation 4roac&) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 8
1)3 +asics o/ Comuter Network Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 8
1)3)1 Simulation Comonents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2
1)3)2 Simulation Per/ormance ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #
1)3)3 Con/idence Inter1al ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #
1)3): C&oices /or Network Simulation Tools ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #
1): Time9.eendent Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 11
1):)1 Time9.ri1en Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 12
1):)2 E1ent9.ri1en Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 13
1)3 4 Simulation EAamle< 4 Sin'le9C&annel Iueuin' System ) ) ) ) ) ) 1:
1)3)1 Entities ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1:
1)3)2 State Llobal 7ariables) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 13
1)3)3 (esource ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 13
1)3): E1ents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
1)3)3 Simulation Per/ormance %easures
and Statistics Lat&erers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
13
18
1)3)8 Simulation Pro'ram ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 18
1)8 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1#
1)2 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,
2 'ntrouction to Network Simu#ator 2 (NS2) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
21 2)1 Introduction ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 21
2)2 +asic 4rc&itecture ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22
A1
A1i Contents
2)3 Installation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23
2)3)1 Installin' an 4ll9In9One NS2 Suite
on 0niA9+ased Systems ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:
2)3)2 Installin' an 4ll9In9One NS2 Suite
on 6indows9+ased Systems ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:
2): .irectories and Con1ention ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23
2):)1 .irectories ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23
2):)2 Con1ention ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23
2)3 (unnin' NS2 Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22
2)3)1 NS2 Pro'ram In1ocation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22
2)3)2 %ain NS2 Simulation Stes ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2"
2)8 4 Simulation EAamle ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#
2)2 Includin' C>> %odules into NS2 and t&e make 0tility ) ) ) ) ) ) ) ) ) ) ) 33
2)2)1 4n In1ocation o/ a make 0tility ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33
2)2)2 4 make .escritor Cile ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33
2)2)3 NS2 .escritor Cile ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3"
2)" C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3"
2)# EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3#
* +inkage Between ,Tc# an $CC in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :1
3)1 T&e Two9!an'ua'e Concet in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2
3)1)1 T&e Natures o/ OTcl and CCC
Pro'rammin' !an'ua'es ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
3)1)2 CCC Pro'rammin' Styles and Its 4lication
in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
:2
:3
3)2 Class +indin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :8
3)2)1 Class +indin' Process ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :8
3)2)2 .e/inin' ;our Own Class +indin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2
3)2)3 Namin' Con1ention /or Class TclClass ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"
3)3 7ariable +indin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"
3)3)1 7ariable +indin' %et&odolo'y ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"
3)3)2 Settin' t&e .e/ault 7alues ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :#
3)3)3 NS2 .ata Tyes ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3,
3)3): Class Inst1ar ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33
3): EAecution o/ CCC Statements /rom t&e OTcl .omain ) ) ) ) ) ) ) ) ) ) ) ) 33
3):)1 OTcl Commands in a Nuts&ell ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33
3):)2 T&e Internal %ec&anism o/ OTcl Commands ) ) ) ) ) ) ) ) ) ) ) 33
3):)3 4n 4lternati1e /or OTcl Command In1ocation ) ) ) ) ) ) ) ) ) ) 3#
3):): Non9OOP Tcl Command ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3#
3):)3 In1okin' a TclCommand ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3#
3)3 S&adow ObBect Construction Process ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 82
3)3)1 4 Handle o/ a TclObBect ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 82
3)3)2 TclObBects Construction Process ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 83
3)3)3 TclObBects .estruction Process ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 82
Contents A1ii
A1ii
3)2 Translation o/ Tcl Code ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22
3)" C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23
3)# EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23
'm&#ementation of -iscrete."vent Simu#ation in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
22 :)1 NS2 Simulation Concet ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22
:)2 E1ents and Handlers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2"
:)2)1 4n O1er1iew o/ E1ents and Handlers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2"
:)2)2
:)2)3
Class NsObject< 4 C&ild Class o/ Class
Handler) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
Classes Packet and AtEvent< C&ild
Classes o/ Class Event ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
2#
",
:)3 T&e Sc&eduler ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "2
:)3)1 %ain Comonents o/ t&e Sc&eduler ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "2
:)3)2 .ata Encasulation and Polymor&ism Concets ) ) ) ) ) ) ) "2
:)3)3 %ain Cunctions o/ t&e Sc&eduler ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "3
:)3): Two 4uAiliary Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "3
:)3)3 .ynamics o/ t&e 0niDue I. o/ an E1ent ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "8
:)3)8 Sc&edulin'H.isatc&in' %ec&anism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "8
:)3)2 Null E1ent and .ummy E1ent Sc&edulin') ) ) ) ) ) ) ) ) ) ) ) ) ) ) ""
:): T&e Simulator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "#
:):)1 %ain Comonents o/ a Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "#
:):)2 (etrie1in' t&e Instance o/ t&e Simulator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #,
:):)3 Simulator InitialiJation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #1
:):): (unnin' Simulation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #2
:):)3 Instrocs o/ OTcl Class Simulator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #3
:)3 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #3
:)8 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #:
3)8 4ccess t&e OTcl .omain /rom t&e CCC .omain ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 82
3)8)1 Obtain a (e/erence to t&e Tcl Interreter ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 8"
3)8)2 EAecution o/ Tcl Statements ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 8"
3)8)3 Pass or (ecei1e (esults to$/rom t&e Interreter ) ) ) ) ) ) ) ) ) ) 8#
3)8): TclObBect (e/erence (etrie1al ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 21
/
0 Network ,b1ects2 $reation3 $onfiguration3
an Packet 4orwaring ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #2
3)1 O1er1iew o/ NS2 Comonents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #"
3)1)1 Cunctionality9+ased Classi/ication o/ NS2 %odules ) ) ) ) #"
3)1)2 CCC Class Hierarc&y ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) #"
3)2 NsObBects< 4 Network ObBect Temlate ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,,
3)2)1 Class NsObject ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,,
3)2)2 Packet Corwardin' %ec&anism o/ NsObBects ) ) ) ) ) ) ) ) ) ) ) ) 1,1
3)3 Connectors ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,1
3)3)1 Class .eclaration ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,2
3)3)2 OTcl Con/i'uration Commands ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,3
3)3)3 Packet Corwardin' %ec&anism o/ Connectors ) ) ) ) ) ) ) ) ) ) 1,8
8)3 Node
8)3)1
Construction and Con/i'uration ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
Key 7ariables o/ t&e OTcl Class Node
13:
and T&eir (elations&i ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 133
8)3)2 Installin' Classi/iers in a Node ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 132
8)3)3 +rid'in' a Node to a Transort !ayer Protocol ) ) ) ) ) ) ) ) ) 13"
8)3): 4ddin'$.eletin' a (outin' (ule ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1:,
8)3)3 Node Construction and Con/i'uration) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1:,
8)8 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1:2
8)2 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1:"
5 +ink an Buffer Management ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 131
2)1 Introduction to Simle!ink ObBects ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 131
2)1)1 %ain Comonents o/ a Simle!ink ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 131
2)1)2 Instrocs /or Con/i'urin' a SimpleLink ObBect )
) ) ) ) )
133
2)1)3 T&e Constructor o/ Class SimpleLink ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 13:
2)2 %odelin' Packet .earture ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 133
2)2)1 Packet .earture %ec&anism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 133
2)2)2 CCC Class LinkDelay ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 138
2)3 +u//er %ana'ement ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 13"
2)3)1 Class Packet!e!e< 4 %odel /or Packet +u//erin' )
)
13#
2)3)2 Iueue Handler ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 18,
2)3)3 Iueue +lockin' and Callback %ec&anism ) ) ) ) ) ) ) ) ) ) ) ) ) ) 181
2)3): Class DropTail< 4 C&ild Class o/ Class !e!e) ) ) ) ) ) 183
A1iii Contents
3): C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,"
3)3 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1,#
6 Noes as Routers or $om&uter Hosts ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 111
8)1 4n O1er1iew o/ Nodes in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 111
8)1)1 (outin' Concet and Terminolo'y ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 111
8)1)2 4rc&itecture o/ a Node ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 112
8)1)3 .e/ault Nodes and Node Con/i'uration Inter/ace ) ) ) ) ) ) ) 113
8)2 Classi/iers< %ulti9Tar'et Packet Corwarders ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
11: 8)2)1 Class Classi"ier and Its %ain Comonents )
) ) ) ) ) ) ) )
11:
8)2)2 Port Classi/iers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 11"
8)2)3 Has& Classi/iers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 11#
8)2): Creatin' ;our Own Classi/iers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 123
8)3 (outin' %odules ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 123
8)3)1 4n O1er1iew o/ (outin' %odules ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 123
8)3)2 CCC Class #o!tin$%od!le ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
128
8)3)3 OTcl Class #t%od!le ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 12#
8)3): +uilt9in (outin' %odules ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 131
8): (oute !o'ic ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 132
8):)1 CCC Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 132
8):)2 OTcl Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 133
Contents AiA
AiA
2):)1 Network Construction ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 183
2):)2 Packet Clow %ec&anism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 183
2)3 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 188
2)8 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 182
7 Packets3 Packet Heaers3 an Heaer 4ormat ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 18#
")1 4n O1er1iew o/ Packet %odelin' Princile ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 18#
")1)1 Packet 4rc&itecture ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 18#
")1)2 4 Packet as an E1ent< 4 .elayed Packet
(ecetion E1ent ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 122
")1)3 4 !ink !ist o/ Packets ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 123
")1): Cree Packet !ist ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 12:
")2 Packet 4llocation and .eallocation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 123
")2)1 Packet 4llocation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 123
")2)2 Packet .eallocation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 12"
")3 Packet
")3)1
Header ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
4n O1er1iew o/ Cirst !e1el Packet
Comosition< O//setin' Protocol9Seci/ic
Header on t&e Packet Header ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
1",
1"1
")3)2 Common Packet Header ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1"2
")3)3 IP Packet Header ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1"3
")3): Payload Tye ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1":
")3)3 Protocol9Seci/ic Headers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1"8
")3)8 Packet Header 4ccess %ec&anism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1#,
")3)2 Packet Header %ana'er ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1#3
")3)" Protocol9Seci/ic Header Comosition
and Packet Header Construction ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 1#:
"): .ata Payload ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,,
")3 CustomiJin' Packets ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,2
")3)1 Creatin' ;our Own Packet ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,2
")3)2 4cti1ate$.eacti1ate a Protocol9Seci/ic Header ) ) ) ) ) ) ) ) ) 2,3
")8 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,8
")2 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,2
8 Trans&ort $ontro# Protoco#s Part %2
An ,verview an 9ser -atagram Protoco# 'm&#ementation ) ) ) ) ) ) ) ) ) ) 2,#
#)1 0.P and TCP +asics ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,#
#)1)1 0.P +asics ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2,#
#)1)2 TCP +asics ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 21,
#)2 +asic 4'ents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 21:
#)2)1 4lications* 4'ents* and a !ow9!e1el Network ) ) ) ) ) ) ) 213
#)2)2 4'ent Con/i'uration ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 212
#)2)3 Internal %ec&anism /or 4'ents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 21"
#)2): Luidelines to .e/ine a New Transort !ayer 4'ent ) ) ) ) ) 222
2): 4 Samle Two9Node Network ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 183
1,)2)1 Class Acker ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 232
1,)2)2 Class TcpSink ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
2:,
1,)3 TCP Sender ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:2
1,): TCP Packet Transmission Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:2
1,):)1 Cunction sendms$&nbytes' ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
2:3
1,):)2 Cunction send m!c(&"orce)reason)
ma*b!rst' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2::
1,):)3 Cunction o!tp!t&se+no)reason' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:8
1,):): Cunction send one&' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:"
1,)3 4CK Processin' Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2:#
1,)3)1 Cunction recv&p)(' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
23,
1,)3)2 Cunction recv ne,ack (elper&pkt' )
) ) ) ) ) ) ) ) ) ) ) ) )
231
1,)3)3 Cunction ne,ack&pkt' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 233
1,)3): Cunction d!pack action&' ) ) ) ) ) ) 233
1,)8 Timer9(elated Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
23: 1,)8)1 (TT Samle Collection ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23:
1,)8)2 (TT Estimation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 238
1,)8)3 O1er1iew o/ State 7ariables ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 232
1,)8): (etransmission Timer ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23"
1,)8)3 Cunction O1er1iew ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23#
1,)8)8 Cunction rtt !pdate&tao' ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
28,
1,)8)2 Cunction rtt timeo!t&' ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
282
1,)8)" Cunction rtt backo""&' ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
283
1,)8)# Cunction set rt* timer&'and Cunction
reset rt* timer&mild)backo""'
) ) ) ) ) ) ) ) ) ) ) ) ) )
28:
1,)8)1, Cunction ne,timer&pkt' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 28:
1,)8)11 Cunction timeo!t&tno' ) ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
283
1,)2 6indow4dBustment Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 282
1,)2)1 Cunction openc,nd&' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 28"
1,)2)2 Cunction slo,do,n&(o,' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 28#
AA Contents
#)3 0.P and Null 4'ents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 222
#)3)1 Null ?(ecei1in'@ 4'ents ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 222
#)3)2 0.P ?Sendin'@ 4'ent ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 223
#)3)3 Settin' 0 a 0.P Connection ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 222
#): C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 222
#)3 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22"
%: Trans&ort $ontro# Protoco#s Part 22
Transmission $ontro# Protoco# ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22#
1,)1 4n O1er1iew o/ TCP 4'ents in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22#
1,)1)1 Settin' 0 a TCP Connection ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22#
1,)1)2 Packet Transmission and 4cknowled'ment
%ec&anism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 23,
1,)1)3 TCP Header ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 231
1,)1): .e/inin' TCP Sender and (ecei1er ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 231
1,)2 TCP (ecei1er ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 233
Contents AAi
1,)" C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 221
1,)# EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 221
%% A&&#ication2 9ser -eman 'nicator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 223
11)1 (elations&i +etween an 4lication and a Transort
!ayer 4'ent ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 223
11)2 4lications ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 228
11)2)1 Cunctions o/ Classes Application and A$ent) ) ) ) ) ) 222
11)2)2 Public Cunctions o/ Class Application ) ) ) ) ) ) ) ) ) ) ) ) ) ) 22"
11)2)3 (elated Public Cunctions o/ Class A$ent )
) ) ) ) ) ) ) ) ) ) ) ) ) )
2",
11)2): OTcl Commands o/ Class Application) ) ) ) ) ) ) ) ) ) ) ) ) ) 2",
11)3 Tra//ic Lenerators ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2",
11)3)1 4n O1er1iew o/ Class Tra""ic-enerator ) ) ) ) ) ) ) ) ) 2"1
11)3)2 %ain %ec&anism o/ a Tra//ic Lenerator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2"3
11)3)3 +uilt9in Tra//ic Lenerators in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2":
11)3): Class C.# Tra""ic< 4n EAamle Tra//ic
Lenerator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2"2
11): Simulated 4lications ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2"#
11):)1 Cile Trans/er Protocol ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#,
11):)2 Telnet ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#,
11)3 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#1
11)8 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#2
%2 Wire#ess Mobi#e A Hoc Networks ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#3
12)1 4n O1er1iew o/ 6ireless Networkin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#:
12)1)1 %obile Node ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#:
12)1)2 4rc&itecture o/ %obile Node ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#:
12)1)3 Leneral Packet Clow in a 6ireless Network
Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#2
12)1): %obile Node Con/i'uration Process ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 2#"
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols ) ) ) ) ) ) ) ) ) ) ) 3,3
12)2)1 Preliminaries /or t&e 4O.7 (outin' Protocol ) ) ) ) ) ) ) ) ) ) 3,3
12)2)2 T&e Princiles o/ 4O.7 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3,8
12)2)3 4n O1er1iew o/ 4O.7 Imlementation in NS2 ) ) ) ) ) ) ) ) 3,"
12)2): 4O.7 (outin' 4'ent Construction Process ) ) ) ) ) ) ) ) ) ) ) ) 311
12)2)3 Leneral Packet Clow %ec&anism
in a 6ireless Network ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 312
12)2)8 Packet (ecetion and Processin' Cunction o/ 4O.7 ) )
)
312
12)2)2 4O.7 Time9.ri1en 4ctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 313
12)3 .ata !ink !ayer< !ink !ayer %odels* 4ddress
(esolution Protocols* and Inter/ace Iueues ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 313
12)3)1 !ink !ayer ObBects ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 313
12)3)2 4ddress (esolution Protocol ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 313
12)3)3 Inter/ace Iueues ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 312
12): %edium 4ccess Control !ayer< IEEE ",2)11 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 312
12):)1 .escrition o/ IEEE ",2)11 %4C Protocol ) ) ) ) ) ) ) ) ) ) ) ) ) 31"
12):)2 NS2 Classes %ac and %ac/01 22 ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
31#
AAii
AAii
Contents
12):)3 +asic Cunctions o/ NS2 Classes %ac
and %ac/01 22 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
321
12):): Timer Concets /or Imlementation o/ IEEE ",2)11 ) ) ) 323
12):)3 Packet (ecetion %ec&anism o/ IEEE ",2)11 ) ) ) ) ) ) ) ) ) ) 323
12):)8 Imlementation o/ Packet (etransmission in NS2 ) ) ) ) ) ) 328
12):)2 Imlementation o/ Carrier9Sensin'* +acko//*
and N47 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 32#
12)3 P&ysical !ayer< P&ysical Network Inter/aces and C&annel ) ) ) ) ) ) ) ) 331
12)3)1 P&ysical Network Inter/ace ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 331
12)3)2 6ireless C&annels ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 333
12)3)3 Sender Oerations at t&e P&ysical !ayer ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 333
12)3): (ecei1er Oerations at t&e P&ysical !ayer ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33:
12)8 4n Introduction to Node %obility ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
332 12)8)1 +asic %obility Con/i'uration ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 332
12)8)2 Leneral Oeration .irector ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33"
12)8)3 (andom %obility ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33#
12)8): %obility and Tra//ic Lenerators< Standalone
Heler 0tility ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3:,
12)2 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3:3
12)" EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3::
%* -eve#o&ing New Mou#es for NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3:3
13)1 4utomatic (eeat reIuest ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3:3
13)1)1 T&e .esi'n ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3:8
13)1)2 CCC Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3:"
13)1)3 OTcl Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33:
13)1): 4(I 0nder a .elayed ?Error9Cree@
Ceedback C&annel ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 332
13)2 Packet Sc&edulin' /or %ulti9Clow .ata Transmission ) ) ) ) ) ) ) ) ) ) ) ) ) 33#
13)2)1 T&e .esi'n ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 33#
13)2)2 CCC Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 38,
13)2)3 OTcl Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 383
13)3 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 382
13): EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 38"
%/ Postsimu#ation Processing2 -ebugging3 Tracing3
an Resu#t $om&i#ation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 38#
1:)1 .ebu''in'< 4 Process to (emo1e Pro'rammin' Errors ) ) ) ) ) ) ) ) ) ) ) 38#
1:)1)1 Tyes o/ Pro'rammin' Errors ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 38#
1:)1)2 .ebu''in' Luidelines ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 321
1:)2 7ariable Tracin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 32:
1:)2)1 4cti1ation Process /or 7ariable Tracin') )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
32:
1:)2)2 Traceable 7ariable ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
323
1:)2)3 Comonents and 4rc&itecture /or 7ariable Tracin' ) ) ) ) ) 328
1:)2): Tracin' in 4ction< 4n EAamle o/ Class TcpA$ent) ) ) 3"1
1:)2)3 Settin' 0 7ariable Tracin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3"1
13):)1 +it %askin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ::#
13):)2 +it S&i/tin' and .ecimal %ultilication ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :31
13)3 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :32
13)8 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :32
A Programming "ssentia#s ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :33
4)1 Tcl Pro'rammin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :33
4)1)1 Pro'ram In1ocation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :33
4)1)2 SyntaA ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :38
4)1)3 7ariables and +asic Oerations ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :32
4)1): !o'ical and %at&ematical Oerations ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :8,
4)1)3 Control Structure ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :81
4)1)8 %odulariJation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :83
4)1)2 4d1anced Inut$Outut< Ciles and C&annels ) ) ) ) ) ) ) ) ) ) ) ) ) :83
4)1)" .ata Tyes ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :82
Contents AAiii
1:)3 Packet Tracin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3":
1:)3)1 OTcl Con/i'uration Inter/aces ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3"3
1:)3)2 CCC %ain Packet Tracin' Class Trace ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3"#
1:)3)3 CCC Heler Class .aseTrace ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3#2
1:)3): 7arious Tyes o/ Packet Tracin' ObBects ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3#:
1:)3)3 Cormat o/ Trace Strin's /or Packet Tracin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3#2
1:): Comilation o/ Simulation (esults ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :,2
1:)3 C&ater Summary ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :,8
1:)8 EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :,2
%0 Re#ate He#&er $#asses ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :,#
13)1 Timers ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :,#
13)1)1 Imlementation Concet o/ Timer in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :,#
13)1)2 OTcl Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :11
13)1)3 CCC Class Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :13
13)1): Luidelines /or Imlementin' Timers in NS2 ) ) ) ) ) ) ) ) ) ) ) ) :23
13)2 Imlementation o/ (andom Numbers in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
:2: 13)2)1 (andom Number Leneration ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2:
13)2)2 Seedin' a (andom Number Lenerator ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :23
13)2)3 OTcl and CCC Imlementation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :22
13)2): (andomness in Simulation Scenarios ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2#
13)2)3 (andom 7ariables ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :31
13)2)8 Luidelines /or (andom Number Leneration
in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :3:
13)3 +uilt9in Error %odels ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :33
13)3)1 OTcl Imlementation< Error %odel Con/i'uration ) ) ) ) ) ) :38
13)3)2 CCC Imlementation< Error %odel Simulation ) ) ) ) ) ) ) ) ::,
13)3)3 Luidelines /or Imlementin' a New Error
%odel in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ::"
13): +it Oerations in NS2 ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ::#
AAi1
AAi1
Contents
+)1 Cundamentals o/ Polymor&ism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"3
+)2 Tye Castin' and Cunction 4mbi'uity ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :""
+)3 7irtual Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"#
+):
+)3
+)8
+)2
4bstract Classes and Pure 7irtual Cunctions) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
Class Comosition< 4n 4lication o/ Tye Castin'
Polymor&ism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
Pro'rammin' Polymor&ism wit& No Tye Castin'<
4n EAamle ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
4 Scalability Problem Caused by Non9Tye Castin'
Polymor&ism ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )
:#,
:#1
:#2
:#3
+)" T&e Class Comosition Pro'rammin' Concet ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :#:
$ BS- +ink +ist an Bit +eve# 4unctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :##
C)1 +S. !ink !ist ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :##
C)2 +it !e1el Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :##
References ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3,1
;enera# 'ne< ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3,3
$oe 'ne< ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 3,2
4)2 ObBected9Oriented Tcl Pro'rammin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :8#
4)2)1 OTcl !an'ua'e Structure ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2,
4)2)2 Classes and In&eritance ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2,
4)2)3 ObBects and ObBect Construction Process ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :21
4)2): %ember 7ariables and Cunctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :22
4)2)3 4 !ist o/ 0se/ul Instance Procedures ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2:
4)3 46K Pro'rammin' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :28
4)3)1 Pro'ram In1ocation ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :22
4)3)2 4n 46K Scrit ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2"
4)3)3 46K Pro'rammin' Structure ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2"
4)3): Pattern %atc&in' ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2#
4)3)3 +asic 4ctions ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :2#
4)3)8 (edirection and Outut to Ciles ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"1
4)3)2 Control Structure ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"2
4): EAercises ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"2
B A Review of the Po#ymor&hism $once&t in ,,P ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) :"3
$ha&ter %
Simu#ation of $om&uter Networks
Peole communicate) One way or anot&er* t&ey eAc&an'e some in/ormation
amon' t&emsel1es all t&e times) In t&e ast se1eral decades* many electronic
tec&nolo'ies &a1e been in1ented to aid t&is rocess o/ eAc&an'in' in/ormation
in an e//icient and creati1e way) 4mon' t&ese are t&e creation o/ /iAed tele&one
networks* t&e broadcastin' o/ tele1ision and radio* t&e ad1ent o/ comuters* t&e
rise o/ t&e Internet* and t&e emer'ence o/ wireless sensation) Ori'inally* t&ese
tec&nolo'ies eAisted and oerated indeendently* ser1in' t&eir 1ery own
uroses) Not until recently t&at t&ese tec&nolo'ical wonders &a1e started to
con1er'e* and it is a well9known /act t&at a comuter communication network is a
result o/ t&is con1er'ence)
T&is c&ater resents an o1er1iew o/ comuter communication networks and
t&e basics o/ simulation o/ suc& a network) Section 1)1 introduces a comuter
network alon' wit& t&e re/erence model w&ic& is used /or describin' t&e
arc&itecture o/ a comuter communication network) 4 brie/ discussion on
desi'nin' and modelin' a comleA system suc& as a comuter network is t&en
'i1en in Sect) 1)2) In Sect) 1)3* t&e basics o/ comuter network simulation are
discussed) Section 1): resents one o/ t&e most common tye o/ network
simulation* namely* t&e time9 deendent simulation) 4n eAamle simulation is
'i1en in Sect) 1)3) Cinally* Sect) 1)8 summariJes t&e c&ater)
%=% $om&uter Networks an the +ayering $once&t
4 comuter network is usually de/ined as a collection o/ comuters intercon9
nected /or 'at&erin'* rocessin'* and distributin' in/ormation) Computer is used
as a broad term &ere to include de1ices suc& as workstations* ser1ers* routers*
modems* base stations* and wireless eAtension oints) T&ese comuters are con9
nected by communication links suc& as coer cables* /iber otic cables* and
microwa1e$satellite$radio links) 4 comuter network can be built as a nestin'
and$or interconnection o/ se1eral networks) T&e Internet is a 'ood eAamle o/
comuter
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* 1
.OI 1,)1,,2$#2"919:81:91:,893 1* = Srin'er Science>+usiness %edia* !!C 2,12
2 1 Simulation o/ Comuter Networks
networks) In /act* it is a network o/ networks* wit&in w&ic& tens o/ t&ousands o/
networks interconnect millions o/ comuters worldwide)
1.1.1 Layering Concept
4 comuter network is a comleA system) To /acilitate desi'n and /leAible imle9
mentation o/ suc& a system* t&e concet o/ layering is introduced) 0sin' a layered
structure* t&e /unctionalities o/ a comuter network can be or'aniJed as a stack o/
layers)
!o'ically* eac& layer communicates to its eer ?a lo'ical entity on t&e same
layer@ on t&e ot&er communication node) Howe1er* t&e actual data transmission
occurs t&rou'& t&e lowest layer* namely* t&e &ysical layer) T&ere/ore* data at t&e
source node always mo1e down t&e layers until reac&in' t&e &ysical layer) T&en*
it is transmitted 1ia a &ysical link to a nei'&borin' node or t&e destination node)
4t t&e destination node* t&e data are assed to t&e layers until reac&in' t&e
corresondin' eer)
(eresentin' a well9de/ined and seci/ic art o/ t&e system* eac& layer ro1ides
certain services to t&e abo1e layer) 6&en er/ormin' a task ?e)')* transmit a
acket@* an uer layer asks its lower layer to do more seci/ic Bob) 4ccessible ?by
t&e uer layers@ t&rou'& so9called inter/aces* t&ese ser1ices usually de/ine what
s&ould be done in terms o/ network oerations or rimiti1es* but do not
seci/ically de/ine how suc& t&in's are imlemented) T&e details o/ &ow a ser1ice
is imlemented are de/ined in a so9called rotocol)
4 rotocol is a set o/ rules t&at multiple eers comly wit& w&en
communicatin' to eac& ot&er)
1
4s lon' as t&e eers abide to a rotocol* t&e
communication er/ormance would be consistent and redictable) 4s an eAamle*
consider an error detection rotocol) 6&en a transmitter sends out a data acket*
it may wait /or an acknowled'ment /rom t&e recei1er) T&e recei1er* on t&e ot&er
&and* may be resonsible /or acknowled'in' to t&e transmitter t&at t&e
transmitted ackets are recei1ed success/ully)
T&e beauty o/ t&is layerin' concet is t&e layer indeendency) T&at is* a c&an'e
in a rotocol o/ a certain layer does not a//ect t&e rest o/ t&e system as lon' as t&e
inter/aces remain unc&an'ed) Here* we &i'&li'&t t&e words services* protocol* and
interface to em&asiJe t&at it is t&e interaction amon' t&ese comonents t&at
makes u t&e layerin' concet)
Ci'ure 1)1 'ra&ically s&ows an o1erall 1iew o/ t&e layerin' concet used
/or communication between two comuter &osts< a source &ost and a destination
&ost) In t&is /i'ure* t&e /unctionality o/ eac& comuter &ost is di1ided into /our
1
0nlike a rotocol* an al'orit&m is a set o/ stes to 'et t&in's done ?eit&er wit& or wit&out
communications@)
H1 H2 H3 M1 H1 H2 H3 M2 H1 H2 H3 M1 H1 H2 H3 M2
1)1 Comuter Networks and t&e !ayerin' Concet 3
Source
M
Layer 4 Protocol
Destination
M
H3 M1
H2 H3 M1
H3 M2
H2 H3 M2
Layer 3 Protocol
Layer 2 Protocol
Layer 1
Protocol
H3 M1
H2 H3 M1
H3 M2
H2 H3 M2
Physical Medium
4ig= %=% .ata /low in a layered network arc&itecture
layers)
2
6&en lo'ically linked wit& t&e same layer on anot&er &ost* t&ese layers
are called peers)
3
4lt&ou'& not directly connected to eac& ot&er* t&ese eers
lo'ically communicate wit& one anot&er usin' a rotocol reresented by an
arrow) 4s mentioned earlier* t&e actual communication needs to roa'ate down
t&e stack and use t&e abo1e layerin' concet)
Suose an alication rocess runnin' on !ayer : o/ t&e source 'enerates data
or messa'es destined /or t&e destination) T&e communication starts by assin' a
'enerated messa'e % down to !ayer 3* w&ere t&e data are se'mented into two
c&unks ?%2 and %1@* and control in/ormation called header ?H3@ seci/ic to
!ayer
3 is aended to %2 and %1) T&e control in/ormation are* /or eAamle* seDuence
numbers* acket siJes* and error c&eckin' in/ormation) T&ese in/ormation are
understandable and used only by t&e eerin' layer on t&e destination to reco1er
t&e data ?%@) T&e resultin' data ?e)')* H34%2@ are called a Frotocol data unit
?P.0@G and are &anded to t&e neAt lower layer* w&ere some rotocol9seci/ic
control in/ormation is a'ain added to t&e messa'e) T&is rocess continues until t&e
messa'e reac&es t&e lowest layer* w&ere transmission o/ in/ormation is actually
er/ormed o1er a &ysical medium) Note t&at* alon' t&e line o/ t&ese rocesses* it
mi'&t be necessary to /urt&er se'ment t&e data /rom uer layers into smaller
se'ments /or 1arious uroses) 6&en t&e messa'e reac&es t&e destination* t&e
re1erse rocess takes lace) T&at is* as t&e messa'e is mo1in' u t&e stack* its
&eaders are ried o// layer by layer) I/ necessary* se1eral messa'es are ut
to'et&er be/ore bein' assed to t&e uer layer) T&e rocess continues until t&e
ori'inal messa'e ?%@ is reco1ered at !ayer :)
2
Cor t&e sake o/ illustration only /our layers are s&own) In t&e real9world systems* t&e number o/
layers may 1ary* deendin' on t&e /unctionality and obBecti1es o/ t&e networks)
3
4 eerin' &ost o/ a source and a destination are t&e destination and t&e source* resecti1ely)
: 1 Simulation o/ Comuter Networks
1.1.2 OSI and TCP/IP Reference Models
T&e Oen Systems Interconnection ?OSI@ model was t&e /irst re/erence model
de1eloed by International Standards Or'aniJation ?ISO@ to ro1ide a standard
/ramework to describe t&e rotocol stacks in a comuter network) Its consists o/
se1en layers* w&ere eac& layer is intended to er/orm a well9de/ined /unction M1N)
T&ese are &ysical layer* data link layer* network layer* transort layer* session
layer* resentation layer* and alication layer) T&e OSI model only seci/ies
w&at eac& layer s&ould doO it does not seci/y t&e eAact ser1ices and rotocols to
be used in eac& layer)
T&e Transmission Control Protocol ?TCP@$Internet Protocol ?IP@ re/erence
model M1N* w&ic& is based on t&e two rimary rotocols* namely* TCP and IP* is
used in t&e current Internet) T&ese rotocols &a1e ro1en 1ery ower/ul* and as a
result &a1e eAerienced widesread use and imlementation in t&e eAistin'
comuter networks) It was de1eloed /or 4(P4NET* a researc& network
sonsored by t&e 0S .eartment o/ .e/ense* w&ic& is considered as t&e
'randarent o/ all comuter networks) In t&e TCP$IP model* t&e rotocol stack
consists o/ /i1e layers H &ysical* data link* network* transort* and alication H
eac& o/ w&ic& is resonsible /or certain ser1ices as will be discussed s&ortly) Note
t&at t&e alication layer in t&e TCP$IP model can be considered as t&e
combination o/ session* resentation* and alication layers o/ t&e OSI model)
%=%=2=% A&&#ication +ayer
T&e alication layer sits on to o/ t&e stack and uses ser1ices /rom t&e transort
layer ?discussed below@) T&is layer suorts se1eral &i'&er9le1el rotocols suc& as
HyerteAt Trans/er Protocol ?HTTP@ /or 6orld 6ide 6eb alications* Simle
%ail Trans/er Protocol ?S%TP@ /or electronic mail* TE!NET /or remote 1irtual
terminal* .omain Name Ser1ice ?.NS@ /or main' comre&ensible &ost names
to t&eir network addresses* and Cile Trans/er Protocol ?CTP@ /or /ile trans/er)
%=%=2=2 Trans&ort +ayer
T&e obBecti1e o/ a transort layer is to er/orm /low control and error control /or
messa'e transortation) Clow control ensures t&at t&e end9to9end transmission
seed is neit&er too /ast to make t&e network con'ested nor too slow to
underutiliJe t&e net9 work) Error control ensures t&at t&e ackets are deli1ered to
t&e destination roerly)
Lenerally* w&en a transort rotocol recei1es a messa'e /rom t&e &i'&er layer*
it breaks down t&e messa'e into smaller ieces) T&en it 'enerates a P.0 H called a
segment H by attac&in' necessary error and /low control in/ormation* and asses
t&e se'ment to t&e lower layer)
Two well9known transort rotocols* namely* TCP and 0ser .ata'ram
Protocol ?0.P@* are de/ined in t&is layer) 6&ile TCP is resonsible /or a reliable
and connection9oriented communication between two &osts* 0.P suorts an
unreliable
1)2 System %odelin' 3
connectionless transort) TCP is ideal /or alications t&at re/er accuracy o1er
romt deli1ery and t&e re1erse is true /or 0.P)
%=%=2=* Network +ayer
T&is layer determines t&e route t&rou'& w&ic& a acket is deli1ered /rom a source
node to a destination node) 4 P.0 /or t&e network layer is called a packet)
%=%=2=/ +ink +ayer
4 link layer rotocol &as t&ree main resonsibilities) Cirst* /low control re'ulates
t&e transmission seed in a communication link) Second* error control ensures t&e
inte'rity o/ data transmission) T&ird* /low multileAin'$demultileAin' combines
multile data /lows into and eAtracts data /lows /rom a communication link)
C&oices o/ link layer rotocols may 1ary /rom &ost to &ost and network to
network) EAamles o/ widely used link layer rotocols$tec&nolo'ies include
Et&ernet* Point9 to9Point Protocol ?PPP@* IEEE ",2)11 ?i)e)* 6i9Ci@* and
4sync&ronous Trans/er %ode ?4T%@)
!ink layer rotocols are di//erent /rom transort layer rotocol as /ollows) T&e
/ormer deals wit& a sin'le communication link) On t&e ot&er &and* t&e latter does
t&e same Bob /or an end9to9end /low w&ic& may tra1erse multile links)
%=%=2=0 Physica# +ayer
T&e &ysical layer deals wit& t&e transmission o/ data bits across a communication
link) Its rimary 'oal is to ensure t&at t&e transmission arameters ?e)')*
transmission ower@ are set aroriately to ac&ie1e t&e reDuired transmission
er/ormance ?e)')* to ac&ie1e t&e tar'et bit error rate er/ormance@)
Cinally* we oint out t&at t&e /i1e layers discussed abo1e are common to t&e
OSI layer) 4s &as been mentioned already* t&e OSI model contains two ot&er
layers sittin' on to o/ t&e transort layer* namely* session and resentation
layers) T&e session layer simly allows users on di//erent comuters to create
communication sessions amon' t&emsel1es) T&e resentation layer basically takes
care o/ di//erent data resentations eAistin' across t&e network) Cor eAamle* a
uni/ied network mana'ement system 'at&ers data wit& di//erent /ormat /rom
di//erent comuters and con1erts t&eir /ormat into a uni/orm /ormat)
%=2 System Moe#ing
System modelin' is an act o/ /ormulatin' a simle reresentation /or an actual
system) It allows in1esti'ators to look closely into t&e system wit&out &a1in' to
actually imlement it) .urin' t&e in1esti'ation* 1arious arameters can be alied
8 1 Simulation o/ Comuter Networks
to study system be&a1ior) 4/ter t&e system is well understood* in1esti'ators can
decide w&et&er t&e actual system s&ould be imlemented)
System modelin' o/ten reDuires simli/ication assumtions) T&ese assumtions
eAclude irrele1ant details o/ t&e actual system* &ence makin' t&e model cleaner
and easier to imlement) Howe1er* eAcessi1e assumtions may lead to inaccurate
reresentation o/ t&e system) .esi'n en'ineers need to use t&eir discretion to
ac&ie1e t&e best modelin' trade9o//)
Traditionally* t&ere are two modelin' aroac&es< 4nalytical aroac& and
simulation aroac&)
1.2.1 Analytical Approach
T&e 'eneral concet o/ analytical modelin' aroac& is to come u wit& a way to
describe t&e system mat&ematically* and aly numerical met&ods to 'ain insi'&t
/rom t&e de1eloed mat&ematical model) EAamles o/ widely used mat&ematical
tools are Dueuin' and robability t&eories) Since analytical results deri1e mainly
/rom mat&ematical roo/s* t&ey are true as lon' as t&e underlyin' conditions &old)
I/ roerly used* analytical modelin' can be a cost9e//ecti1e way to ro1ide a
'eneral 1iew o/ t&e system)
1.2.2 Si!lation Approach
Simulation recreates real9world scenarios usin' comuter ro'rams) It is used in
1arious alications ran'in' /rom oerations researc&* business analysis* manu/ac9
turin' lannin'* and biolo'ical eAerimentation* Bust to name a /ew) Comared to
analytical modelin'* simulation usually reDuires /ewer simli/ication assumtions*
since almost e1ery ossible detail o/ system seci/ications can be incororated in a
simulation model) 6&en t&e system is rat&er lar'e and comleA* a strai'&t/orward
mat&ematical /ormulation may not be /easible) In t&is case* t&e simulation
aroac& is usually re/erred to t&e analytical aroac&) T&e essence o/
simulation is to er/orm eAtensi1e eAeriment and make con1incin' ar'ument /or
'eneraliJation) .ue to t&e 'eneraliJation* simulation results are usually considered
not as stron' as t&e analytical results)
%=* Basics of $om&uter Network Simu#ation
4 simulation is* more or less* a combination o/ art and science) T&at is* w&ile t&e
eAertise in comuter ro'rammin' and t&e alied mat&ematics accounts /or t&e
science art* t&e 1ery skills in analysis and concetual model /ormulation usually
reresent t&e art ortion) 4 lon' list o/ stes in eAecutin' a simulation rocess* as
'i1en in M2N* seems to re/lect t&is oular claim)
1)3 +asics o/ Comuter Network Simulation 2
4 simulation o/ 'eneral comuter networks consists o/ t&ree main arts<
Part ! Planning< T&is art includes de/inin' t&e roblem* desi'nin' t&e
corresondin' model* and de1isin' a set o/ eAeriments /or t&e /ormulated
simulation model) It is recommended t&at :,P o/ time and e//ort be sent on
lannin')
Part 2 ! Implementing< Imlementation o/ simulation ro'rams consists o/
t&ree stes<
H Step ! Initiali"ation< T&is ste establis&es initial conditions ?e)')* resettin'
simulation clocks and 1ariables@ so t&at t&e simulation always starts /rom a
known state)
H Step 2 ! #esult generation< T&e simulation creates and eAecutes e1ents* and
collects necessary data 'enerated by t&e created e1ents)
H Step $ ! Postsimulation processing< T&e raw data collected /rom simulation
are rocessed and translated into er/ormance measures o/ interest)
It is recommended t&at 2,P o/ time s&ould be used /or imlementation)
Part $ ! Testing< T&is art includes 1eri/yin'$1alidatin' t&e simulation model*
eAerimentin' on t&e scenarios de/ined in Part 1 and ossibly /ine9tunin' t&e
eAeriments t&emsel1es* and analyJin' t&e results) T&e remainin' :,P o/ time
s&ould be used in t&is art)
T&is /ormula is in no way a strict one) 4ny actual simulation may reDuire more
or less time and e//ort* deendin' on t&e conteAt o/ interest* and de/initely on t&e
modeler &imsel/$&ersel/)
1.".1 Si!lation Coponents
4 comuter network simulation can be t&ou'&t o/ as a /low o/ interaction amon'
network entities ?e)')* nodes* ackets@) T&ese entities mo1e t&rou'& t&e system*
interact wit& ot&er entities* Boin acti1ities* tri''er e1ents* cause some c&an'es to
state o/ t&e system* and terminate t&emsel1es) Crom time to time* t&ey contend or
wait /or some tye o/ resources) T&is imlies t&at t&ere must be a lo'ical
eAecution seDuence to cause all t&ese actions to &aen in a comre&ensible and
mana'eable way)
4ccordin' to In'alls M:N* t&e key comonents o/ a simulation include t&e
/ollowin'<
%=*=%=% "ntities
Entities are obBects t&at interact wit& one anot&er in a simulation ro'ram) T&ey
cause some c&an'es to t&e states o/ t&e system) In t&e conteAt o/ a comuter
network* entities may include comuter nodes* ackets* /lows o/ ackets* or
non&ysical obBects suc& as simulation clocks)
" 1 Simulation o/ Comuter Networks
%=*=%=2 Resources
(esources are limited 1irtual assets s&ared by entities suc& as bandwidt& or ower
bud'et)
%=*=%=* Activities an "vents
Crom time to time* entities en'a'e in some acti1ities) T&e en'a'ement creates
e1ents and tri''ers c&an'es in t&e system state) Common eAamles o/ e1ents are
acket recetion and route udate e1ents)
%=*=%=/ Scheu#er
4 sc&eduler maintains a list o/ e1ents and t&eir eAecution time) .urin' a
simulation* it mo1es alon' a simulation clock and eAecutes e1ents in t&e list
c&ronolo'ically)
%=*=%=0 State an ;#oba# >ariab#es
State 1ariables kee track o/ t&e system state) T&ey can be classi/ied as local
1ariables and 'lobal 1ariables based on t&eir scoe o/ oeration) !ocal 1ariables
are 1alid under a limited ran'e* w&ile 'lobal 1ariables are understandable 'lobally
by all ro'ram entities)
In 'eneral* 'lobal state 1ariables &old 'eneral in/ormation s&ared by se1eral
entities suc& as t&e total number o/ nodes* t&e 'eo'ra&ical area in/ormation* t&e
re/erence to t&e sc&eduler* and so on)
%=*=%=6 Ranom Number ;enerator
4 (andom Number Lenerator ?(NL@ introduces randomness in a simulation
model) It 'enerates random numbers by seDuentially ickin' numbers /rom a
deterministic seDuence o/ seudo9random numbers M3N* yet t&e numbers icked
/rom t&is seDuence aear to be random)
6it&out randomness* t&e results /or e1ery run would be eAactly t&e same) To
'enerate a set o/ di//erent results* we may initialiJe t&e (NL /or di//erent runs
wit& di//erent seeds) 4 seed identi/ies t&e /irst location w&ere t&e (NL starts
ickin' random numbers) Two simulations w&ose (NL icks di//erent initial
ositions would 'enerate di//erent simulation results)
In a comuter network simulation* /or eAamle* a acket arri1al rocess and a
ser1ice rocess are usually modeled as random rocesses) T&ese random rocesses
are usually imlemented wit& t&e aid o/ an (NL) T&e readers are re/erred to M8* 2N
/or a comre&ensi1e treatment on random rocess imlementation)
1)3 +asics o/ Comuter Network Simulation #
%=*=%=5 Statistics ;atherer
Statistics 'at&erers use 1ariables to collect rele1ant data ?e)')* acket arri1al and
dearture time@) T&ese data can later be used to comute t&e er/ormance
measures suc& as a1era'e and standard de1iation o/ t&e Dueuin' delay /or data
ackets tra1ersin' a network)
1.".2 Si!lation Perforance
Per/ormance o/ a simulation is measured by t&e /ollowin' metrics
M3N<
E%ecution speed< How /ast a simulation can be comleted
Cost< EAense aid to rocure so/tware$&ardware* de1elo simulation
ro'rams* and obtain simulation results) Lenerally* commercial tools &a1e
more /eatures and easier to work wit& at t&e eAense o/ increasin' cost)
&idelity< How reliable t&e simulation results are) Cidelity can be increased by
incororatin' more details ?i)e)* makin' less assumtions@ into t&e simulation)
#epeata'ility< 4n assurance t&at i/ t&e eAeriment was to be reeated* t&e
results would be t&e same) (eeatability can be Duanti/ied usin' confidence
interval ?see t&e details in Sect) 1)3)3@)
Scala'ility< T&e imact o/ t&e siJe o/ t&e roblem ?e)')* t&e number o/ node* t&e
inut tra//ic@ on ot&er simulation er/ormance measures)
1."." Confidence Inter#al
Confidence interval M8N is a use/ul mat&ematical tool w&ic& &els Duanti/y t&e
le1el o/ reeatability) 4 con/idence inter1al is a ran'e between w&ic& one &as
con/idence in /indin' data oints) It is c&aracteriJed by t&e widt& and t&e
con/idence coe//icient ?i)e)* robability@ to /ind data oints) Ci'ure 1)2 s&ows an
eAamle o/ con/idence inter1al o/ M 1*1N wit& t&e con/idence coe//icient is ",P)
T&e interretation o/ t&is eAamle is t&at t&e robability o/ /indin' a data oint
wit&in an inter1al M 1*1N is ,)")
It is /airly imossible$imractical to &a1e er/ectly reeatable results)
Con/idence inter1al measures suc& imer/ection) 4s lon' as t&e imer/ection is
well de/ined ?e)')* by con/idence inter1al@ and reasonable* t&e simulation results
are usually deemed su//iciently reliable)
1.".$ Choices for %et&or' Si!lation
Tools
T&ere is a wide 1ariety o/ network simulation tools in t&e market) Eac& &as its own
stren't&s and weaknesses) To c&oose t&e most aroriate one* t&e /ollowin'
/actors mi'&t be considered M3N<
1, 1 Simulation o/ Comuter Networks
4ig= %=2 4 con/idence
inter1al o/ M 1*1N wit&
con/idence coe//icient o/ ",P
Probability density function (f(x))
!"
#
$1 1
%=*=/=% Simu#ation P#atform
T&e simulation lat/orm can be so/tware* &ardware* or &ybrid) So/tware
simulation lat/orms can be 1ery /leAible and economical) In most cases* it can
be installed in ersonal comuters or ser1ers) T&ere/ore* it can be u'raded 1ery
easily) T&e &ardware simulation lat/orm ?e)')* t&ose usin' 1ery &i'&9le1el desi'n
lan'ua'e ?7H.!@@ can be 1ery /ast to run and is more suitable /or comutationally
intensi1e simulation) It is also essential w&en inut arameters need to be
collected /rom surroundin' en1ironment) T&e maBor drawback o/ &ardware
simulation lat/orm is t&at t&ey can be ro&ibiti1ely eAensi1e to be
imlemented and modi/ied) Hybrid simulation lat/orms combine t&e bene/its o/
bot& t&e so/tware and t&e &ardware lat/orms) 4n eAamle o/ &ybrid simulation
lat/orms is Hardware In t&e !oo ?HI!@ simulation* w&ic& is usually used to test
comleA real9time embedded systems M3N)
%=*=/=2 Ty&es of Simu#ation Too#s
Simulation tools can also be classi/ied based on &ow t&ey are
de1eloed<
(pen)source or closed)source< +y re1ealin' its source code* oen9source so/t9
ware oens itsel/ /or in1esti'ation) 0sers$ro'rammers can /ind and reort
roblems* modi/y t&e source codes* incororate new /eatures* and redistribute
t&e so/tware) T&e drawback o/ t&e oen9source so/tware is t&e lack o/
accountability) 4 lot o/ oen9source so/tware roBects is run by 1olunteers)
Since t&ey can be modi/ied by anyone at any time* t&ey mi'&t be&a1e
di//erently /rom users5 eAectation) Closed9source so/tware* on t&e ot&er &and*
can be modi/ied only by t&e so/tware de1eloers) T&ere/ore* t&ese de1eloers
are /ully accountable /or t&e so/tware Duality)
&ree or commercial< 4lt&ou'& /ree o/ c&ar'e* /ree so/tware may lack t&e
suort and accountability) Commercial so/tware* on t&e ot&er &and* is usually
well documented and &as better tec&nical suort)
Pu'licly availa'le or in)house< Publicly a1ailable so/tware can be oen9source
or close9source* and can be /ree or commercial) It can &el sa1e substantial
e//ort
reDuired to de1elo simulation so/tware) 6&en aroriately c&osen* it can be
/airly trustwort&y* since well9de1eloed so/tware would &a1e been eAtensi1ely
eAamined by t&e ublic) .e1eloed internally* in9&ouse so/tware &as 'reater
/leAibility) 6&en t&e so/tware needs to be c&an'ed or udated* t&e de1eloers
know w&at* w&ere* and &ow to make t&e c&an'es raidly)
%=*=/=* 9ser 'nterface
T&e user inter/aces o/ a simulation ro'ram can be Command !ine Inter/ace ?C!I@
or Lra&ic 0ser Inter/ace ?L0I@) 4imin' at obtainin' statistical results* a lar'e
number o/ academic works use C!I9based simulation tools* since t&ese tools use
most comutational ower /or simulations) L0I9based simulation tools* on t&e
ot&er &and* allocate a art o/ comutational ower to imro1e user inter/ace) T&ey
usually ro1ide user9/riendly network con/i'uration inter/aces* and &a1e 'ra&ical
and animation9based simulation result resentation)
%=*=/=/ "<am&#es of Simu#ation Too#s
T&e /ollowin' are some o/ t&e widely used network simulation
tools<
NS1< 4n oen9source so/tware written in CCC and OTcl ro'rammin' lan9
'ua'es
-lo%oSim< 4n oen9source so/tware de1eloed at 0ni1ersity o/ Cali/ornia*
!os 4n'eles ?0C!4@
!alNet< 4 commercialiJed 1ersion o/ -lo%oSim) It suorts a wider
1ariety o/ rotocols* &as better documentation* and ro1ides customiJable
simulation modules)
Opnet< 4 commercial network simulation tool w&ic& o//ers se1eral /eatures
H includin' HI!* arallel comutin'* detailed documentation* and tec&nical
suort)
%ATLA.< 4 commercial multi9urose so/tware t&at can be used /or network
simulation and comleA numerical e1aluation)
%=/ Time.-e&enent Simu#ation
4s its name su''ested* time9deendent simulation roceeds c&ronolo'ically)
It maintains a simulation clock to kee track o/ simulation time) +ased on &ow
e1ents are &andled* time9deendent simulation can be classi/ied into two
cate'ories< time9dri1en simulation and e1ent9dri1en simulation)
12 1 Simulation o/ Comuter Networks
2 4
a
!
3
b c
%
&
time
4ig= %=* Clock ad1ancement in a time9dri1en simulation
1.$.1 Tie()ri#en Si!lation
Time9dri1en simulation induces and eAecutes e1ents /or e1ery /iAed time inter1al
o/
time units) In articular* it looks /or e1ents t&at may &a1e occurred durin' t&is
/iAed inter1al) I/ /ound* suc& e1ents would be eAecuted as i/ t&ey occurred at t&e
end o/ t&is inter1al) 4/ter t&e eAecution* it ad1ances t&e simulation clock by time
units and reeats t&e rocess) T&e simulation roceeds until t&e simulation time
reac&es a rede/ined termination time)
Ci'ure 1)3 s&ows t&e basic idea be&ind time ad1ancement in a time9dri1en
simulation) T&e cur1ed arrows reresent suc& ad1ances* and a) b) and c
mark t&e occurrences o/ e1ents) .urin' t&e /irst inter1al* no e1ent occurs) T&e
second inter1al contains e1ent a* w&ic& is not &andled until t&e end o/ t&e inter1al)
Time inter1al ? @ is an imortant arameter o/ time9dri1en simulation) 6&ile a
lar'e inter1al can lead to loss o/ in/ormation* a small inter1al can cause
unnecessary waste o/ comutational e//ort) Suose* in Ci') 1)3* e1ents b and
c in t&e /i/t& inter1al are acket arri1al and dearture e1ents* resecti1ely) Since
t&ese two e1ents are considered to occur eAactly at t&e end o/ t&e inter1al ?i)e)* at
3 @* t&e system state would be as i/ t&ere is no acket arri1al or dearture e1ents
durin' Q: O 3 ) T&is is considered a loss o/ in/ormation) 4n eAamle o/ waste
o/ comutational e//ort occurs between 2 and : ) 4lt&ou'& no e1ent occurs in
t&is inter1al* t&e simulation wastes t&e comutational resource to sto and rocess
e1ents at 3 and
: ) In time9dri1en simulation* ro'rammers need to use t&eir discretion to
otimiJe t&e time inter1al 1alue )
E%ample ** Pro'ram 1)1 s&ows t&e seudo codes /or a time9dri1en simulation)
!ines 1 and 2 initialiJe t&e system state 1ariables and t&e simulation clock* resec9
ti1ely) !ine 3 seci/ies t&e stoin' criterion) !ines :H8 are run as lon' as t&e sim9
ulation clock ?i)e)* sim5clock@ is less t&an t&e rede/ined t&res&old stopTime)
T&ese lines eAecute e1ents* collect statistics* and ad1ance t&e simulation)
Program %=% Skeleton o/ a time9dri1en simulation
2 initiali6e 7system states8
1 sim5clock 9: startTime;
3 ,(ile 7sim5clock < stopTime8
= collect statistics "rom c!rrent state;
> e*ec!te all events t(at occ!rred d!rin$
?sim5clock) sim5clock 4 step@;
A sim5clock 9: sim5clock 4 step;
B end ,(ile
'o the next e(ent
! a b
time
c
4ig= %=/ Clock ad1ancement in an e1ent9dri1en simulation
Program %=2 Skeleton o/ an e1ent9dri1en simulation
2 initiali6e 7system states8
1 initiali6e 7event list8
3 ,(ile 7Event list C: NDLL8
= retrieve and remove an event
,(ose timestamp is smallest "rom t(e event list
> e*ec!te t(e retrieved event
A set sim5clock 9: time correspondin$ to t(e retrieved
event
B end ,(ile
1.$.2 *#ent()ri#en Si!lation
4n e1ent9dri1en simulation does not roceed accordin' to /iAed time inter1al)
(at&er* it induces and eAecutes e1ents at any arbitrary time) E1ent9dri1en
simulation &as /our imortant c&aracteristics<
E1ery e1ent is stamed wit& its occurrence time and is stored in a so9called
e1ent list)
Simulation roceeds by retrie1in' and remo1in' an e1ent wit& t&e smallest
timestam /rom t&e e1ent list* eAecutin' it* and ad1ancin' t&e simulation clock
to t&e timestam associated wit& t&e retrie1ed e1ent)
4t t&e eAecution* an e1ent may induce one or more e1ents) T&e induced e1ents
are stamed wit& t&e time w&en t&e e1ent occurs and a'ain are stored in t&e
e1ent list) T&e timestam o/ t&e induced e1ents must not be less t&an t&e
simulation clock) T&is is to ensure t&at t&e simulation would ne1er 'o backward
in time)
4n e1ent9dri1en simulation starts wit& a set o/ initial e1ents in t&e e1ent list)
It runs until t&e list is emty or anot&er stoin' criterion is satis/ied)
Ci'ure 1): s&ows a 'ra&ical reresentation o/ e1ent9dri1en simulation) Here*
e1ents a) b) and c are eAecuted in order) T&e time 'a between any air
o/ e1ents is not /iAed) T&e simulation ad1ances /rom one e1ent to anot&er* as
oosed to one inter1al to anot&er in time9dri1en simulation) In e1ent9dri1en
simulation* ro'rammers do not &a1e to worry about otimiJin' time inter1al)
E%ample *2* Pro'ram 1)2 s&ows t&e skeleton o/ a tyical e1ent9dri1en simulation
ro'ram) !ines 1 and 2 initialiJe t&e system state 1ariables and t&e e1ent list*
resecti1ely) !ine 3 seci/ies a stoin' criterion) !ines :H8 are eAecuted as alon'
1: 1 Simulation o/ Comuter Networks
as !ine 3 returns tr!e) 6it&in t&is loo* t&e e1ent w&ose timestam is smallest is
retrie1ed* eAecuted* and remo1ed /rom t&e list) T&en* t&e simulation clock is set to
t&e time associated wit& t&e retrie1ed e1ent)
%=0 A Simu#ation "<am&#e2 A Sing#e.$hanne# ?ueuing System
4s an eAamle* t&is section demonstrates a simulation o/ a sin'le9c&annel Dueuin'
system s&own in Ci') 1)3) Here* we &a1e one communication link connectin'
Node 4 to Node +) 4lications at Node 4 create ackets accordin' to
underlyin' distributions /or inter9arri1al time and ser1ice time) 4/ter t&e creation*
t&e ackets are laced into a transmission bu//er) 6&en t&e communication link
is /ree* t&e &ead o/ t&e line acket is transmitted to Node +* and t&e &ead o/ t&e
line ser1er /etc& anot&er acket /rom t&e bu//er in a Cirst9In9Cirst9Out ?CICO@
manner)
6e now de/ine t&e comonents o/ t&e e1ent9dri1en simulation based on t&e
/ramework discussed in Sect) 1)3)
1.+.1 *ntities
T&e rimary entities in t&is simulation include t&e /ollowin'<
+pplications w&ic& 'enerate tra//ic w&ose inter9arri1al time and ser1ice time
/ollow certain distributions*
+ server w&ic& stores t&e acket bein' transmitted ?its state can be eit&er idle
or b!sy@*
)*D+ ,
)*D+ -
,PP
,PP ,PP
-uffer
./.*
0hannel
4ig= %=0 Illustration o/ a sin'le9c&annel Dueuin' system
4ig= %=6 Packet arri1al e1ent
Pac1et ,rri(al +(ent
'ransmit
Pac1et
yes
0hannel
no
/dle2
+n3ueue
Pac1et
+ ,ueue w&ic& stores ackets waitin' to be transmitted ?its state consists o/ t&e
siJe and t&e current occuancy@* and
Communication link w&ic& carries ackets /rom Node 4 to Node +)
1.+.2 State ,lo-al .aria-les
Cor simlicity* we make all 1ariables 'lobal so t&at t&ey can be accessed /rom
anyw&ere in t&e simulation ro'ram<
n!m5pkts< T&e number o/ ackets in t&e systems H one in t&e &ead9o/9t&e9line
ser1er lus all ackets in t&e bu//er)
link5stat!s< T&e current status o/ t&e communication link ?its state can be
eit&er idle or b!sy@)
1.+." Reso!rce
Ob1iously* t&e only resource in t&is eAamle is t&e transmission time in t&e
c&annel)
1.+.$ *#ents
%ain e1ents in t&is simulation include t&e /ollowin'<
1) pkt5arrival corresonds to a packet arrival e1ent) T&is e1ent occurs w&en
an alication 'enerate a acket) 4s s&own in Ci') 1)8* t&e acket may eit&er
be immediately transmitted or stored in t&e Dueue* deendin' on w&et&er t&e
c&annel is busy or idle)
2) srv5complete corresonds to a successful packet transmission e1ent) T&is
e1ent indicates t&at a acket &as been recei1ed success/ully by node +) 4t t&e
comletion* node 4 be'ins to transmit ?ser1e@ anot&er acket waitin' in t&e
Dueue) I/ t&ere is no more acket to be sent* t&e c&annel becomes idle) T&e /low
dia'ram o/ t&e rocess is s&own in Ci') 1)2)
18 1 Simulation o/ Comuter Networks
Successful Pac1et
'ransmission
-e4in 0hannel
/dle 'ime
yes
5ueue
no
+m6ty2
De3ueue and
transmit a 6ac1et
from the buffer
4ig= %=5 Success/ul acket transmission ?ser1ice comletion@ e1ent
1.+.+ Si!lation Perforance Meas!res and Statistics ,atherers
Here* we consider t&e two /ollowin' er/ormance
measures<
+verage packet transmission latency is t&e a1era'e time t&at a acket sends
?/rom its arri1al to its dearture@ in t&e system)
+verage server utili"ation is t&e ercenta'e time w&ere t&e ser1er is
busy)
It is imortant to note t&at all t&e abo1e measures are t&e a1era'e 1alues taken
o1er time) T&e simulation time s&ould be su//iciently lon' to ensure statistical
accuracy o/ t&e simulation result)
In order to comute t&e abo1e two er/ormance measures* arri1al time and
ser1ice times o/ all t&e ackets must be 'at&ered) T&e comutation o/ ot&er
er/ormance measures /rom t&ese two data will be s&own later in t&is section)
1.+./ Si!lation Progra
Pro'ram 1)3 s&ows t&e skeleton o/ a ro'ram w&ic& simulates t&e sin'le9c&annel
Dueuin' system described abo1e) It roceeds accordin' to t&e t&ree9ste
simulation imlementation de/ined in Sect) 1)3<
Step ! Initiali"ation -.ines !/0< !ines 1 and 2 initialiJe t&e status o/ t&e
communication link ?link5stat!s@ to idle and number o/ ackets in t&e
systems ?n!m5pkts@ to Jero) !ine 3 sets t&e simulation clock to start at Jero) !ine
: creates an e1ent list ?event5list@ by in1okin' t&e rocedure
create5list&') T&e e1ent list contains all e1ents in t&e simulation) 4'ain* t&e
sc&eduler mo1es alon' t&is list and eAecutes t&e e1ents c&ronolo'ically) Crom
wit&in t&e rocedure create5list&'* t&e initial acket arri1al e1ents created
by alications are laced on t&e e1ent list)
Step 2 ! #esult generation -.ines 1!20< T&is is t&e main art o/ t&e ro'ram
w&ere t&e loo runs as lon' as t&e two /ollowin' conditions satis/ied< ?1@ t&e
e1ent list is nonemty and ?2@ t&e simulation clock &as not reac&ed a rede/ined
t&res&old)
Program %=* Simulation skeleton o/ a sin'le9c&annel Dueuin' system
E Initiali6e system states
2 link5stat!s : idle; ET(e initial link stat!s is idle
1 n!m5pkts : 0; EN!mber o" packets in system
3 sim5clock : 0; EC!rrent time o" sim!lation
E-enerate packets and sc(ed!le t(eir arrivals
= event5list : create5list&';
E %ain loop
> ,(ile 7event5list C: empty8 F 7sim5clock < stop5time8
A i" t(e application creates events) insert t(em to t(e list
B e*p!n$e t(e previo!s event "rom event list;
/ set sim5clock : time o" c!rrent event;
G e*ec!te t(e c!rrent event;
20 end ,(ile
EDe"ine events
22 pkt5arrival&'7
21 i"&link5stat!s'
23 link5stat!s : b!sy;
2= n!m5pkts : n!m5pkts 4 2;
E Dpdate Hevent5listH9 P!t Hs!ccess"!l packet t* eventH
E into Hevent5list)H T is random service timeI
2> sc(ed!le event Hsrv5completeH at sim5clock 4 T;
2A else
2B n!m5+!e!e : n!m5+!e!e 4 2; EPlace packet in +!e!e
2/ n!m5pkts : n!m5+!e!e 4 2;
2G 8
10 srv5complete&'7
12 n!m5pkts : n!m5pkts J 2;
11 i"&n!m5pkts K 0'
13 sc(ed!le event Hsrv5completeH at sim5clock 4 T;
1= else
1> link5stat!s : idle;
1A n!m5pkts : 0;
1B 8
6it&in t&e loo* !ine 8 takes arri1al$dearture e1ents ?i/ any@ created by
alications and laced t&em in t&e e1ent list) !ines 2H1, eAecute t&e neAt e1ent
on t&e e1ent list by in1okin' eit&er t&e rocedure pkt5arrival&' in !ines
11H1# or t&e rocedure srv5complete&' in !ines 2,H22)
T&e rocedure pkt5arrival&' ?!ines 11H1#@ c&ecks w&et&er t&e commu9
nication link is idle w&en a acket arri1es) I/ so* t&e link is set to 'usy* and a
service completion e1ent is inserted into t&e event5list /or /uture eAecution)
T&e timestam associated wit& t&e e1ent is eDual to t&e current clock time
?sim5clock@ lus t&e acket5s randomly 'enerated ser1ice time ?T@) I/ t&e link is
1" 1 Simulation o/ Comuter Networks
1 ,)2 ,)3
2 ,)2 ,)3
3 ,)2 ,)1
: ,)2 ,),3
3 ,)1 ,),3
8 ,),3
2 ,),3
Tab#e %=% Probability mass
/unctions o/ inter9arri1al time
and ser1ice time
Inter9arri1al Ser1ice
T ime un i t ?robab ility m ass @ ?robab ility m ass @
Tab#e %=2 Simulation result o/ a sin'le9c&annel Dueuin' system
Packet
Interarr)
time
Ser1ice
time
4rri1al
time
Ser1ice
starts
Packet waitin'
time
Packet transmission
latency
1 H 3 , , , 3
2 2 : 2 3 3 2
3 : 1 8 # 3 :
: 1 1 2 1, 3 :
3 8 3 13 13 , 3
8 2 1 2, 2, , 1
2 2 1 22 22 , 1
" 1 : 23 23 , :
# 3 3 28 22 1 :
1, 3 2 31 31 , 2
1 ) , 3)3
busy* on t&e ot&er &and* t&e acket will be enDueued into t&e bu//er* and t&e
acket counter ?n!m5pkts@ is incremented by one unit)
T&e rocedure srv5complete&' ?!ines 2,H22@ /irst udates t&e number o/
ackets in t&e system ?n!m5pkts@) T&en* it c&ecks w&et&er t&e system contains
any acket) I/ so* t&e &ead9o/9t&e9line acket will be ser1ed) T&is is done by
insertin'
anot&er service completion e1ent at time sim5clock 4 T) Howe1er* i/ t&e
Dueue is emty* t&e c&annel is set to idle and t&e number o/ ackets in t&e
system is set to Jero)
Step $ ! Postsimulation processing< T&is ste collects and comutes t&e er/or9
mance measures based on t&e simulation results) Suose t&at t&e inter9arri1al
time and t&e ser1ice time comly wit& t&e robability mass /unctions seci/ied in
Table 1)1) Table 1)2 s&ows t&e simulation results /or ten ackets)
In Table 1)2* t&e second and t&ird columns reresent t&e inter9arri1al time
and ser1ice time* resecti1ely* o/ eac& acket) T&ese two columns contain raw
in/ormation) .ata s&own in ot&er columns deri1e /rom t&ese two columns)
T&e /ourt& and /i/t& columns seci/y t&e time w&ere t&e ackets arri1e and start
to be ser1ed in t&e &ead9o/9t&e9line ser1er* resecti1ely) T&e siAt& column
reresents t&e acket waitin' time H t&e time t&at a acket sends in t&e Dueue) It
is comuted as t&e time di//erence between w&en t&e ser1ice starts and w&en t&e
acket arri1es) Cinally* t&e se1ent& column reresents t&e acket transmission
latency H t&e time
Tab#e %=* E1olution o/
number o/ ackets in t&e
system o1er time
E1ent Packet no) Simulation clock
4rri1al 1 ,
4rri1al 2 2
Comletion 1 3
4rri1al 3 8
4rri1al : 2
Comletion 2 #
Comletion 3 1,
Comletion : 11
4rri1al 3 13
Comletion 3 18
)umber of
Pac1ets in the
System
3
2
1
2 4 & 1! 12 14 1&
Simulation
time
4ig= %=7 Number o/ ackets in t&e system at 1arious instances
t&at a acket sends in bot& t&e Dueue and t&e c&annel) It is comuted as t&e
summation o/ t&e waitin' time and t&e ser1ice time)
+ased on t&e results in Table 1)2* we comute t&e a1era'e waitin' time and t&e
a1era'e acket transmission latency by a1era'in' t&e siAt& and se1ent& columns
?i)e)* addin' all t&e 1alues and di1idin' t&e result by 1,@) T&e results are t&ere/ore
1), and 3)3 time units*
resecti1ely)
+ased on t&e in/ormation in Table 1)2* we also s&ow a series o/ e1ents and t&e
dynamics o/ bu//er occuancy wit& resect to t&e Simulation Clock ?sim5clock@
in Table 1)3 and Ci') 1)"* resecti1ely) +ased on Ci' 1)"* t&e mean ser1er
utiliJation can be comuted /rom t&e ratio o/ t&e time w&en t&e ser1er is in use to
t&e simulation time* w&ic& is 1:$18 . ,)"23 in t&is case)
%=6 $ha&ter Summary
4 comuter network is a comleA system) .esi'n analysis* and otimiJation o/ a
comuter network can be a comre&ensi1e task) Simulation* re'arded as one o/
t&e most ower/ul er/ormance analysis tools* is usually used in carryin' out t&is
task to comlement t&e analytical tools)
2, 1 Simulation o/ Comuter Networks
T&is c&ater /ocuses mainly on time9deendent simulation* w&ic& ad1ances in a
time domain) T&e time9deendent simulation can be classi/ied into two cate'ories)
Time9dri1en simulation ad1ances t&e simulation by /iAed time inter1als* w&ile
e1ent9 dri1en simulation roceeds /rom one e1ent to anot&er) NS2 is an e1ent9
dri1en simulation tool) .esi'nin' e1ent9dri1en simulation models usin' NS2 is t&e
t&eme o/ t&e rest o/ t&e book)
%=5 "<ercises
1) 6&at are t&e di//erences between OSI model and TCP$IP model) .raw a
dia'ram to em&asiJe t&e di//erences)
2) 6&at are t&e key stes in simulatin' a comuter communication networkR
3) .raw a robability density /unction wit& con/idence inter1al M 2O C2N and
con/idence coe//icient is #3P)
:) ;ou are 'i1en a teAt /ile) Eac& line o/ t&is teAt /ile contains a number
reresentin' a data oint) 6rite a ro'ram w&ic& comutes t&e a1era'e 1alue
and t&e standard de1iation /or t&e data oints alon' wit& t&e con/idence le1el
w&en a con/idence inter1al is 'i1en as an inut arameter)
3) 6&at are t&e two tyes o/ time9deendent simulationsR 6rite down t&eir main
/eatures* stren't&s* and weaknesses)
8) 6rite a sub9routine w&ic& rints out t&e current time slot) In a time9slotted
system* write a ro'ram w&ic& eAecuted t&e sub9routine at time slot 1* 2* 13*
2:* and :2 by
a) 0sin' time9dri1en simulation
b) 0sin' e1ent9dri1en simulation
$ha&ter 2
'ntrouction to Network Simu#ator 2 (NS2)
2=% 'ntrouction
Network Simulator ?7ersion 2@* widely known as NS2* is simly an e1ent9dri1en
simulation tool t&at &as ro1ed use/ul in studyin' t&e dynamic nature o/ commu9
nication networks) Simulation o/ wired as well as wireless network /unctions and
rotocols ?e)')* routin' al'orit&ms* TCP* 0.P@ can be done usin' NS2) In 'eneral*
NS2 ro1ides users wit& a way o/ seci/yin' suc& network rotocols and
simulatin' t&eir corresondin' be&a1iors)
.ue to its /leAibility and modular nature* NS2 &as 'ained constant oularity
in t&e networkin' researc& community since its birt& in 1#"#) E1er since* se1eral
re1olutions and re1isions &a1e marked t&e 'rowin' maturity o/ t&e tool* t&anks
to substantial contributions /rom t&e layers in t&e /ield) 4mon' t&ese are t&e
0ni1ersity o/ Cali/ornia and Cornell 0ni1ersity w&o de1eloed t&e (E4! network
simulator*
1
t&e /oundation on w&ic& NS is in1ented) Since 1##3 t&e .e/ense
4d1anced (esearc& ProBects 4'ency ?.4(P4@ suorted t&e de1eloment o/ NS
t&rou'& t&e 7irtual InterNetwork Testbed ?7INT@ roBect M1,N)
2
Currently t&e
National Science Coundation ?NSC@ &as Boined t&e ride in de1eloment) !ast but
not t&e least* t&e 'rou o/ researc&ers and de1eloers in t&e community are
constantly workin' to kee NS2 stron' and 1ersatile)
4'ain* t&e main obBecti1e o/ t&is book is to ro1ide t&e readers wit& insi'&ts
into t&e NS2 arc&itecture) T&is c&ater 'i1es a brie/ introduction to NS2) NS2
+e'inners are recommended to 'o t&orou'& t&e detailed introductory online
resources) Cor eAamle* NS2 o//icial website M12N ro1ides NS2 source code as
well as detailed installation instruction) T&e web a'es in M13N and M1:N are amon'
&i'&ly recommended ones w&ic& ro1ide tutorial and eAamles /or settin' u
basic
1
(E4! was ori'inally imlemented as a tool /or studyin' t&e dynamic be&a1ior o/ /low and
con'estion control sc&emes in acket9switc&ed data networks)
2
Cunded by .4(P4* t&e 7INT roBect aimed at creatin' a network simulator t&at will initiate
t&e study o/ di//erent rotocols /or communication networkin')
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* 21
.OI 1,)1,,2$#2"919:81:91:,893 2* = Srin'er Science>+usiness %edia* !!C 2,12
22 2 Introduction to Network Simulator 2
NS2 simulation) 4 comre&ensi1e list o/ NS2 codes contributed by researc&ers
can be /ound in M13N) T&ese introductory online resources would be &el/ul in
understandin' t&e material resented in t&is book)
In t&is c&ater an introduction to NS2 is ro1ided) In articular* Sect) 2)2
resents t&e basic arc&itecture o/ NS2) T&e in/ormation on NS2 installation is
'i1en in Sect) 2)3) Section 2): s&ows NS2 directories and con1entions) Section 2)3
s&ows t&e main stes in NS2 simulation) 4 simle simulation eAamle is 'i1en in
Sect) 2)8) Section 2)2 describes &ow to include CCC modules in NS2) Cinally*
Sect) 2)" concludes t&e c&ater)
2=2 Basic Architecture
Ci'ure 2)1 s&ows t&e basic arc&itecture o/ NS2) NS2 ro1ides users wit& an
eAecutable command FnsG w&ic& takes one inut ar'ument* t&e name o/ a Tcl
simulation scritin' /ile) In most cases* a simulation trace /ile is created and is
used to lot 'ra& and$or to create animation)
NS2 consists o/ two key lan'ua'es< CCC and ObBect9oriented Tool Command
!an'ua'e ?OTcl@) 6&ile t&e CCC de/ines t&e internal mec&anism ?i)e)* a
backend@ o/ t&e simulation* t&e OTcl sets u simulation by assemblin' and
con/i'urin' t&e obBects as well as sc&edulin' discrete e1ents ?i)e)* a /rontend@)
T&e CCC and t&e OTcl are linked to'et&er usin' TclC!) %aed to a CCC
obBect* 1ariables in t&e OTcl domains are sometimes re/erred to as handles)
Concetually* a &andle is Bust a strin' ?e)')* F5o20G@ in t&e OTcl domain and
does not contain any /unctionality) Instead* t&e /unctionality ?e)')* recei1in' a
acket@ is de/ined in t&e maed CCC obBect ?e)')* o/ class Connector@) In t&e
OTcl domain* a &andle acts as a /rontend w&ic& interacts wit& users and ot&er
OTcl obBects) It may de/ine its own rocedures and 1ariables to /acilitate t&e
interaction) Note t&at t&e member rocedures and 1ariables in t&e OTcl domain are
called instance rocedures ?instrocs@ and instance 1ariables ?inst1ars@*
resecti1ely) +e/ore roceedin' /urt&er*
'cl
Simulation
Scri6t
Simulation
*b7ects
'cl0L
Simulation
*b7ects
Simulation
'race .ile
088 *'cl
)S2 Shell +xecutable 0ommand (ns)
),M
(,nimation)
#4ra6h
(Plottin4)
4ig= 2=% +asic arc&itecture o/ NS
2)3 Installation 23
t&e readers are encoura'ed to learn CCC and OTcl lan'ua'es) 6e re/er t&e
readers to M18N /or t&e detail o/ CCC* w&ile a brie/ tutorial o/ Tcl and OTcl
tutorial are 'i1en in 4endices 4)1 and 4)2* resecti1ely)
NS2 ro1ides a lar'e number o/ built9in CCC classes) It is ad1isable to use
t&ese CCC classes to set u a simulation 1ia a Tcl simulation scrit) Howe1er*
ad1ance users may /ind t&ese obBects insu//icient) T&ey need to de1elo t&eir
own CCC classes and use a OTcl con/i'uration inter/ace to ut to'et&er obBects
instantiated /rom t&ese class)
4/ter simulation* NS2 oututs eit&er teAt9based simulation results) To interret
t&ese results 'ra&ically and interacti1ely* tools suc& as N4% ?Network
4ni%ator@ and ELra& are used) To analyJe a articular be&a1ior o/ t&e network*
users can eAtract a rele1ant subset o/ teAt9based data and trans/orm it to a more
concei1able resentation)
2=* 'nsta##ation
NS2 is a /ree simulation tool* w&ic& can be obtained /rom M1,N) It runs on 1arious
lat/orms includin' 0NIE ?or !inuA@* 6indows* and %ac systems) +ein'
de1eloed in t&e 0niA en1ironment* wit& no surrise* NS2 &as t&e smoot&est ride
t&ere* and so does its installation) Howe1er* due to t&e oularity o/ windows
systems* t&e discussion in t&is book is based on a Cy'win ?0NIE emulator@
acti1ated 6indows system)
NS2 source codes are distributed in two /orms< t&e all9in9one suite and t&e
comonent9wise) 6it& t&e all9in9one acka'e* users 'et all t&e reDuired como9
nents alon' wit& some otional comonents) T&is is basically a recommended
c&oice /or t&e be'inners) T&is acka'e ro1ides an FinstallG scrit w&ic&
con/i'ures t&e NS2 en1ironment and creates NS2 eAecutable /ile usin' t&e
FmakeG utility)
T&e current all9in9one suite consists o/ t&e /ollowin' main comonents<
NS release 2)33*
Tcl$Tk release ")3)"*
OTcl release 1)1:* and
TclC! release 1)2,)
and t&e /ollowin' are t&e otional comonents<
N4% release 1)13< N4% is an animation tool /or 1iewin' network simulation
traces and acket traces)
Slib 1ersion 1)2)3< T&is is t&e reDuired library /or
N4%)
E'ra& 1ersion 12)2< T&is is a data lotter wit& interacti1e buttons /or annin'*
Joomin'* rintin'* and selectin' dislay otions)
2: 2 Introduction to Network Simulator 2
Tab#e 2=% 4dditional Cy'win acka'es reDuired to run NS2
Cate'ory Packa'es
%andatory $cc=* $ccJ$44* $a,k* $6ip* tar* make* patc(* perl*
,31api
Otinal ?'ra&ic9related@ *or$J*server* *init* libL22Jdevel* libLm!Jdevel
T&e idea o/ t&e comonent9wise aroac& is to obtain t&e abo1e ieces and
install t&em indi1idually) T&is otion sa1e considerable amount o/ downloadin'
time and memory sace) Howe1er* it could be troublesome /or t&e be'inners and
is t&ere/ore recommended only /or eAerienced users)
2.".1 Installing an All(In(One %S2 S!ite on 0ni1(2ased Systes
T&e all9in9one suite can be installed in t&e 0niA9based mac&ines by simly
runnin' t&e FinstallG scrit and /ollowin' t&e instructions t&erein) T&e only
reDuirement is a comuter wit& a CCC comiler installed) T&e /ollowin' two
commands s&ow &ow t&e all9in9one NS2 suite can be installed and 1alidated*
resecti1ely<
KKIMinstall
KKIMvalidate
7alidatin' NS2 in1ol1es simly runnin' a number o/ workin' scrits t&at 1eri/y
t&e essential /unctionalities o/ t&e installed comonents)
2.".2 Installing an All(In(One %S2 S!ite on 3indo&s(2ased
Systes
To run NS2 on 6indows9based oeratin' systems* a bit o/ tweakin' is reDuired)
+asically* t&e idea is to make 6indows9based mac&ines emulate t&e /unctionality
o/ t&e 0niA9like en1ironment) 4 oular ro'ram t&at er/orms t&is Bob is
Cy'win)
3
4/ter 'ettin' Cy'win to work* t&e same rocedure as t&at o/ 0niA9based
installation can be /ollowed) Cor ease o/ installation* it is recommended t&at t&e
all9in9one acka'e be used) T&e detailed descrition o/ 6indows9based
installation can be /ound online at NS25s 6iki site M1,N* w&ere t&e in/ormation
on ost9installation troubles can also be /ound)
Note t&at by de/ault Cy'win does not install all acka'es necessary to run NS2)
4 user needs to manually install t&e addition acka'es s&own in Table 2)1)
:
3
Cy'win is a1ailable online and comes /ree) In/ormation suc& as &ow to obtain and install
Cy'win is a1ailable online at t&e Cy'win website ww w ) c y'w i n ) c om)
:
.i//erent 1ersions may install di//erent de/ault acka'es) 0sers may need to install more or less
acka'es deendin' on t&e 1ersion o/ Cy'win)
2): .irectories and Con1ention 23
2=/ -irectories an $onvention
2.$.1 )irectories
Suose t&at NS2 is installed in .irectory nsallinoneJ1I3>) Ci'ure 2)2
s&ows t&e directory structure under directory nsallinoneJ1I3>) Here* t&e
directory nsallinoneJ1I3>is on t&e !e1el 1) On t&e !e1el 2* t&e directory
tclclJ2I10 contains classes in TclC! ?e)')* Tcl) TclObject)
TclClass@) 4ll NS2 simulation modules are in t&e directory nsJ1I3> on
t&e !e1el 2) Herea/ter* we will re/er to directories nsJ1I3> and tclclJ
2I10as Tns$ and Ttclcl$* resecti1ely)
On !e1el 3* t&e modules in t&e interreted &ierarc&y are under t&e directory
tcl) 4mon' t&ese modules* t&e /reDuently used ones ?e)')* nsJlibItcl)
nsJnodeItcl) nsJlinkItcl@ are stored under t&e directory lib on !e1el
:) Simulation modules in t&e comiled &ierarc&y are classi/ied in directories
on !e1el 3) Cor eAamle* directory tools contain 1arious &eler classes suc&
as random 1ariable 'enerators) .irectory common contains basic modules related
to acket /orwardin' suc& as t&e simulator* t&e sc&eduler* connector* acket)
.irec9 tories +!e!e* tcp* and trace contain modules /or Dueue* TCP
?Transmission Control Protocol@* and tracin'* resecti1ely)
2.$.2 Con#ention
T&e terminolo'ies and /ormats t&at are used in NS2 and in t&is book &erea/ter are
s&own below<
2=/=2=% Termino#ogy
4n NS2 simulation scrit ?e)')* my"irst5nsItcl@ is re/erred to as a Tcl
simulation script)
L+9+L 1
,ll )S2
modules
nsallinone$2:3%
::: 'cl0L
classes
L+9+L 2 ns$2:3% tcl:%: tclcl$1:2!
:::
L+9+L 3
common tools tc6 3ueue trace tcl
:::
Modules in
the
inter6reted
hierarchy
L+9+L 4 0ommonly$used
modules in the
inter6reted hierarchy
lib rt4lib
4ig= 2=2 .irectory structure o/ NS2 M1:N
28 2 Introduction to Network Simulator 2
CCC and OTcl class &ierarc&ies* w&ic& &a1e one9to9one corresondence* are
re/erred to as the compiled hierarchy and the interpreted hierarchy*
resecti1ely) Class ?or member@ 1ariables and class ?or member@ /unctions are
t&e 1ariables and /unctions w&ic& belon' to a class) In t&e comiled &ierarc&y*
t&ey are re/erred to simly as 1ariables and /unctions* resecti1ely) T&ose
in t&e interreted &ierarc&y are re/erred to as instance varia'les ?instvars@ and
instance procedures ?instprocs@* resecti1ely) 4s we will see in Sect) 3):* (Tcl
command* is a secial instance rocedure* w&ose imlementation is in t&e
comiled &ierarc&y ?i)e)* written in CCC@) 4n OTcl obBect is* t&ere/ore*
associated wit& instance 1ariables* instance rocedures* and OTcl commands*
w&ile a CCC obBect is associated wit& 1ariables and /unctions)
4 F%yClassG obBect is a s&ort&and /or an obBect o/ class %yClass)
4 F%yClassG ointer is a s&ort&and /or a ointer w&ic& oints to an obBect
o/ class %yClass) Cor eAamle* based on t&e statements F!e!e +G and
FPacket
N
p*G F+G and FpG are said to be a F!e!eG obBect and a FPacket
ointer*G resecti1ely) 4lso* suose /urt&er t&at class DerivedClass
and Anot(erClass deri1e /rom class %yClass) T&en* t&e term a
%yClass obBect re/ers to any obBect w&ic& is instantiated /rom class
%yClass or its
deri1ed classes ?i)e)* DerivedClass or
Anot(erClass@)
('3ects and instances are instantiated /rom a CCC class and an OTcl class*
resecti1ely) Howe1er* t&e book uses t&ese two terms
interc&an'eably)
NS2 consists o/ two lan'ua'es) Suose t&at obBects FAG and F.G are written in
eac& lan'ua'e and corresond to one anot&er) T&en* FAG is said to be the
shadow o'3ect o/ F.)G Similarly F.G is said to be the shadow o'3ect o/ FA)G
Consider two consecuti1e nodes in Ci') 3)2) In t&is con/i'uration* an obBect ?i)e)*
node@ on t&e le/t always sends ackets to t&e obBect on t&e ri'&t) T&e obBect on
t&e ri'&t is re/erred to as a downstream o'3ect or a target* w&ile t&e obBect on
t&e le/t is re/erred to as an upstream o'3ect) In a 'eneral case* an obBect can
&a1e more t&an one tar'et) 4 acket must be /orwarded to one o/ t&ose
tar'ets) Crom t&e ersecti1e o/ an ustream obBect* a downstream obBect t&at
recei1es t&e acket is also re/erred to as a forwarding o'3ect)
2=/=2=2 Notations
4s in CCC* we use F99G to indicate t&e scoe o/ /unctions and instrocs ?e)')*
TcpA$ent99send&III'@)
%ost o/ t&e teAts in t&is book are written in re'ular letters) NS2 codes are written
in Ft(is "ont type)G T&e Duotation marks are omitted i/ it is clear /rom
t&e conteAt) Cor eAamle* t&e Simulator is a 'eneral term /or t&e simulatin'
module in NS2* w&ile a Sim!lator obBect is an obBect o/ class Sim!lator)
4 1alue contained in a 1ariable is embraced wit& <K) Cor eAamle* i/ a 1ariable
var stores an inte'er B* <varK will be
B)
4 command romt or an NS2 romt is denoted by FKKG at t&e be'innin' o/ a
line)
2)3 (unnin' NS2 Simulation 22
Tab#e 2=2 EAamles o/ NS2 namin' con1ention
T&e interreted &ierarc&y T&e comiled &ierarc&y
+ase class A$ent A$ent
.eri1ed class A$entMTCP TcpA$ent
.eri1ed class ?2nd le1el@ A$entMTcpM#eno #enoTcpA$ent
Class /unctions installNe*t install5ne*t
Class 1ariables ,indo,Option5 ,nd5option5
In t&is book* codes s&own in /i'ures are partially eAcerted /rom NS2 /ile)
T&e /ile name /rom w&ic& t&e codes is eAcerted is s&own in t&e /irst line
o/ t&e /i'ure) Cor eAamle* t&e codes in Pro'ram 2)1 are eAcerted /rom /ile
Fmy"irst5nsItcl)G
4 class name may consist o/ se1eral words) 4ll t&e words in a class name are
caitaliJed) In t&e interreted &ierarc&y* a deri1ed class is named by &a1in' t&e
name o/ its arent class /ollowin' by a slas& c&aracter ?FMG@ as a re/iA* w&ile
t&at comiled classes are named by &a1in' t&e name o/ its base class as a su//iA)
EAamles o/ NS2 namin' con1ention are 'i1en in Table 2)2)
In t&e interreted &ierarc&y* an instroc name is written in lower case) I/ t&e
instroc name consists o/ more t&an one word* eac& word eAcet /or t&e /irst
one will be caitaliJed) In t&e comiled &ierarc&y* all t&e words are written in
lower case and searated by an underscore F5G ?see Table 2)2@)
T&e namin' con1ention /or 1ariables is similar to t&at /or /unctions and
instrocs)
Howe1er* t&e last c&aracter o/ t&e names o/ class 1ariables in bot& t&e
&ierarc&ies is always an underscore ?F5GO see Table 2)2@) Note t&at t&is
con1ention is only a 'uideline t&at a ro'rammer s&ould ?but does not have to@
/ollow)
2=0 Running NS2 Simu#ation
2.+.1 %S2 Progra In#ocation
4/ter t&e installation and$or recomilation ?see Sect) 2)2@* an eAecutable /ile FnsG
is created in t&e NS2 &ome directory) NS2 can be in1oked by eAecutin' t&e
/ollowin' statement /rom t&e s&ell en1ironment<
KKns ?<"ileK@ ?<ar$sK@
w&ere <"ileK and <ar$sK are otional inut ar'ument) I/ no ar'ument is
'i1en* t&e command will brin' u an NS2 en1ironment* w&ere NS2 waits to
interret commands /rom t&e standard inut ?i)e)* keyboard@ line9by9line) I/ t&e
/irst inut ar'ument <"ileK is 'i1en* NS2 will interret t&e inut scritin'
<"ileK ?i)e)* a so9called Tcl simulation scrit@ accordin' to t&e Tcl syntaA) T&e
detail /or writin' a Tcl scritin' /ile is 'i1en in 4endiA 4)1) Cinally* t&e inut
ar'uments <ar$sK*
2" 2 Introduction to Network Simulator 2
General Simulation Steps NS2 Simulation Steps
1: Plannin4
2: /m6lementation;
/nitiali<ation
=esult 4eneration
Performance
measure
com6utation
1: Simulation Desi4n
2: 0onfi4urin4 and =unnin4
Simulation;
)et>or1 confi4uration
6hase
Simulation 6hase
3: Post Simulation Processin4
3: 'estin4 and Debu4in4
4ig= 2=* 4 comarison o/ 'eneral simulation stes and NS2 simulation stes
eac& searated by a w&ite sace* are /ed to t&e Tcl /ile <"ileK) Crom wit&in t&e
/ile <"ileK* t&e inut ar'ument is stored in t&e built9in 1ariable Far$vG ?see
4endiA 4)1)1@)
2.+.2 Main %S2 Si!lation Steps
Section 1)3 resents t&e key stes /or 'eneral simulation) 4s s&own in Ci') 2)3* t&e
'eneral simulation stes can be tailored to /it wit& t&e NS2 /ramework) T&e key
NS2 simulation stes include t&e /ollowin'<
Ste& %2 Simu#ation -esign
T&e /irst ste in simulatin' a network is to desi'n t&e simulation) In t&is ste* t&e
users s&ould determine t&e simulation uroses* network con/i'uration* assum9
tions* t&e er/ormance measures* and t&e tye o/ eAected results)
Ste& 22 $onfiguring an Running Simu#ation
T&is ste imlements t&e desi'n in t&e /irst ste) It consists o/ two
&ases<
Network configuration phase< In t&is &ase* network comonents ?e)')* node*
TCP and 0.P@ are created and con/i'ured accordin' to t&e simulation desi'n)
4lso* t&e e1ents suc& as data trans/er are sc&eduled to start at a certain
time)
Simulation Phase< T&is &ase starts t&e simulation w&ic& was con/i'ured in t&e
Network Con/i'uration P&ase) It maintains t&e simulation clock and eAecutes
e1ents c&ronolo'ically) T&is &ase usually runs until t&e simulation clock
reac&es a t&res&old 1alue seci/ied in t&e Network Con/i'uration P&ase)
In most cases* it is con1enient to de/ine a simulation scenario in a Tcl scritin'
/ile ?e)')* <"ileK@ and /eed t&e /ile as an inut ar'ument o/ an NS2 in1ocation
?e)')* eAecutin' Fns <"ileKG@)
Ste& *2 Postsimu#ation Processing
T&e main tasks in t&is stes include 1eri/yin' t&e inte'rity o/ t&e ro'ram and
e1aluatin' t&e er/ormance o/ t&e simulated network) 6&ile t&e /irst task is
re/erred to as de'ugging* t&e second one is ac&ie1ed by roerly collectin' and
comilin' simulation results ?see C&a) 1:@)
2=6 A Simu#ation "<am&#e
6e demonstrate a network simulation t&rou'& a simle eAamle) 4'ain* a simula9
tion rocess consists o/ t&ree stes)
Ste& %2 Simu#ation -esign
Ci'ure 2): s&ows t&e con/i'uration o/ a network under consideration) T&e network
consists o/ /i1e nodes Fn0G to Fn=)G In t&is scenario* node Fn0G sends constant9
bit9 rate ?C+(@ tra//ic to node Fn3*G and node Fn2G trans/ers data to node Fn=G
usin' a /ile trans/er rotocol ?CTP@) T&ese two carried tra//ic sources are carried by
transort layer rotocols 0ser .ata'ram Protocol ?0.P@ and Transmission
Control Protocol ?TCP@* resecti1ely) In NS2* t&e transmittin' obBect o/ t&ese two
rotocols are a 0.P a'ent and a TCP a'ent* w&ile t&e recei1ers are a Null a'ent
and a TCP sink a'ent* resecti1ely)
3, 2 Introduction to Network Simulator 2
0-=
node
'rans6ort a4ent
?DP ,4ent 1!! Mb6s
n!
% ms Delay
n2
%4 Mb6s
1! ms Delay
'0PSin1
n4
,66lication
?DP .lo>
'0P ,4ent
1!! Mb6s
% ms Delay
n1
%4 Mb6s
1! ms Delay
1! Mb6s
1% ms Delay
n3
'0P .lo>
.'P
)ull,4ent
4ig= 2=/ 4 samle network toolo'y
Ste& 22 $onfiguring an Running Simu#ation
Pro'rams 2)1 and 2)2 s&ow two ortions o/ a Tcl simulation scrit w&ic&
imlements t&e scenario in Ci') 2):)
Consider Pro'ram 2)1) T&is ro'ram creates a simulator instance in !ine 1) It
creates a trace /ile and a N4% trace /ile in !ines 2H3 and :H3* resecti1ely) It
de/ines rocedure "inis(/' in !ines 8H13) Cinally* it creates nodes and links
t&em to'et&er in !ines 1:H1" and 1#H2:* resecti1ely)
T&e Simulator is created in !ine 1 by eAecutin' Fne, Sim!lator)G T&e
returned Sim!lator &andle is stored in a 1ariable Fns)G !ines 2 and : oen
/iles Fo!tItrG and Fo!tInam*G resecti1ely* /or writin') T&e 1ariables
FmyTraceG and FmyNA%G are t&e /ile &andles /or t&ese two /iles* resecti1ely)
!ines 3 and 3 in/orm NS2 to collect all trace in/ormation /or a re'ular trace and
a N4% trace* resecti1ely)
T&e rocedure "inis(/' will be in1oked immediately be/ore t&e simulation
terminates) T&e keyword $lobal in/orms t&e Tcl interreter t&at t&e 1ariables
Fns*G FmyTrace*G FmyNA%G are t&ose de/ined in t&e 'lobal scoe ?i)e)* de/ined
outside t&e rocedure@) !ine " /lus&es t&e bu//er o/ t&e acket tracin' 1ariables)
!ines # and 1, close t&e /iles associated wit& &andles FmyTraceG and FmyNA%)G
!ine 11 eAecutes t&e statement Fnam o!tInam FG /rom t&e s&ell en1ironment*
w&ere FnamG is an eAecutable /ile w&ic& in1oke t&e Network 4ni%ator) Cinally*
!ine 12 tells NS2 to eAit wit& code ,)
!ines 1:H1" create Nodes usin' t&e instroc node/III' o/ t&e Simulator
w&ose &andle is Fns)G !ines 1#H23 connect eac& air o/ nodes wit& a bi9
directional link usin' an instroc d!ple*Jlink /src dst b, delay
+type' o/ class Sim!lator* w&ere FsrcG is a be'innin' node* FdstG is a
terminatin' node* Fb,G is t&e link bandwidt&* FdelayG is t&e link roa'ation
delay* and F+typeG is t&e tye o/ t&e Dueues between t&e node FsrcG and t&e
node Fdst)G Similar to
Program 2=% Cirst NS2 Pro'ram
O my"irst5nsItcl
O Create a Sim!lator
2 set ns ?ne, Sim!lator@
O Create a trace "ile
1 set mytrace ?open o!tItr ,@
3 Pns traceJall Pmytrace
O Create a NA% trace "ile
= set myNA% ?open o!tInam ,@
> Pns namtraceJall PmyNA%
O De"ine a proced!re "inis(
A proc "inis( 7 8 7
B $lobal ns mytrace myNA%
/ Pns "l!s(Jtrace
G close Pmytrace
20 close PmyNA%
22 e*ec nam o!tInam F
21 e*it 0
23 8
O Create Nodes
2= set n0 ?Pns node@
2> set n2 ?Pns node@
2A set n1 ?Pns node@
2B set n3 ?Pns node@
2/ set n= ?Pns node@
O Connect Nodes ,it( Links
2G Pns d!ple*Jlink Pn0 Pn1 200%b >ms DropTail
10 Pns d!ple*Jlink Pn2 Pn1 200%b >ms DropTail
12 Pns d!ple*Jlink Pn1 Pn= >=%b 20ms DropTail
11 Pns d!ple*Jlink Pn1 Pn3 >=%b 20ms DropTail
13 Pns simple*Jlink Pn3 Pn= 20%b 2>ms DropTail
1= Pns +!e!eJlimit Pn1 Pn3 =0
t&e instroc d!ple*Jlink/III'* !ine 23 create a uni9directional link usin' an
instroc simple*Jlink/III' o/ class Sim!lator) Cinally* !ine 2: sets siJe
o/ t&e Dueue between node Fn1G and node Fn3G to be :, ackets)
NeAt* consider t&e second ortion o/ t&e Tcl simulation scrit in Pro'ram 2)2)
4 0.P connection* a C+( tra//ic source* a TCP connection* and an CTP session
are created and con/i'ured in !ines 23H3,* 31H3:* 33H:,* and :1H:2*
resecti1ely) !ines :3H:2 sc&edule discrete e1ents) Cinally* t&e simulator is
started in !ine :" usin' t&e instroc r!n/' associated wit& t&e simulator &andle
Fns)G
To create a 0.P connection* a sender F!dpG and a recei1er Fn!llG are created
in !ines 23 and 22* resecti1ely) Takin' a node and an a'ent as inut ar'ument*
an
instroc attac(Ja$ent/III' o/ class Sim!lator in !ine 28 attac&es a 0.P
32 2 Introduction to Network Simulator 2
Program 2=2 Cirst NS2 Pro'ram ?Continued@
O Create a DDP a$ent
1> set !dp ?ne, A$entMDDP@
1A Pns attac(Ja$ent Pn0 P!dp
1B set n!ll ?ne, A$entMN!ll@
1/ Pns attac(Ja$ent Pn3 Pn!ll
1G Pns connect P!dp Pn!ll
30 P!dp set "id5 2
O Create a C.# tra""ic so!rce
32 set cbr ?ne, ApplicationMTra""icMC.#@
31 Pcbr attac(Ja$ent P!dp
33 Pcbr set packetSi6e5 2000
3= Pcbr set rate5 1%b
O Create a TCP a$ent
3> set tcp ?ne, A$entMTCP@
3A Pns attac(Ja$ent Pn2 Ptcp
3B set sink ?ne, A$entMTCPSink@
3/ Pns attac(Ja$ent Pn= Psink
3G Pns connect Ptcp Psink
=0 Ptcp set "id5 1
O Create an QTP session
=2 set "tp ?ne, ApplicationMQTP@
=1 P"tp attac(Ja$ent Ptcp
O Sc(ed!le events
=3 Pns at 0I0> HP"tp startH
== Pns at 0I2 HPcbr startH
=> Pns at A0I0 HP"tp stopH
=A Pns at A0I> HPcbr stopH
=B Pns at A2 H"inis(H
O Start t(e sim!lation
=/ Pns r!n
a'ent F!dpG and a node Fn0G to'et&er) Similarly* !ine 2" attac&es a Null a'ent
Fn!llG to a node Fn3)G T&e instroc connect/<"rom5a$tK <to5a$tK' in
!ine 2# in/orms an a'ent <"rom5a$tK to send t&e 'enerated tra//ic to an a'ent
<to5a$tK) Cinally* !ine 3, sets t&e 0.P /low I. to be 1) T&e construction o/
a TCP connection in !ines 33H:, is similar to t&at o/ a 0.P connection in !ines
23H3,)
4 C+( tra//ic source is created in !ine 31) It is attac&ed to a 0.P a'ent F!dpG
in !ine 32) T&e acket siJe and 'eneration rate o/ t&e C+( connection are set to
1*,,, bytes and 2 %bs* resecti1ely) Similarly* an CTP session &andle is created
in
!ine :1 and is attac&ed to a TCP a'ent FtcpG in !ine :2)
In NS2* discrete e1ents can be sc&eduled usin' an instroc at/III' o/
class Sim!lator* w&ic& takes two inut ar'uments< <timeK and <strK)
2)8 4 Simulation EAamle 33
T&is instroc sc&edules an eAecution o/ <strK w&en t&e simulation time is
<timeK) !ines :3 and :: start t&e CTP and C+( tra//ic at ,),3t& second and 1st
second* resecti1ely) !ines :3 and :8 sto t&e CTP and C+( tra//ic at 8,),t&
second
and 8,)3t& second* resecti1ely) !ine :2 terminates t&e simulation by in1okin' t&e
rocedure "inis(/' at 81st second) Note t&at t&e CTP and C+( tra//ic source
can be started and stoed by in1okin' t&eir OTcl commands start/' and
stop/'* resecti1ely)
6e run t&e abo1e simulation scrit by eAecutin'
KKns my"irst5nsItcl
/rom t&e s&ell en1ironment) 4t t&e end o/ simulation* t&e trace /iles s&ould be
created and N4% s&ould be runnin' ?since it is in1oked /rom wit&in t&e rocedure
"inis(/'@)
Ste& *2 Post simu#ation Processing2 Packet
Tracing
Packet tracin' records t&e detail o/ acket /low durin' a simulation) It can be
classi/ied into a teAt9based acket tracin' and a N4% acket tracin')
TeAt9+ased Packet Tracin'
TeAt9based acket tracin' records t&e detail o/ ackets assin' t&rou'& network
c&eckoints ?e)')* nodes and Dueues@) 4 art o/ t&e teAt9based trace obtained by
runnin' t&e abo1e simulation ?my"irst5nsItcl@ is s&own below)
III
4 0I220=2G 2 1 tcp 20=0 JJJJJJJ 1 2I0 =I0 > 21
4 0I220=2G 2 1 tcp 20=0 JJJJJJJ 1 2I0 =I0 A 23
J 0I220=32 2 1 tcp 20=0 JJJJJJJ 1 2I0 =I0 > 21
J 0I220>2= 2 1 tcp 20=0 JJJJJJJ 1 2I0 =I0 A 23
r 0I2230/ 0 1 cbr 2000 JJJJJJJ 2 0I0 3I0 1 /
4 0I2230/ 1 3 cbr 2000 JJJJJJJ 2 0I0 3I0 1 /
J 0I2230/ 1 3 cbr 2000 JJJJJJJ 2 0I0 3I0 1 /
r 0I2232A 0 1 cbr 2000 JJJJJJJ 2 0I0 3I0 3 G
4 0I2232A 1 3 cbr 2000 JJJJJJJ 2 0I0 3I0 3 G
J 0I22311/ 1 3 cbr 2000 JJJJJJJ 2 0I0 3I0 3 G
r 0I22>11/ 1 3 cbr 2000 JJJJJJJ 2 0I0 3I0 0 A
r 0I22>3=/ 2 1 tcp 20=0 JJJJJJJ 1 2I0 =I0 3 20
4 0I22>3=/ 1 = tcp 20=0 JJJJJJJ 1 2I0 =I0 3 20
J 0I22>3=/ 1 = tcp 20=0 JJJJJJJ 1 2I0 =I0 3 20
r 0I22>3BA 1 3 cbr 2000 JJJJJJJ 2 0I0 3I0 2 B
r 0I22>=32 2 1 tcp 20=0 JJJJJJJ 1 2I0 =I0 = 22
III
3: 2 Introduction to Network Simulator 2
4ig= 2=0 Cormat o/ eac& line in a normal trace /ile
Ci'ure 2)3 an eAamle o/ a trace /ile) Eac& line in t&e trace /ile consists o/ 12
columns)
T&e 'eneral /ormat o/ eac& trace line is s&own in Ci') 2)3* w&ere 12 columns
make u a comlete trace line) T&e type identifier /ield corresonds to /our
ossible e1ent tyes t&at a acket &as eAerienced< FrG ?recei1ed@* FCG
?enDueued@* F G ?deDueued@* and FdG ?droed@) T&e time /ield denotes t&e time at
w&ic& suc& e1ent occurs) Cields 3 and : are t&e startin' and t&e terminatin' nodes*
resecti1ely* o/ t&e link at w&ic& a certain e1ent takes lace) Cields 3 and 8 are
acket tye and acket siJe* resecti1ely) T&e neAt /ield is a series o/ /la's*
indicatin' any abnormal be&a19 ior) Note t&e outut HJJJJJJJH denotes no
/la') Collowin' t&e /la's is a acket /low I.) Cields # and 1, mark t&e source and
t&e destination addresses* resecti1ely* in t&e /orm o/ FnodeIport)G Cor correct
acket assembly at t&e destination node* NS also seci/ies a acket seDuence
number in t&e second last /ield) Cinally* to kee track o/ all ackets* a acket
uniDue I. is recorded in t&e last /ield)
Now* &a1in' t&is trace at &and would not be use/ul unless meanin'/ul analysis
is er/ormed on t&e data) In ost simulation analysis* one usually eAtracts a subset
o/ t&e data o/ interest and /urt&er analyJes it) Cor eAamle* t&e a1era'e t&rou'&ut
associated wit& a seci/ic link can be comuted by eAtractin' only t&e columns
and /ields associated wit& t&at link /rom t&e trace /ile) Two o/ t&e most oular
lan'ua'es t&at /acilitate t&is rocess are 46K and Perl) T&e basic structures and
usa'e o/ 46K is described in 4endiA 4)3)
TeAt9based acket tracin' is acti1ated by eAecutin' FPns traceJall
P"ile*G w&ere FnsG stores t&e Simulator &andle and F"ileG stores a &andle
associated wit& t&e /ile w&ic& records t&e tracin' strin's) T&is statement simly
in/orms NS2 o/ t&e need to trace ackets) 6&en an obBect is created* a tracin'
obBect is also created to collect t&e detail o/ tra1ersin' ackets) Hence* t&e
FtraceJallG statement must be eAecuted be/ore obBect creation) 6e s&all discuss
t&e detail o/ teAt9based acket tracin' later in C&a) 1:)
Network AniMation (NAM)
Trace
N4% trace records simulation detail in a teAt /ile and uses t&e teAt /ile to lay back
t&e simulation usin' animation) N4% trace is acti1ated by t&e command FPns
namtraceJall P"ile*G w&ere FnsG is t&e Simulator &andle and F"ileG is
a &andle associated wit& t&e /ile ?e)')* Fo!tInamG in t&e abo1e eAamle@ w&ic&
stores t&e N4% trace in/ormation) 4/ter obtainin' a N4% trace /ile* t&e animation
can be initiated directly at t&e command romt t&rou'& t&e /ollowin' command
?See !ine 11 in Pro'ram 2)1@<
KKnam "ilenameInam
2)2 Includin' C>> %odules into NS2 and t&e make
0tility
33
%any 1isualiJation /eatures are a1ailable in N4%) T&ese /eatures are /or eA9
amle animatin' colored acket /lows* dra''in' and droin' nodes ?ositionin'@*
labelin' nodes at a seci/ied instant* s&ain' t&e nodes* colorin' a seci/ic link*
and monitorin' a Dueue)
2=5 'nc#uing $CC Mou#es into NS2 an the make
9ti#ity
In de1eloin' an NS2 simulation* 1ery o/ten it is necessary to create customiJed
CCC modules to comlement t&e eAistin' libraries) 4s suc&* t&e de1eloer is
/aced wit& t&e task o/ keein' track o/ all t&e created /iles as a art o/ NS2) 6&en
a c&an'e is made to one /ile* usually it reDuires recomilation o/ some ot&er /iles
t&at deend on it) %anual recomilation o/ eac& o/ suc& /iles may not be
ractical) In 0niA* a utility tool called make is a1ailable to o1ercome suc&
di//iculties) In t&is section we introduce t&is tool and discuss &ow to use it in t&e
conteAt o/ NS2 simulation de1eloment)
4s a 0niA utility tool make is 1ery use/ul /or mana'in' t&e de1eloment
o/ so/tware written in any comilable ro'rammin' lan'ua'e includin' CCC)
Lenerally* t&e make ro'ram automatically kees track o/ all t&e /iles created
t&rou'&out t&e de1eloment rocess) +y keeping track* we mean recomilin' or
relinkin' w&ere1er interdeendencies eAist amon' t&ese /iles* w&ic& may &a1e
been modi/ied as a art o/ t&e de1eloment rocess)
2.4.1 An In#ocation of a make
0tility
4 FmakeG utility can be in1oked /orm a 0NIE s&ell wit& t&e /ollowin'
command<
KKmake ?J" mydescriptor@
w&ere FmakeG is mandatory* w&ile t&e teAt inside t&e bracket is otional) +y
de/ault ?i)e)* wit&out otional inut ar'uments@* t&e FmakeG utility recomiles and
relinks t&e source codes accordin' to t&e de/ault descritor /ile F%ake"ile)G
I/ t&e descritor /ile FmydescriptorG is seci/ied* t&e utility uses t&is /ile in
lace o/ t&e de/ault /ile F%ake"ile)G
2.4.2 A make )escriptor
5ile
4 descritor /ile contains instructions o/ &ow t&e source codes s&ould be
recomiled and relinked) 4'ain* t&e de/ault descritor /ile is t&e /ile named
F%ake"ile)G 4 de9 scritor /ile contains t&e names o/ t&e source code /iles t&at
make u t&e eAecutable*
38 2 Introduction to Network Simulator 2
t&eir interdeendencies* and &ow eac& /ile s&ould be rebuilt or recomiled) Suc&
descritions are seci/ied t&rou'& a series o/ so9called deendency rules) Eac&
rule takes t&ree comonents* i)e)* tar'ets* deendencies* and commands) T&e
/ollowin' is t&e /ormat o/ t&e deendency rule<
<tar$et2K ?<tar$et1K III@ 9 <dep2K ?<dep1K III@
<command2K ?<command1K III@
w&ere e1eryt&in' inside t&e brackets are otional) 4 tar'et is usually t&e name o/
t&e /ile w&ic& needs to be remade i/ any modi/ication is done to deendency /iles
seci/ied a/ter t&e mandatory colon ?9@) I/ any c&an'e is noticed* t&e second and
subseDuent lines will be e%ecuted to re'enerate t&e tar'et /ile)
E%ample 2* -E%ample of a 4escriptor &ile0* 4ssume t&at we &a1e a main eAe9
cutable /ile c(annel consistin' o/ t&ree searate source /iles named mainIc*
"adeIc* and modelIc) 4lso assume t&at modelIc deends on modelI()
T&e %ake"ile corresondin' to t&is eAamle is s&own below)
O make"ile o" c(annel
c(annel 9 mainIo "adeIo modelIo
cc Jo c(annel mainIo "adeIo modelIo
mainIo 9 mainIc
cc Jc mainIc
"adeIo 9 "adeIc
cc Jc "adeIc
modelIo 9 modelIc modelI(
cc Jc modelIc
clean 9
rm mainIo "adeIo modelIo
T&e /irst line is a comment be'innin' wit& a ound ?FOG@ si'n) 6&en make
is in1oked* it starts c&eckin' t&e tar'ets one by one) T&e tar'et c(annel is
eAamined /irst* and make /inds t&at c(annel deends on t&e obBect /iles
mainIo* "adeIo* and modelIo) T&e make utility neAt c&ecks to see i/
any o/ t&ese obBect /iles is desi'nated as a tar'et /ile) I/ t&is is t&e case* make
/urt&er c&ecks t&e mainIo obBect /ile5s deendency and /inds t&at it
deends on mainIc) 4'ain* make roceeds to c&eck w&et&er mainIc is
listed as a tar'et) I/ not* t&e command under t&e mainIo tar'et is eAecuted
i/ any c&an'e is made to mainIc) In t&e command line Fcc Jc mainIc*G
3
mainIc is simly comiled
3
T&e 0NIE command Fcc Jc "ileIcG comiles t&e /ile F"ileIcG and creates an obBect /ile
F"ileIo*G w&ile t&e command Fcc Jo "ileIoG links t&e obBect /ile F"ileIoG and create
an eAecutable /ile F"ile)G
2)2 Includin' C>> %odules into NS2 and t&e make
0tility
32
to obtain t&e mainIo obBect) NeAt* make roceeds in a similar manner wit&
t&e "adeIo and modelIo tar'ets) Once any o/ t&ese obBect /iles is
udated* make returns to t&e c(annel tar'et and eAecutes its command*
w&ic& merely comiles all o/ its deendent obBects) Cinally* we note a secial
tar'et known as a phony target w&ic& is not really t&e name o/ any /ile in t&e
deendency &ierarc&y) T&is tar'et is FcleanG and usually er/orms a
&ousekeein' /unction suc& as cleanin' u all t&e obBect /iles no lon'er needed
a/ter t&e comilation and linkin')
In EAamle 2)1* we notice se1eral occurrences o/ certain seDuences suc& as
mainIo "adeIo modelIo) To a1oid a reetiti1e tyin'* w&ic& may introduce
tyos or omissions* a macro can be de/ined to reresent suc& a lon' seDuence) Cor
eAamle* we may de/ine a macro to reresent mainIo "adeIo modelIo as
/ollows<
O.RS : mainIo "adeIo modelIo
4/ter de/inin' t&e macro* we re/er to FmainIo "adeIo modelIoG by eit&er
arent&eses or curly brackets and recede t&at wit& a dollar si'n ?e)')* P&O.RS'
or PO.RS@) 6it& t&is macro* EAamle 2)1 becomes a bit more &andy as s&own in
EAamle 2)2)
E%ample 2*2 -E%ample of 5akefile with 5acros*0* T&e EAamle 2)1 can be modi9
/ied by de/inin' macros as /ollows<
O make"ile o" c(annel
O.RS : mainIo "adeIo modelIo
CO% : cc
c(annel 9 P7O.RS8
P7CO%8 Jo c(annel P7O.RS8
mainIo 9 mainIc
P7CO%8 Jc mainIc
"adeIo 9 "adeIc
P7CO%8 Jc "adeIc
modelIo 9 modelIc modelI(
P7CO%8 Jc modelIc
clean 9
rm P7O.RS8
w&ere P/CO%' and P/O.RS' are used in t&e lace o/ FccG and Fmain)o /ade)o
model)o*G resecti1ely)
3" 2 Introduction to Network Simulator 2
2.4." %S2 )escriptor 5ile
T&e NS2 descritor /ile is de/ined in t&e /ile F%ake"ileG located in t&e &ome
directory o/ NS2) It contains details needed to recomile and relink NS2) T&e key
rele1ant details are t&ose be'innin' wit& t&e /ollowin' keywords)
INCLDDES : < T&e items be&ind t&is keyword are t&e directory w&ic&
s&ould be included into t&e NS2 en1ironment)
O.R5CC : and O.R5STL : < T&e items be&ind t&ese two keywords
constitute t&e entire NS2 obBect /iles) 6&en a new CCC module is
de1eloed* its corresondin' obBect /ile name wit& FIoG eAtension s&ould be
added &ere)
NS5TCL5LI. : < T&e items t&at bind t&ese keywords are t&e Tcl /ile o/
NS2)
4'ain* w&en a new OTcl module is de1eloed* its corresondin' Tcl /ile name
s&ould be added &ere)
Suose a module consistin' o/ CCC /iles FmycIccG and FmycI(G and a
Tcl /ile FmytclItcl)G Suose /urt&er t&at t&ese /iles are created in a directory
my"iles under t&e NS2 &ome directory) T&en t&is module can be
incororated into NS2 usin' t&e /ollowin' stes<
1) Include a strin' FJIIMmy"ilesG into t&e !ine be'innin' wit& INCLDDES :
in t&e F%ake"ile)G
2) Include a strin' Fmy"ileMmycIoG into t&e !ine be'innin' wit& O.R5CC :
or O.R5STL : in t&e F%ake"ile)G
3) Include a strin' Fmy"ileMmytclItclG into t&e !ine be'innin' wit&
NS5TCL5LI. : in t&e F%ake"ile)G
:) (un FmakeG /rom t&e s&ell)
4/ter runnin' Fmake*G an eAecutable /ile FnsG is created) 6e can now use t&is
/ile FnsG to run simulation)
2=7 $ha&ter Summary
T&is c&ater introduces Network Simulator ?7ersion 2@* NS2) In articular* in/or9
mation on t&e installation o/ NS2 in bot& 0niA and 6indows9based systems is
ro1ided) T&e basic arc&itecture o/ NS2 is described) T&ese materials are essential
/or understandin' NS2 as a w&ole and would &el to 'et one started workin' wit&
NS2)
NS2 consists o/ OTcl and CCC) T&e CCC obBects are maed to OTcl &andles
usin' TclCl) To run a simulation* a user needs to de/ine a network scenario in a
Tcl Simulation scrit and /eeds t&is scrit as an inut to an eAecutable /ile Fns)G
.urin' t&e simulation* t&e acket /low in/ormation can be collected t&rou'& teAt9
based tracin' or N4% tracin') 4/ter t&e simulation* an 46K ro'ram or a erl
ro'ram can be used to analyJe a teAt9based trace /ile) T&e N4% ro'ram* on t&e
ot&er &and* uses a N4% trace /ile to relay t&e network simulation usin'
animation)
2)# EAercises 3#
Simulation usin' NS2 consists o/ t&ree main stes) Cirst* t&e simulation desi'n
is robably t&e most imortant ste) Here* we need to clearly seci/y t&e
obBecti1es and assumtions o/ t&e simulation) Second* con/i'urin' and runnin'
simulation imlement t&e concet desi'ned in t&e /irst ste) T&is ste also includes
con/i'urin' t&e simulation scenario and runnin' simulation) T&e /inal ste in a
simulation is to collect t&e simulation result and trace t&e simulation i/ necessary)
6ritten mainly in CCC* NS2 uses a FmakeG utility to comile t&e source
code* to link t&e created obBect /iles* and create an eAecutable /ile Fns)G It /ollows
t&e instruction seci/ied in t&e de/ault descritor /ile F%ake"ile)G T&e FmakeG
utility ro1ides a simle way to incororate a newly de1eloed modules into NS2)
4/ter de1eloin' a CCC source code* we simly add an obBect /ile name into t&e
deendency and rerun Fmake)G
2=8 "<ercises
1) .ownload and install NS2) Hint< 6&en usin' 6indows* install Cy'win /irst)
2) 6&at are ustream obBects* downstream obBects* and tar'etsR .raw a dia'ram
to suort your eAlanation)
3) 6rite a Tcl simulation scrit w&ic& rints t&e inut ar'uments on screen)
Cormat t&e outut suc& t&at eac& line contains only one inut ar'ument) (un
NS2 to test your ro'ram) Hint< See Tcl Tutorial in 4endiA 4)
:) 6&at are t&e key stes in NS2 simulationR Comare your answer wit& 'eneral
simulation stes discussed in C&a) 1)
3) 6rite a Tcl simulation scrit /or t&e /ollowin' network dia'ram in Ci') 2)8) (un
NS2 to test your ro'ram)
,ddr:Port @ !:!
.'P! '0P!
)!
% Mb6s
,ddr:Port @ 3:!
Sin1!
1:% Mb6s
)2 )3
!:% Mb6s
)1
Sin11
,ddr:Port @ 3:1
.'P1
'0P1
,ddr:Port @ 1:!
4ig= 2=6 EAamle network dia'ram
:, 2 Introduction to Network Simulator 2
8) .esi'n CCC and OTcl classes ?e)')* Class %yTCP@) .eri1e t&is class /rom t&e
TCP (eno classes s&own in Table 2)2) 0se t&e con1ention de/ined abo1e to
name your class names* 1ariables$inst1ars* and /unctions$instrocs in bot& t&e
domains)
2) 6rite a ro'ram F(ello*G w&ic& rints FHello NS1 DsersCG on t&e
screen
a) 0sin' C lan'ua'e*
b) 0sin' CCC) .e/ine at least one class*
c) 0sin' a make utility to create an eAecutable /ile) %ake c&an'es in your
CCC and$or &eader /iles) (un t&e make utility) .oes t&e utility re9
comile and recreate an eAecutable /ile /or your ro'ramR
") Suose you &a1e de1eloed a new NS2 module) ;our module include CCC
/iles* &eader /iles* and Tcl /iles) 6&ere would you store t&ese /ileR How would
you include t&is new NS2 module into NS2R .emonstrate your answer wit& an
eAamle)
$ha&ter *
+inkage Between ,Tc# an $CC in NS2
NS2 is an obBect9oriented simulator written in OTcl and CCC lan'ua'es)
1
6&ile
OTcl acts as t&e /rontend ?i)e)* user inter/ace@* CCC acts as t&e backend runnin'
t&e actual simulation ?Ci') 2)1@) Crom Ci') 3)1 class &ierarc&ies o/ bot& lan'ua'es
can be eit&er standalone or linked to'et&er usin' an OTcl$CCC inter/ace called
TclC! M12N) T&e OTcl and CCC classes w&ic& are linked to'et&er are re/erred to
as the interpreted hierarchy and the compiled hierarchy* resecti1ely)
ObBect construction in NS2 roceeds as /ollows) 4 ro'rammer creates an
obBect /rom an OTcl class in t&e interreted &ierarc&y) T&en* NS2 ?or more
recisely TclC!@ automatically creates a so9called s&adow obBect /rom a CCC
class in t&e comiled &ierarc&y) It is imortant to note t&at no s&adow obBect
would be created w&en a ro'rammer creates an obBect /rom a class in bot&
comiled and standalone OTcl &ierarc&ies)
6ritten in CCC* TclC! consists o/ t&e /ollowin' siA main classes) Cirst* class
TclClass mas class names in t&e comiled &ierarc&y to class names in t&e
interreted &ierarc&y) Second* class InstSar binds member 1ariables in bot&
t&e &ierarc&ies to'et&er) T&ird* class TclCommand allows t&e Tcl interreter to
eAecute non9OOP C>> statements) Court&* class TclObject is t&e base class /or
all CCC simulation obBects in t&e comiled &ierarc&y) Ci/t&* class Tcl ro1ides
met&ods to access t&e interreted &ierarc&y /rom t&e comiled &ierarc&y) Cinally*
class EmbeddedTcl translates OTcl scrits into CCC codes) T&e details o/ t&e
abo1e classes are located in /iles Ttclcl$tclcl)&* Ttclcl$Tcl)cc* and Ttclcl$tcl4Init)cc)
T&is c&ater /ocuses on usin' TclC! in t&e /ollowin' meanin'/ul ways<
Section 3)1 resents t&e moti1ation o/ &a1in' two lan'ua'es in
NS2)
Section 3)2 eAlains class bindin' w&ic& mas CCC class names to OTcl class
names)
1
(e/er to M18N /or t&e C>> ro'rammin' lan'ua'e)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* :1
.OI 1,)1,,2$#2"919:81:91:,893 3* = Srin'er Science>+usiness %edia* !!C 2,12
:2 3 !inka'e +etween OTcl and CCC in NS2
4ig= *=% Two lan'ua'e structure o/ NS2 M1:N) Class &ierarc&ies in bot& t&e lan'ua'es may be
standalone or linked to'et&er) OTcl and CCC class &ierarc&ies w&ic& are linked to'et&er are
called the interpreted hierarchy and the compiled hierarchy* resecti1ely
Section 3)3 discusses &ow NS2 binds a air o/ member 1ariables o/ two bound
classes so t&at a c&an'e in one 1ariable will be automatically re/lected in t&e
ot&er)
Section 3): s&ows a met&od to eAecute CCC statements /rom t&e OTcl
domain)
Section 3)3 walks t&rou'& t&e s&adow obBect construction
rocess)
Section 3)8 discusses 1arious /unctionalities to access t&e Tcl interreter /rom
t&e CCC domain< Tcl statement eAecution* result assin' between bot& t&e
domains* and t&e TclObBect re/erence retrie1al)
Section 3)2 brie/ly outlines &ow t&e OTcl codes are translated into t&e CCC
code)
*=% The Two.+anguage $once&t in NS2
".1.1 The %at!res of OTcl and CCC Prograing Lang!ages
6hy two languages7 !oosely seakin'* NS2 uses OTcl to create and con/i'ure a
network ?i)e)* user /rontend@* and CCC to run simulation ?i)e)* internal
mec&anism@) 4ll CCC codes need to be comiled and linked to create an
eAecutable /ile) Since t&e body o/ NS2 is /airly lar'e* t&e comilation time is
not ne'li'ible) 4 tyical %acbook Pro comuter reDuires /ew seconds ?lon'
enou'& to annoy most ro'rammers@ to comile and link t&e codes wit& a small
c&an'e suc& as includin' a CCC statement Fint i:0;G into t&e ro'ram)
OTcl* on t&e ot&er &and* is an interreted ro'rammin' lan'ua'e* not a comiled
one) 4ny c&an'e in a OTcl /ile can be eAecuted wit&out comilation) Since OTcl
does not con1ert t&e codes into mac&ine lan'ua'e* eac& line needs more eAecution
time)
2
2
4lt&ou'& OTcl is an interreted ro'rammin' lan'ua'e* NS2 translates most o/ its OTcl codes
into CCC usin' class EmbeddedTcl ?see Sect) 3)2@ to seed u t&e simulation) 4s a result*
most c&an'e in OTcl also reDuires comilation)
3)1 T&e Two9!an'ua'e Concet in NS2 :3
6ac1et
Lin1 delay
:::
*(erall 6ac1et deli(ery delay
4ig= *=2 4 c&ain toolo'y /or network simulation
In summary* CCC is /ast to run but slow to c&an'e) It is suitable /or runnin'
a lar'e simulation) OTcl* on t&e ot&er &and* is slow to run but /ast to c&an'e)
It is suitable as a arameter con/i'urator) NS2 is constructed by combinin' t&e
ad1anta'es o/ t&ese two lan'ua'es)
".1.2 CCC Prograing Styles and Its Application in %S2
T&e moti1ation can be better understood by considerin' t&ree /ollowin' CCC
ro'rammin' styles)
*=%=2=% Basic $CC Programming
T&is is t&e simlest /orm and in1ol1es basic CCC instructions only) T&is style &as
a /leAibility roblem* since any c&an'e in system arameters reDuires a
comilation ?w&ic& takes non9ne'li'ible time@ o/ t&e entire ro'ram)
E%ample $** Consider t&e network toolo'y in Ci') 3)2) .e/ine o1erall acket
deli1ery delay as t&e time needed to carry a acket /rom t&e le/tmost node to t&e
ri'&tmost node* w&ere delay in link FiG is Fd5iG and total number o/ nodes is
Fn!m5nodes)G 6e would like to measure t&e o1erall acket deli1ery delay and
s&ow t&e result on t&e screen)
Suose t&at e1ery link &as t&e same delay o/ 1 s ?i)e)* Fd5i : 2G second /or
all FiG@* and t&e number o/ nodes is 11 ?n!m5nodes : 22@) Pro'ram 3)1
s&ows a CCC ro'ram written in t&is style ?t&e /ilename is FsimIccG@) Since t&e
link delay is /iAed* we simly increase FdelayG /or n!m5nodesJ2 times
?!ines : and 3@) 4/ter comilin' and linkin' t&e /ile simIcc* we obtain an
eAecutable /ile Fsim)G +y eAecutin' FIMsimG at t&e command romt* we will see
t&e /ollowin' result on t&e screen<
KKIMsim
Overall Packet Delay is 20I0 secondsI
.esite its simlicity* t&is ro'rammin' style &as a /leAibility roblem) Suose
link delay and t&e number o/ nodes are c&an'ed to 2 s and 3 nodes* resecti1ely)
:: 3 !inka'e +etween OTcl and CCC in NS2
Program *=% 4 basic CCC ro'ram t&at simulates EAamle 3)1* w&ere t&e delay
/or eac& o/ t&e links is 1 unit and t&e number o/ nodes is 11
MMsimIcc
2 main&'7
1 "loat delay : 0) d5i : 2;
3 int i) n!m5nodes : 22;
= "or&i : 2; i < n!m5nodes; i44'
> delay 4: d5i;
A print"&HOverall Packet Delay is E1I2" secondsITnH)
delay';
B 8
T&en* we need to modi/y* comile* and link t&e /ile simIcc to create a new
eAecutable /ile Fsim)G 4/ter t&at* we can run FIMsimG to 'enerate anot&er result
?/or d5i U 2 and n!m5nodes U 3@)
*=%=2=2 $CC Programming with 'n&ut Arguments
4ddressin' t&e /leAibility roblem* t&is ro'rammin' style takes t&e system
aram9 eters ?i)e)* ar$v)ar$c@ as inut ar'uments M18N) 4s t&e system
arameters c&an'e* we can simly c&an'e t&e inut ar'uments* and do not need to
recomile t&e entire ro'ram)
E%ample $*2* Consider EAamle 3)1) 6e can a1oid t&e abo1e need /or recomila9
tion and relinkin' by /eedin' system arameters as inut ar'uments o/ t&e
ro'ram) Pro'ram 3)2 s&ows a ro'ram t&at /eeds link delay and t&e number o/
nodes as t&e /irst and t&e second ar'uments* resecti1ely) !ine 1 seci/ies t&at t&e
ro'ram takes inut ar'uments) T&e 1ariable ar$c is t&e number o/ inut
ar'uments) T&e 1ariable ar$v is an ar'ument 1ector t&at contains all inut
ar'uments ro1ided by t&e caller ?See t&e details on CCC ro'rammin' wit&
inut ar'uments in M18N@)
6it& t&is style* we only need to comile and link t&e ro'ram once) 4/ter
obtainin' an eAecutable /ile Fsim*G we can c&an'e t&e simulation arameters as
desired) Cor eAamle*
KK IMsim 2 22
Overall Packet Delay is 20I0 secondsI
KK IMsim 1 >
Overall Packet Delay is /I0 secondsI
4lt&ou'& t&is ro'rammin' style sol1es t&e /leAibility roblem* it becomes
increasin'ly incon1enient w&en t&e number o/ inut ar'uments increases) Cor
eAamle* i/ delays in all t&e links in EAamle 3)1 are di//erent* we will &a1e to
tye in all t&e 1alues o/ link delay e1ery time we run t&e ro'ram)
3)1 T&e Two9!an'ua'e Concet in NS2 :3
Program *=2 4 CCC ro'ram wit& inut ar'uments< 4 CCC ro'ram w&ic&
simulate EAamle 3)2) T&e /irst and second ar'uments are link delay and t&e
number o/ nodes* resecti1ely
MMsimIcc
2 int main&int ar$c) c(ar
N
ar$v?@' 7
1 "loat delay : 0) d5i : ato"&ar$v?0@';
3 int i) n!m5nodes : atoi&ar$v?2@';
= "or&i : 2; i < n!m5nodes; i44'
> delay 4: d5i;
A print"&HOverall Packet Delay is E1I2" secondsTnH)
delay';
B 8
*=%=2=* $CC Programming with $onfiguration 4i#es
T&is last ro'rammin' style uts all system arameters in a con/i'uration /ile*
and t&e CCC ro'ram reads t&e system arameters /rom t&e con/i'uration /iles)
T&is style does not &a1e t&e /leAibility roblem* and it /acilitates ro'ram in1o9
cation) To c&an'e system arameters* we can simly c&an'e t&e content o/ t&e
con/i'uration /ile) In /act* t&is is t&e style /rom w&ic& NS2 de1elos)
E%ample $*$* Pro'ram 3)3 alies t&e last C>> ro'rammin' style ?i)e)* wit& con9
/i'uration /iles@) T&e ro'ram takes only one inut ar'ument< T&e con/i'uration
/ile name ?See CCC /ile inut$outut in M18N@) Cunction
readAr$QromQile&"p)d' reads t&e con/i'uration /ile associated wit& a /ile
ointer F"p*G and sets 1ariables Fn!m5nodeG and FdG accordin'ly ?t&e details
are not s&own &ere@) In t&is case* t&e con/i'uration /ile ?con"i$It*t@ is s&own
in !ines 1, and 11) 6&en in1okin' FIMsim con"i$It*t*G t&e screen will
s&ow t&e /ollowin' result<
KKIMsim con"i$It*t
Overall Packet Delay is >>I0 secondsI
To c&an'e t&e system arameters* we can simly modi/y t&e /ile
Fcon"i$It*tG and run FIMsim)G Clearly* t&is ro'rammin' style remo1es
t&e necessity /or comilin' t&e entire ro'ram and t&e len't&y in1ocation rocess)
(ecall /rom Sect) 2)3 t&at we write and /eed a Tcl simulation script as an inut
ar9 'ument to NS2 w&en runnin' a simulation ?e)')* eAecutin' Fns
my"irst5nsItclG@) Here* FnsG is a CCC eAecutable /ile obtained /rom t&e
comilation* w&ile Fmy"irst5nsItclG is an inut con/i'uration /ile seci/yin'
system arameters and con/i'uration suc& as nodes* link* and &ow t&ey are
connected) 4nalo'ous to readin' a con/i'uration /ile t&rou'& CCC* NS2 reads t&e
system con/i'uration /rom t&e Tcl simulation scrit) 6&en we would like to
c&an'e t&e arameters in t&e simulation* all we &a1e to do is to modi/y t&e Tcl
simulation scrit and rerun t&e simulation)
:8 3 !inka'e +etween OTcl and CCC in NS2
Program *=* CCC ro'rammin' style wit& con/i'uration /iles< 4 CCC ro'ram
in /ile simIcc ?!ines 1H#@ and a con/i'uration /ile con"i$It*t ?!ines 1, and
11@
MMsimIcc
2 int main&int ar$c) c(ar
N
ar$v?@' 7
1 "loat delay : 0) d?20@;
3 QILE
N
"p : "open&ar$v?2@)H,H';
= int i) n!m5nodes : readAr$QromQile&"p)d';
> "or&i : 2; i < n!m5nodes; i44'
A delay 4: d?iJ2@;
B print"&HOverall Packet Delay is E1I2" secondsTnH)
delay';
/ "close&"p';
G 8
MMcon"i$It*t
20 N!mber o" node : 22
22 Link delay : 2 1 3 = > A B / G 20
*=2 $#ass Bining
Class bindin' mas CCC classes to OTcl classes) 6&en a ro'rammer creates
an obBect /rom t&e interreted &ierarc&y* NS2 determines t&e comiled class /rom
w&ic& a s&adow obBect s&ould be instantiated by lookin' u t&e class bindin'
ma) 4s an eAamle* an OTcl class A$entMTcp is bound to t&e CCC class
TcpA$ent) 4 ro'rammer can create an A$entMTCP obBect usin' t&e
/ollowin' OTcl statement
ne, A$entMTCP
In resonse* NS2 automatically creates a comiled s&adow TcpA$ent
obBect)
".2.1 Class 2inding Process
4 class bindin' rocess in1ol1es /our /ollowin'
comonents<
4 CCC class ?e)')* class TcpA$ent@
4n OTcl class ?e)')* class A$entMTCP@
4 main' class ?e)')* class TcpClass@< 4 CCC class w&ic& mas a CCC
class to an OTcl class
4 main' 1ariable ?e)')* class5tcp@< 4 static 1ariable instantiated /rom t&e
abo1e main' class to er/orm class bindin' /unctionalities)
Class bindin' is carried out by de/inin' t&e main' class as a art o/ t&e CCC
/ile) Pro'ram 3): s&ows a main' class TcpClass t&at binds t&e OTcl class
A$entMTCP to t&e CCC class TcpA$ent)
3)2 Class +indin' :2
Program *=/ Class TcpClass w&ic& binds t&e OTcl A$entMTCP to t&e CCC
class TcpA$ent
MMUnsMtcpMtcpIcc
2 static class TcpClass 9 p!blic TclClass 7
1 p!blic9
3 TcpClass&' 9 TclClass&HA$entMTCPH' 78
= TclObject
N
create&int ) const c(ar
N
const
N
' 7
> ret!rn &ne, TcpA$ent&'';
A 8
B 8 class5tcp;
E1ery main' class deri1es /rom t&e CCC class TclClass w&ere all t&e
bindin' /unctionalities are de/ined) Eac& main' class contains only two
/unctions< T&e constructor and /unction create&III') In !ine 3* t&e
constructor /eeds t&e OTcl class name A$entMTCP as an inut ar'ument to t&e
constructor o/ its base class ?i)e)* TclClass@)
3
In !ines :H8* t&e /unction
create&III' creates a s&adow comiled obBect w&ose class is TcpA$ent)
T&is /unction is automatically eAecuted w&en a ro'rammer creates an
A$entMTCP obBect /rom t&e interreted &ierarc&y) 6e s&all discuss t&e details
o/ t&e s&adow obBect construction rocess later in Sect) 3)3)
Note t&at a CCC class by itsel/ cannot er/orm any oeration) To bind classes*
we need to instantiate a main' obBect /rom t&e main' class) In !ine 2* suc& an
obBect is t&e 1ariable class5tcp) Since e1ery class bindin' is uniDue* t&e
main' 1ariable class5tcp is declared as static to a1oid class bindin'
dulication)
".2.2 )efining 6o!r O&n Class 2inding
T&e /ollowin' stes bind an OTcl class to a CCC class<
1) Seci/y an OTcl class ?e)')* A$entMTCP@ and a CCC class ?e)')* TcpA$ent@
w&ic& s&all be bound to'et&er)
2) .eri1e a main' class ?e)')* TcpClass@ /rom class TclClass)
3) .e/ine t&e constructor o/ t&e main' class ?e)')* !ine 3 in Pro'ram 3):@) Ceed
t&e OTcl class name ?e)')* A$entMTCP@ as an inut ar'ument to t&e
constructor o/ t&e class TclClass ?i)e)* t&e base class@)
:) .e/ine /unction create&III' to construct a s&adow comiled obBect)
In1oke Fne,G to create a s&adow comiled obBect and return t&e created
obBect to t&e caller ?e)')* ret!rn &ne, TcpA$ent&'' in !ine 3 o/
Pro'ram 3):@)
3) .eclare a static main' 1ariable ?e)')* class5tcp@)
3
4 CCC oerator F9G indicates w&at to be done be/ore t&e eAecution o/ w&at is enclosed wit&in
t&e /ollowin' curly braces M18N)
:" 3 !inka'e +etween OTcl and CCC in NS2
Tab#e *=% EAamles o/ namin' con1ention /or main' classes and 1ariables
C CC c l ass O Tcl c l ass % a i n' c l ass % a i n' 1 ar i ab l e
TcpA$ent A$entMTCP TcpClass class5tcp
#enoTcpA$ent A$entMTCPM#eno #enoTcpClass class5reno
DropTail !e!eMDropTail DropTailClass class5drop5tail
".2." %aing Con#ention for Class TclClass
T&e con1ention to name main' classes and main' 1ariables are as /ollows)
Cirst* e1ery class deri1es directly /rom class TclClass* irresecti1e o/ its class
&ierarc&y) Cor eAamle* class #enoTcpA$ent deri1es /rom class TcpA$ent)
Howe1er* t&eir main' classes #enoTcpClass and TcpClass deri1e
/rom class TclClass)
Second* t&e namin' con1ention is 1ery similar to t&e CCC 1ariable namin'
con1ention) In most cases* we simly name t&e main' class by attac&in' t&e
word FClassG to t&e CCC class name) %ain' 1ariables are named wit& t&e
re/iA Fclass5G attac&ed to t&e /ront) Table 3)1 s&ows /ew eAamles o/ t&e
namin' con1ention)
*=* >ariab#e Bining
Class bindin'* discussed in t&e re1ious section* creates connections between OTcl
and CCC class names) +y de/ault* t&e bound classes &a1e t&eir own 1ariables
w&ic& are not related in any way) 7ariable bindin' is a tool t&at allows
ro'rammers to bind one 1ariable in t&e CCC class to anot&er 1ariable in t&e
bound OTcl class suc& t&at a c&an'e in one 1ariable will be automatically re/lected
in t&e ot&er)
".".1 .aria-le 2inding
Methodology
4n OTcl 1ariable* iname* can be bound to a CCC 1ariable* cname* by includin'
one o/ t&e /ollowin' statements in t&e CCC class constructor<
bind&HinameH)Fcname' binds inte'er and real
1ariables)
:
bind5b,&HinameH)Fcname' binds a bandwidt&
1ariable)
bind5time&HinameH)Fcname' bind a time
1ariable)
bind5bool&HinameH)Fcname' bind a boolean
1ariable)
3)3 7ariable +indin' :#
:
In Sect) 3)3)3* we s&all discuss t&e /i1e /ollowin' data tyes in NS2< Inte'er* real* bandwidt&*
time* and boolean)
:" 3 !inka'e +etween OTcl and CCC in NS2
E%ample $*/* !et a CCC class %yObject be bound to an OTcl class %yOTcl
Object) !et ico!nt5* idelay5* ispeed5* ido,n5time5* iis5active5
be OTcl class 1ariables w&ose tyes are inte'er* real* bandwidt&* time* and
boolean* resecti1ely) T&e /ollowin' CCC ro'ram binds t&e abo1e 1ariables<
class %yObject 7
p!blic9
int co!nt5;
do!ble delay5)do,n5time5)speed5;
bool is5active5;
%yObject&' 7
bind&Hico!nt5H)Fco!nt5';
bind&Hidelay5H)Fdelay5';
bind5b,&Hispeed5H)Fspeed5';
bind5time&Hido,n5time5H)Fdo,n5time5';
bind5bool&Hiis5active5H)Fis5active5';
8;
8;
".".2 Setting the )efa!lt
.al!es
NS2 sets t&e de/ault 1alues o/ bound OTcl class 1ariables in t&e /ile Tns$tcl$lib$ns9
de/ault)tcl) T&e syntaA /or settin' a de/ault 1alue is similar to t&e 1alue assi'nment
syntaA) T&at is*
<classNameK set <instvarK <de"5val!eK
w&ic& sets t&e de/ault 1alue o/ t&e inst1ar <instvarK o/ class <classNameK
to be <de"5val!eK) 4s an eAamle* a art o/ /ile Tns$tcl$lib$ns9de/ault)tcl is
s&own in Pro'ram 3)3)
In re'ards to de/ault 1alues* t&ere are two imortant notes &ere) Cirst* i/ no
de/ault 1alue is ro1ided /or a bound 1ariable* t&e instroc ,arnJinstvar
/III' o/ class SplitObject will s&ow t&e /ollowin' a warnin' messa'e on
t&e screen<
,arnin$9 no class variable <C44 class nameK99<OTcl
variable nameK see tclJobjectItcl in tclcl "or
in"o abo!t t(is ,arnin$I
T&e second note is t&at t&e de/ault 1alue settin' in t&e OTcl domain takes
recedence o1er t&at in t&e CCC domain) In CCC* t&e de/ault 1alues are usually
set in t&e constructor) +ut t&e 1alues would be o1erwritten by t&ose seci/ied in
t&e /ile Tns$tcl$lib$ns9de/ault)tcl)
3)3 7ariable +indin' 31
Program *=0 EAamles /or de/ault 1alue assi'nment
MMUnsMtclMlibMnsJde"a!ltItcl
2 Error%odel set enable5 2
1 Error%odel set markecn5 "alse
3 Error%odel set delay5pkt5 "alse
= Error%odel set delay5 0
> Error%odel set rate5 0
A Error%odel set band,idt(5 1%b
B Error%odel set deb!$5 "alse
III
/ Classi"ier set o""set5 0
G Classi"ier set s(i"t5 0
20 Classi"ier set mask5 0*""""""""
22 Classi"ier set deb!$5 "alse
"."." %S2 )ata Types
NS2 de/ines t&e /ollowin' /i1e data tyes in t&e OTcl domain< real* inte'er*
bandwidt&* time* and boolean)
*=*=*=% Rea# an 'nteger >ariab#es
T&ese two NS2 data tyes are seci/ied as do!ble91alued and int91alued*
resecti1ely* in t&e C>> domain) In t&e OTcl domain* we can use Fe<*KG as
F 1,
<*K
G* w&ere <*K denotes t&e 1alue stored in t&e 1ariable *)
E%ample $*1* !et realvar and intvar be a real inst1ar and an inte'er
inst1ar* resecti1ely* o/ an OTcl obBect FobjG) T&e /ollowin' s&ows 1arious
ways to set
3
realvar and intvar to be 12,,<
Pobj set realvar 2I1e3
Pobj set realvar 2100
Pobj set intvar 2100
*=*=*=2 Banwith
+andwidt& is seci/ied as do!ble91alued in t&e C>> domain) +y de/ault* t&e unit
o/ bandwidt& is bits er second ?bs@) In t&e OTcl domain we can add t&e
/ollowin' su//iAes to /acilitate bandwidt& settin')
3
See t&e OTcl 1alue assi'nment in 4endiA 4)2):)
3, 3 !inka'e +etween OTcl and CCC in NS2
FkG or FVG means kilo or 1,
3
*
FmG or F%G means me'a or 1,
8
* and
F.G c&an'es t&e unit /rom bits to bytes)
NS2 only considers leadin' c&aracter o/ 1alid su//iAes) T&ere/ore* t&e su//iAes
F%G and F%bpsG are t&e same to NS2)
E%ample $*8* !et b,var be a bandwidt& inst1ar o/ an OTcl obBect Fobj)G T&e
di//erent ways to set b,var to be " %bs ?me'abits er second@ are as /ollows<
Pobj set b,var /000000
Pobj set b,var /m
Pobj set b,var /%bps
Pobj set b,var /000k
Pobj set b,var 2%.
*=*=*=* Time
Time is seci/ied as do!ble91alued in t&e C>> domain) +y de/ault* t&e unit o/
time is second) Otionally* we can add t&e /ollowin' su//iAes to c&an'e t&e unit)
FmG means milli or 1,
3
*
FnG means nano or 1,
#
* and
FpG means ico or 1,
12
)
NS2 only reads t&e leadin' c&aracter o/ 1alid su//iAes) T&ere/ore* t&e su//iAes
FpG
and FpsG are t&e same to NS2)
E%ample $*9* !et timevar also be a time inst1ar o/ an OTcl obBect Fobj)G
T&e di//erent ways to set timevar to 2 ms are as /ollows<
Pobj set timevar 1m
Pobj set timevar 1eJ3
Pobj set timevar 1eAn
Pobj set timevar 1eGps
*=*=*=/ Boo#ean
+oolean is seci/ied as eit&er tr!e ?or a ositi1e number@ or "alse ?or a Jero@
in t&e C>> domain) 4 boolean 1ariable will be tr!e i/ t&e /irst letter o/ t&e
1alue is 'reater t&an ,* or Ft*G or FT)G Ot&erwise* t&e 1ariable will be "alse)
E%ample $*:* !et boolvar be a boolean inst1ar o/ an OTcl obBect Fobj)G T&e
di//erent ways to set boolvar to be tr!e and "alse are as /ollows<
O set boolvar to be T#DE
Pobj set boolvar 2
3): EAecution o/ CCC Statements /rom t&e OTcl .omain 33
Pobj set boolvar T
Pobj set boolvar tr!e
Pobj set boolvar tasty
Pobj set boolvar 10
Pobj set boolvar 3I3B
Pobj set boolvar =***
O set boolvar to be QALSE
Pobj set boolvar 0
Pobj set boolvar "
Pobj set boolvar "alse
Pobj set boolvar somet(in$
Pobj set boolvar 0IG
Pobj set boolvar J>I1G
4'ain* NS2 i'nores all letters eAcet /or t&e /irst one) 4s can be seen /rom
EAamle 3)"* t&ere are se1eral stran'e ways /or settin' a boolean 1ariable ?e)')*
tasty* somet(in$* J>I1G@)
E%ample $*;* T&e /ollowin' ro'ram se'ment s&ows &ow NS2 er/orms 1alue
assi'nment to inst1ars deb!$5 and rate5 o/ class Error%odel)
O Create a Sim!lator instance
set ns ?ne, Sim!lator@
O Create an error model object
set err ?ne, Error%odel@
O Set val!es "or class variables
Perr set deb!$5 somet(in$
Perr set rate5 21e3
O S(o, t(e res!lts
p!ts Hdeb!$5&bool' is ?Perr set deb!$5@H
p!ts Hrate5&do!ble' is ?Perr set rate5@H
T&e results o/ eAecution o/ t&e abo1e ro'ram are as /ollows<
KKdeb!$5&bool' is 0
KKrate5&do!ble' is 21000
.urin' t&e con1ersion* t&e arameter su//iAes are con1erted ?e)')* F%G is con9
1erted by multilyin' 1,
8
to t&e 1alue@) Cor boolean data tye* NS2 retrie1es t&e
/irst c&aracter in t&e strin' and t&rows away all ot&er c&aracters) I/ t&e retrie1ed
c&aracter is a ositi1e inte'er* Ft*G or FT*G NS2 will assi'n a tr!e 1alue to
t&e bound C>> 1ariable) Ot&erwise* t&e 1ariable will be set to "alse)
32 3 !inka'e +etween OTcl and CCC in NS2
Tab#e *=2 NS2 data tyes*
CCC main' classes* and
t&e corresondin' CCC
data tyes
NS2 da t a t ye C CC m a i n' c l ass C CC da t a t ye
Inte'er InstSarInt int
(eal InstSar#eal do!ble
+andwidt& InstSar.and,idt( do!ble
Time InstSarTime do!ble
+oolean InstSar.ool bool
".".$ Class Inst#ar
Class Instvar is a CCC class w&ic& binds member 1ariables o/ OTcl and
CCC classes to'et&er) It &as /i1e deri1ed classes* eac& /or one o/ t&e NS2 data
tyes de/ined in Sect) 3)3)3) T&ese /i1e classes and t&eir main' class are
s&own in Table 3)2)
*=/ "<ecution of $CC Statements from the ,Tc# -omain
T&is section /ocuses on Fmet&od bindin'*G w&ic& makes an (Tcl commands
a1ailable in t&e CCC domain) T&ere are two tyes o/ met&od bindin'< OOP
bindin' and non9OOP bindin') T&e OOP bindin'* binds t&e met&od usin' t&e
CCC /unction command&III' associated wit& a CCC class) In t&is case* t&e
command strin' is called an FOTcl command)G Cor non9OOP bindin'* t&e strin'
H called FTcl commandG H is not bound to any class* and can be eAecuted
'lobally) It is not ad1isable to eAtensi1ely use Tcl commands* since t&ey 1iolate
t&e OOP rincile)
".$.1 OTcl Coands in a %!tshell
*=/=%=% ,Tc# $omman 'nvocation
T&e in1ocation o/ an OTcl command is similar to t&at o/ an
instroc<
Pobj <cmd5nameK ?<ar$sK@
w&ere Pobj is a TclObBect* <cmd5nameK is t&e OTcl command strin'
associated wit& Pobj* and <ar$sK is an otional list o/ inut ar'uments)
3): EAecution o/ CCC Statements /rom t&e OTcl .omain 33
Program *=6 Cunction command o/ class TcpA$ent
MMUnsMtcpMtcpIcc
2 int TcpA$ent99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 III
= i" &ar$c :: 3' 7
> i" &strcmp&ar$v?2@) HeventtraceH' :: 0' 7
A et5 : &EventTrace
N
'TclObject99look!p&ar$v?1@';
B ret!rn &TCL5OV';
/ 8
G III
20 8
22 III
21 ret!rn &A$ent99command&ar$c) ar$v'';
23 8
*=/=%=2 $CC -efinition of ,Tc# $ommans
OTcl commands are de/ined in t&e /unction command&ar$c)ar$v' o/ CCC
classes in t&e comiled &ierarc&y) T&is /unction takes two inut arameters<
Far$cG and Far$v*G w&ic& are t&e number o/ inut arameters and an array
containin' t&e inut arameters* resecti1ely)
E%ample $*2* Consider an OTcl command eventtrace/et' associated wit& an
OTcl class A$entMTCP* w&ere FetG is an e1ent tracin' obBect) Pro'ram 3)8
s&ows t&e details o/ t&is OTcl command) Suose Ptcp and Pobj are an
A$entMTCP obBect and an e1ent tracin' obBect* resecti1ely) T&e eAecution o/
OTcl command eventtrace is as /ollows<
Ptcp eventtrace Pobj
T&e OTcl command eventtrace and t&e e1ent tracin' obBect Pobj are
stored in ar$v?2@ and ar$v?1@* resecti1ely)
8
!ine 3 returns tr!e* and !ine
8 stores t&e inut arameter ar$v?1@ in t&e class 1ariable et5)
*=/=%=* $reating @our ,wn ,Tc#
$ommans
Here are t&e main stes in de/inin' an OTcl command<
1) Pick a name* t&e number o/ inut ar'uments* and t&e OTcl class /or an OTcl
command)
8
4s we s&all see* ar$v?0@ always contains t&e strin' Fcmd)G
3: 3 !inka'e +etween OTcl and CCC in NS2
2) .e/ine a CCC /unction command&ar$c)ar$v' /or t&e s&adow CCC class
in t&e comiled &ierarc&y)
3) 6it&in t&e /unction command&III'* create two conditions w&ic& comare t&e
number o/ inut o/ ar'uments wit& ar$c and t&e name o/ t&e OTcl command
wit& ar$v?2@) Seci/y t&e desired CCC statements* i/ bot& t&e conditions
matc&) (eturn TCL5OV a/ter t&e CCC statement eAecution)
:) Seci/y t&e de/ault return statement in t&e case t&at no criterion matc&es wit&
t&e inut OTcl command) Cor eAamle* !ine 12 in Pro'ram 3)8 eAecutes t&e
/unction command&III' attributed to t&e base class A$ent* and returns t&e
eAecution result to t&e caller)
".$.2 The Internal Mechanis of OTcl Coands
*=/=2=% ,Tc# $omman 'nvocation Mechanism
4s discussed in Sect) 3):)1* t&e syntaA /or t&e OTcl command in1ocation is similar
to t&at o/ instroc in1ocation) T&ere/ore* t&e internal rocess is similar to t&e
instroc in1ocation mec&anism discussed in 4endiA 4)2):)
T&e rocess be'ins by eAecutin' t&e /ollowin' OTcl statement<
Pobj <cmd5nameK ?<ar$sK@
I/ t&e class corresondin' to Pobj contains* eit&er t&e instroc <cmd5nameK
or t&e instroc F!nkno,nG* it will eAecute t&e instroc) Ot&erwise* t&e rocess
would mo1e to t&e base class and reeat itsel/) In case o/ OTcl commands* t&e
to9le1el class is class SplitObject) T&e /unction !nkno,n o/ class
SplitObject is seci/ied in Pro'ram 3)2) T&e key statement in t&is instroc
is FPsel" cmd
Par$sG in !ine 2* w&ic& accordin' to t&e abo1e OTcl command syntaA can be
written as /ollows<
Pobj cmd <cmd5nameK <ar$sK
Program *=5 Instroc !nkno,n o/ class
SplitObject
MMUtclMtclJobjectItcl
2 SplitObject instproc !nkno,n ar$s 7
1 i" ?catc( HPsel" cmd Par$sH ret@ 7
3 set cls ?Psel" in"o class@
= $lobal errorIn"o
> set savedIn"o PerrorIn"o
A error Herror ,(en callin$ class Pcls9 Par$sH P
savedIn"o
B 8
/ ret!rn Pret
G 8
3): EAecution o/ CCC Statements /rom t&e OTcl .omain 32
Tab#e *=* .escrition o/
elements o/ array Far$vG o/
/unction command
IndeA ?i@ Element ?ar$v?i@@
, cmd
1 T&e command name ?<cmd5nameK@
2 T&e /irst inut ar'ument in <ar$sK
3 T&e second inut ar'ument in <ar$sK
< <
T&e strin' FcmdG is t&e 'ateway to t&e CCC domain) Here* t&e strin' Fcmd
Par$sG ?i)e)* Fcmd <cmd5nameK ?<ar$sK@G@ is assed as an inut ar'ument
1ector ?ar$v@ to t&e /unction Fcommand&ar$c)ar$v'G o/ t&e s&adow class
?e')* TcpA$ent@ as seci/ied in Table
3)3)
2
NeAt* t&e /unction command&ar$c)ar$v' comares t&e number o/ ar'u9
ments and t&e OTcl command name wit& ar$c and ar$v?2@* resecti1ely) I/
bot&
matc&* it takes t&e desired actions and returns TCL5OV ?e)')* see Pro'ram
3)8@)
*=/=2=2 ,Tc# -efau#t Returning Structure
Owin' to its OOP nature* NS2 allows OTcl commands to roa'ate u t&e
&ierarc&y) T&at is* an OTcl command o/ a certain OTcl class can be seci/ied in
t&e /unction command&III' o/ t&e s&adow class or in t&e /unction
command&' o/ any o/ its arent classes) I/ t&e inut OTcl command ?i)e)*
ar$v?2@@ does not matc& wit& t&e strin' seci/ied in t&e s&adow class* /unction
command&III' will ski to eAecute t&e de/ault returnin' statement in t&e last
line ?e)')* !ine 12 in Pro'ram 3)8@)
T&e de/ault returnin' statement /irst asses t&e same set o/ inut ar'uments
?i)e)* &ar$c)ar$v'@ to t&e /unction command&III' o/ t&e base class)
T&ere/ore* t&e same rocess o/ comarin' t&e OTcl command and C>> statement
eAecution will reeat in t&e base class) I/ t&e OTcl command does not matc&* t&e
de/ault returnin' rocess will be carried out recursi1ely* until t&e to9le1el
comiled class ?i)e)* class TclObject@ is reac&ed) Here* t&e /unction
command&III' o/ class TclObject will reort an error ?e)')* no suc&
met&od* reDuires additional ar's@ and return TCL5E##O# ?see /ile Ttclcl$Tcl)cc@)
*=/=2=* 'nter&retation of the Returne
>a#ues
In /ile nsallinoneJ1I3>Mtcl/I>I/M$enericMtclI(* NS2 de/ines /i1e
/ollowin' return 1alues ?as ,H3 in Pro'ram 3)"@* w&ic& in/orm t&e interreter o/
t&e OTcl command in1ocation result)
38 3 !inka'e +etween OTcl and CCC in NS2
2
Here* t&e ar$c is t&e number o/ nonemty element in ar$v)
Program *=7 (eturn 1alues in NS2
MMnsallinoneJ1I3>Mtcl/I>I/M$enericMtclI(
2 Ode"ine TCL5OV 0
1 Ode"ine TCL5E##O# 2
3 Ode"ine TCL5#ETD#N 1
= Ode"ine TCL5.#EAV 3
> Ode"ine TCL5CONTINDE =
TCL5OV< T&e command comletes success/ully)
TCL5E##O#< T&e command does not comlete success/ully) T&e interreter will
eAlain t&e reason /or t&e error)
TCL5#ETD#N< 4/ter returnin' /rom CCC* t&e interreter will eAit ?or return
/rom@ t&e current instroc wit&out er/ormin' t&e rest o/ instroc)
TCL5.#EAV< 4/ter returnin' /rom CCC* t&e interreter will break t&e current
loo) T&is is similar to eAecutin' t&e CCC keyword break* but t&e results
re1ail to t&e OTcl domain)
TCL5CONTINDE< 4/ter returnin' /rom CCC* t&e interreter will immediately
restart t&e loo) T&is is similar to eAecutin' t&e CCC keyword contin!e* but
t&e results re1ail to t&e OTcl domain)
4mon' t&ese /i1e tyes* TCL5OV and TCL5E##O# are t&e most common
ones) I/ CCC returns TCL5OV* t&e interreter may read t&e 1alue assed /rom t&e
CCC domain ?see Sect) 3)8)3@)
I/ an OTcl command returns TCL5E##O#* on t&e ot&er &and* t&e interreter
will in1oke rocedure tkerror ?de/ined in /ile TtclclMtclJobjectItcl@*
w&ic& s&ows an error on t&e screen* and eAits t&e ro'ram)
E%ample $** Consider in1ocation o/ an OTcl command associated wit& an
A$entMTCP obBect* Ptcp) T&e rocess roceeds as /ollows ?see also Ci') 3)3@<
1) EAecute an OTcl statement FPtcp <cmd5nameK <ar$sKG ?osition &2'
in Ci') 3)3@)
2) !ook /or an instroc <cmd5nameK in t&e OTcl class A$entMTCP) I/ /ound*
eAecute t&e instroc and comlete t&e rocess) Ot&erwise* roceed to t&e neAt
ste)
3) !ook /or an instroc !nkno,n/III' in t&e OTcl class A$entMTCP) I/
/ound* eAecute t&e instroc !nkno,n/III' and comlete t&e rocess)
Ot&erwise* roceed to t&e neAt ste)
:) (eeat stes ?2@ and ?3@ u t&e &ierarc&y until reac&in' t&e to le1el class in
t&e interreted &ierarc&y ?i)e)* SplitObject@)
3) T&e main statement o/ t&e instroc !nkno,n/III' o/ class SpiltObject
in Pro'ram 3)2 is FPsel" cmd Par$sG in !ine 2* w&ic& interolates to
Ptcp cmd <cmd5nameK ?<cmd5ar$sK@
3" 3 !inka'e +etween OTcl and CCC in NS2
4ig= *=* T&e internal rocess o/ OTcl command in1ocation
8) EAecute t&e /unction command&ar$c)ar$v' o/ class TcpA$ent* w&ere
ar$v?0@ and ar$v?2@ are cmd and <cmd5nameK* resecti1ely)
2) !ook /or t&e matc&in' number o/ ar'uments and OTcl command name)
I/ /ound* eAecute t&e desired actions ?e)')* !ines 8 and 2 in Pro'ram 3)8@ and
return TCL5OV)
3): EAecution o/ CCC Statements /rom t&e OTcl .omain 3#
") I/ no criterion matc&es wit& ?ar$c* ar$v@* ski to t&e de/ault returnin'
statement ?e)')* !ine 12 in Pro'ram 3)8@* mo1in' u t&e &ierarc&y and
eAecutin' t&e /unction command&III')
#) (eeat stes ?8@H?"@ u t&e comiled &ierarc&y until t&e criterion is matc&ed)
(e'ardless o/ ?ar$c)ar$v@* t&e to9le1el class TclObject in t&e
comiled &ierarc&y set t&e return 1alue to be TclJError* indicatin' t&at no
criteria alon' t&e entire &ierarc&ical tree matc&es wit& ?ar$c)ar$v@)
1,) (eturn down t&e comiled &ierarc&y) 6&en reac&in' CCC class TcpA$ent*
return to t&e OTcl domain wit& a return 1alue ?e)')* TCL5OV or
TCL5E##O#@) %o1e down t&e interreted &ierarc&y and carry t&e
returned 1alue to t&e caller)
".$." An Alternati#e for OTcl Coand In#ocation
In 'eneral* we in1oke an OTcl command by
eAecutin'
Pobj <cmd5nameK <ar$sK
w&ic& starts /rom osition &2' in Ci') 3)3) 4lternati1ely* we can also in1oke a
t&e command usin' t&e /ollowin' syntaA<
Pobj cmd <cmd5nameK <ar$sK
w&ic& starts /rom osition &1' in Ci') 3)3) T&is met&od eAlicitly tells NS2 t&at
<cmd5nameK is an OTcl command* not an instroc) T&is &els a1oid t&e
ambi'uity
w&en OTcl de/ines an instroc w&ose name is t&e same as an OTcl command
name)
".$.$ %on(OOP Tcl Coand
Non9OOP Tcl commands are 1ery similar to OOP Tcl command ?i)e)@ (Tcl
commands* discussed in t&e re1ious section) Howe1er* non9OOP Tcl command*
also known as Tcl commands* are not bound to any class)
".$.+ In#o'ing a TclCoand
4 TclCommand can be in1oked as i/ it is a 'lobal Tcl rocedure) Consider
t&e TclCommands nsJversion and nsJrandom* seci/ied in /ile
Tns$common$ misc)cc)
TclCommand nsJversion takes no ar'ument and returns t&e NS2
1ersion)
TclCommand nsJrandom returns a random number uni/ormly distributed in
Q,O 2
31
1 w&en no ar'ument is seci/ied) I/ an inut ar'ument is 'i1en* it will
3" 3 !inka'e +etween OTcl and CCC in NS2
be used to set t&e seed o/ t&e random number 'enerator)
3): EAecution o/ CCC Statements /rom t&e OTcl .omain 81
Program *=8 .eclaration and /unction command&III' o/ class
#andomJCommand
MMUnsMcommonMmiscIcc
2 class #andomCommand 9 p!blic TclCommand 7
1 p!blic9
3 #andomCommand&' 9 TclCommand&HnsJrandomH' 7 8
= virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
> 8;
A int #andomCommand99command&int ar$c) const c(ar
N
const
N
ar$v'
B 7
/ TclF tcl : Tcl99instance&';
G i" &ar$c :: 2' 7
20 sprint"&tclIb!""er&') HE!H) #andom99random&'';
22 tclIres!lt&tclIb!""er&'';
21 8 else i" &ar$c :: 1' 7
23 int seed : atoi&ar$v?2@';
2= i" &seed :: 0'
2> seed : #andom99seed5(e!ristically&';
2A else
2B #andom99seed&seed';
2/ tclIres!lt"&HEdH) seed';
2G 8
10 ret!rn &TCL5OV';
12 8
T&ese two TclCommands can be in1oked 'lobally) Cor eAamle*
KKnsJversion
1I3=
KKnsJrandom
B1G13A
KKnsJrandom
22G3B==B=B
+y eAecutin' nsJversion* t&e 1ersion ?2)3:@ o/ NS2 is s&own on t&e screen)
TclCommand nsJrandom wit& no ar'ument returns a random number)
*=/=0=% $reating a Tc#$omman
4 TclCommand creation rocess consists o/ declaration and imlementation) T&e
declaration is similar to t&at o/ a TclClass) 4 TclCommand is declared as a deri1ed
class o/ class TclCommand) T&e name o/ a TclCommand is ro1ided as an inut
ar'ument o/ class TclCommand ?see !ine 3 in Pro'ram 3)#@)
Similar to t&at o/ OTcl commands* t&e imlementation o/ Tcl commands is de9
/ined in /unction command&ar$c)ar$v' as s&own in !ines 8H21 o/ Pro'ram
3)#) Here* we only need to comare t&e number o/ inut ar'uments ?e)')* !ine #@*
since t&e name o/ t&e Tcl command was declared earlier)
8, 3 !inka'e +etween OTcl and CCC in NS2
Program *=%: Cunction misc init* w&ic& instantiates o/ TclCommands
MMUnsMcommonMmiscIcc
2 void init5misc&void'
1 7
3 &void'ne, SersionCommand;
= &void'ne, #andomCommand;
> III
A 8
In addition to t&e abo1e declaration and imlementation* we need to seci/y ac9
ti1e TclCommands in t&e /unction init5misc&' as s&own in Pro'ram 3)1,)
Here* eac& acti1e TclCommands is instantiated by t&e CCC statement F&void'
ne,
<TclCommandK)G 4t t&e startu time* NS2 in1okes t&e /unction init5misc
&III' /rom wit&in t&e /ile Ttclcl$tcl4Init)cc to instantiate all acti1e
TclCommands)
*=/=0=2 -efining @our ,wn Tc#$omman
To create a TclCommand* you need to
1) Pick a name* t&e number o/ inut ar'uments* and t&e class name /or your
TclCommand)
2) .eri1e a TclCommand class directly /rom class TclCommand*
3) Ceed t&e Tcl command name to t&e constructor o/ class TclCommand*
:) Pro1ide imlementation ?i)e)* desired actions@ in t&e /unction command
&III'* and
3) 4dd an obBect instantiation statement in t&e /unction init5misc&III')
E%ample $*2* !et t&e TclCommand printJallJar$s s&ow all inut ar'u9
ments on t&e screen) 6e can imlement t&is TclCommand by includin' t&e
/ollowin' codes to t&e /ile Tns$common$misc)cc<
class PrintAllAr$sCommand 9 p!blic TclCommand 7
p!blic9
PrintAllAr$sCommand&'9TclCommand&HprintJallJar$sH'
78;
int command&int ar$c) const c(ar
N
const
N
ar$v';
8
int PrintAllAr$sCommand99command&int ar$c)
const c(ar
N
const
N
ar$v' 7
co!t << HInp!t ar$!ments9 H
"or &int i : 2; i < ar$c; i44' 7
co!nt << ar$v?i@;
8
3)3 S&adow ObBect Construction Process 83
.omain 7ariable name Handle
CCC
OTcl
c5object
otcl5object
0*dA"Gc0
5o20
ret!rn &TCL5OV';
8
void init5misc&void'
7 III
&void'ne, PrintAllAr$sCommand;
III
8
*=0 Shaow ,b1ect $onstruction Process
NS2 automatically constructs a s&adow comiled obBect w&en an OTcl obBect is
created /rom t&e interreted &ierarc&y) T&is section demonstrates t&e s&adow
obBect construction rocess) T&e rocess is de/ined in t&e to le1el classes in bot&
t&e &ier9 arc&ies H namely classes TclObject and SplitObject) Howe1er*
t&rou'&out t&is book* we s&all re/er to t&e obBects instantiated /rom t&ese two
&ierarc&ies as TclObBects) T&e term SlitObBect s&all be used w&en a clear
di//erentiation /or bot& t&e &ierarc&ies is needed)
".+.1 A 7andle of a TclO-8ect
4 &andle is a re/erence to an obBect) 4s a comiler* CCC directly accesses t&e
memory sace allocated /or a certain obBect ?e)')* 0*dA"Gc0@) 4 &andler in CCC
is a ointer or a re/erence 1ariable to t&e obBect) OTcl* on t&e ot&er &and* uses a
strin' ?e)')* 5o20@ as a re/erence to t&e obBect) +y con1ention* t&e name strin' o/
a SlitObBect is o/ /ormat 5<NNNK* w&ere <NNNK is a number uniDuely
'enerated /or eac& SlitObBect)
E%ample $*$* !et 1ariables c5obj and otcl5obj contains CCC and OTcl
obBects* resecti1ely) Table 3): s&ows eAamles o/ t&e re/erence 1alue o/ CCC
and OTcl obBects)
Tab#e *=/ EAamles o/
re/erence to ?or &andle o/@
TclObBects
82 3 !inka'e +etween OTcl and CCC in NS2
6e can see t&e 1alue o/ an OTcl obBect stored in an OTcl 1ariable by runnin' t&e
/ollowin' codes<
MMtestItcl
set ns ?ne, Sim!lator@
set tcp ?ne, A$entMTCP@
p!ts HT(e val!e o" tcp is PtcpH
w&ic& s&ow t&e /ollowin' line on t&e screen<
KKns testItcl
T(e val!e o" tcp is 5o20
".+.2 TclO-8ects Constr!ction Process
In 'eneral* an OTcl obBect can be created and stored in a 1ariable Pvar usin' t&e
/ollowin' syntaA<
<classnameK create Pvar ?<ar$sK@
w&ere <classnameK ?mandatory@ and <ar$sK ?otional@ are t&e class name
and t&e list o/ inut ar'uments /or t&e class constructor* resecti1ely)
T&is 'eneral OTcl obBect construction aroac& is not widely used in NS2*
since it does not create s&adow obBects) NS2 uses t&e /ollowin' statement to
create an obBect /rom an interreted &ierarc&y<
ne, <classnameK <ar$sK
T&is section /ocuses on &ow t&e 'lobal rocedure Fne,G automatically creates
a s&adow obBect) 6e s&all use t&e OTcl class A$entMTCP* bound to t&e CCC
class TcpA$ent in t&e CCC comiled &ierarc&y* as an eAamle to /acilitate t&e
eAlanation)
T&e TclObBect construction rocess consists o/ two main arts<
Part ' A,Tc# -omainB2 S&#it,b1ect $onstruction
T&e main stes in t&is art are to eAecute t&e /ollowin' OTcl statements and
instrocs in seDuence ?see also Ci') 3):@<
I)1) T&e OTcl statement ne, <classnameK ?<ar$sK@
I)2) T&e OTcl statement Pclassname create Po Par$s
I)3) T&e instroc alloc o/ t&e OTcl class <classnameK
I):) T&e instroc init o/ t&e OTcl class <classnameK
I)3) T&e instroc init o/ t&e OTcl class SplitObject
I)8) T&e OTcl statement Psel" createJs(ado, Par$s
3)3 S&adow ObBect Construction Process 83
4ig= *=/ 4n eAamle o/ t&e s&adow obBect construction rocess< %ain stes in t&e constructor o/
class A$entMTCP
4/ter t&ese stes are comlete* t&e constructed TclObBect are returned to t&e caller)
In most cases* t&e returned obBect is stored in a local 1ariable ?e)')* Pvar@)
T&e details o/ t&e abo1e siA main stes are as /ollows) Consider Pro'ram 3)11
/or
t&e 'lobal rocedure Fne,/className ar$s'G ?Ste I)1@) !ine 2 retrie1es t&e
re/erence strin' /or a SlitObBect usin' t&e instroc $etid/' o/ class
SplitObject) T&e strin' is t&en stored in t&e 1ariable FPo)G !ine 3 creates an
obBect w&ose OTcl class is PclassName and associates t&e created obBect wit&
t&e strin' stored in FPoG ?Ste I)2@) Cinally* i/ t&e obBect is success/ully created*
!ine 11 returns t&e re/erence strin' FPoG to t&e caller)
"
Ot&erwise* an error
messa'e ?!ine
#@ will be s&own on t&e screen)
4s discussed in Sect) 4)2):* t&e instroc create in !ine 3 in1okes t&e
inst9 roc alloc/III' ?Ste I)3@ to allocate a memory sace /or an obBect o/
class className* and t&e instroc init/III' ?Ste I):@ to initialiJe t&e obBect)
T&e /inal two stes are eAlained t&rou'& class A$entMTCP) Pro'ram 3)12
s&ows t&e details o/ constructors o/ OTcl classes A$entMTCP and
SplitObject) T&e instroc ne*t/III' in !ine 2 in1okes t&e instroc wit& t&e
same name ?i)e)* init in t&is case@ o/ t&e arent class) T&e in1ocation o/
instroc init t&ere/ore kees mo1in' u t&e &ierarc&y until it reac&es t&e to9
le1el class SplitObject
"
Note t&at !ine 11 returns a re/erence strin' stored in Po* not t&e 1ariable Po)
8: 3 !inka'e +etween OTcl and CCC in NS2
Program *=%% Llobal instance rocedures ne, and delete
MMUtclclMtclJobjectItcl
2 proc ne, 7 className ar$s 8 7
1 set o ?SplitObject $etid@
3 i" ?catc( HPclassName create Po Par$sH ms$@ 7
= i" ?strin$ matc( H QAILED5SHADOW5O.RECT5H Pms$@ 7
> delete Po
A ret!rn HH
B 8
/ $lobal errorIn"o
G error Hclass PclassName9 constr!ctor "ailed9
Pms$H PerrorIn"o
20 8
22 ret!rn Po
21 8
23 proc delete o 7
2= Po delete5tkvar
2> Po destroy
2A 8
?see !ines 8H11 in Pro'ram 3)12@) Here* t&e instroc createJs(ado, in !ine
" marks t&e be'innin' o/ t&e CCC s&adow obBect construction rocess* w&ic& will
be discussed in Part II) 4/ter constructin' t&e s&adow obBect* t&e rocess returns
down t&e &ierarc&y tree* er/orms t&e rest o/ t&e initialiJation in instrocs init
?e)')* o/ class A$entMTCP@* and returns t&e constructed obBect to t&e caller)
Program *=%2 T&e constructor o/ OTcl classes A$entMTCP and SplitObject
MMUnsMtclMlibMnsJa$entItcl
2 A$entMTCP instproc init 78 7
1 eval Psel" ne*t
3 set ns ?Sim!lator instance@
= Pns createJeventtrace Event Psel"
> 8
MMUtclclMtclJobjectItcl
A SplitObject instproc init ar$s 7
B Psel" ne*t
/ i" ?catc( HPsel" createJs(ado, Par$sH@ 7
G error H QAILED5SHADOW5O.RECT5H HH
20 8
22 8
3)8 4ccess t&e OTcl .omain /rom t&e CCC .omain 82
4ig= *=0 T&e s&adow obBect creation rocess< %o1in' /rom t&e OTcl domain to t&e CCC
domain t&rou'& t&e OTcl command createJs(ado, o/ class A$entMTCP
Part '' A$CC -omainB2 Shaow ,b1ect $onstruction
Continuin' /rom Ste 8 in Part I* t&e main stes in t&is art are to eAecute t&e
/ollowin' CCC statements and /unctions in seDuence ?see also Ci') 3):@<
II)1) Ste 8 in Part I
II)2) T&e CCC /unction createJs(ado,&III' o/ class TclClass
II)3) T&e CCC /unction create&III' o/ class TcpClass
II):) T&e CCC statement ne, TcpA$ent&'
II)3) 4ll related CCC constructors o/ t&e class TcpA$ent
4/ter all t&e abo1e stes* t&e constructed s&adow obBect is returned to t&e caller in
t&e OTcl domain)
T&e details o/ Part II are as /ollows) T&e /irst ste in Part II is to eAecute
t&e /ollowin' OTcl statement /rom wit&in t&e instroc init o/ t&e OTcl class
SplitObject<
Psel" createJs(ado, Par$s
w&ere Psel" is an OTcl obBect w&ose class is A$entMTCP)
It is &ere w&ere NS2 mo1es /rom t&e OTcl domain to t&e CCC domain) Crom
Ci') 3)3* t&e OTcl command createJs(ado, ?Ste II)1@ o/ class A$entMTCP
is bound to t&e CCC /unction create5s(ado,&' o/ class
TclClass
88 3 !inka'e +etween OTcl and CCC in NS2
?Ste II)2@) Crom wit&in t&e /unction create5s(ado,&'* t&e statement
FpJKcreate&III'G is eAecuted* w&ere FpG is a ointer to a TcpClass
obBect ?Ste II)3@) Crom !ines :H8 o/ Pro'ram 3):* t&e /unction create&III'
eAecutes t&e CCC statement ne, TcpA$ent&' to create a s&adow TcpA$ent
obBect ?Ste II):@) Here* all t&e constructors alon' t&e class &ierarc&y are in1oked
?Ste II)3@) Cinally* t&e created obBect is returned down t&e &ierarc&y back to t&e
caller)
".+." TclO-8ects )estr!ction Process
TclObBect destruction is t&e re1erse o/ t&e TclObBect construction) It destroys
obBects in bot& t&e CCC and OTcl domains* and returns t&e memory allocated to
t&e obBects to t&e system* usin' a 'lobal rocedure delete/III') Crom Pro'ram
3)11* !ines
1: and 13 destroy t&e obBects in t&e OTcl and CCC domains*
resecti1ely)
In most cases* we do not need to eAlicitly destroy obBects* since t&ey are
automatically destroyed w&en t&e simulation terminates) Howe1er* obBect destruc9
tion is a 'ood ractice to re1ent memory leak) 6e destroy obBect w&en it is no
lon'er in need) Cor eAamle* t&e instroc !seJsc(ed!ler o/ t&e OTcl class
Sim!lator eAecutes Fdelete Psc(d!ler5 be/ore creatin' a new one
?see /ile Tns$tcl$lib$ns9lib)tcl@)
*=6 Access the ,Tc# -omain from the $CC -omain
T&is section discusses t&e /ollowin' main oerations /or accessin' t&e OTcl
domain /rom t&e CCC domain
#
<
1) Obtain t&e re/erence to t&e Tcl interreter ?usin' t&e CCC /unction
instance&'@*
2) EAecute t&e OTcl statements /rom wit&in t&e CCC domain ?usin' t&e CCC
/unctions eval&III'* evalc&III'* and eval"&III'@*
3) Pass or recei1e results to$/rom t&e OTcl domain ?usin' t&e CCC /unctions
res!lt&III' and res!lt"&III'@* and
:) (etrie1e t&e re/erence to TclObBects ?usin' t&e CCC /unctions enter&III'*
delete &III'* and look!p&III'@)
#
See t&e details in t&e /ile TtclclMTclIcc)
3)8 4ccess t&e OTcl .omain /rom t&e CCC .omain 8#
"./.1 O-tain a Reference to the Tcl Interpreter
In OOP* a ro'rammer would ask an obBect to take actions) 6it&out an obBect* no
action s&all be taken) In t&is section* we s&all demonstrate &ow NS2 asks t&e Tcl
interpreter ?i)e)* obBect@ to take actions)
NS2 obtains a CCC obBect w&ic& reresents t&e Tcl interreter usin' t&e
/ollowin' CCC statement<
TclF tcl : Tcl99instance&';
w&ere t&e /unction instance&' o/ class Tcl returns t&e 1ariable
instance5 o/ class Tcl w&ic& is a re/erence to t&e Tcl interreter) 4/ter
eAecutin' t&e abo1e statement* we er/orm t&e abo1e oerations t&rou'& t&e
obtained re/erence ?e)')* tclIeval&III'* tclIres!lt&III'@)
"./.2 *1ec!tion of Tcl Stateents
Class Tcl ro1ides t&e /ollowin' /our /unctions to eAecute Tcl
statements<
Tcl99eval&c(ar
N
str'< EAecutes t&e strin' stored in a 1ariable FstrG in
t&e OTcl domain)
Tcl99evalc&const c(ar
N
str'< EAecutes t&e strin' FstrG in t&e OTcl
domain)
Tcl99eval&'< EAecutes t&e strin' w&ic& &as already been stored in t&e
internal 1ariable bp5)
Instroc Tcl99eval"&const c(ar
N
"mt)III@< 0ses t&e /ormat F"mtG
o/ print"&III' in CCC to /ormulate a strin'* and eAecutes t&e /ormulated
strin')
E%ample $*/* T&e /ollowin's s&ow 1arious ways in CCC* w&ic& tell t&e Tcl
interreter to rint out FOverall Packet Delay is 20I0 secondsG on
t&e screen)
TclF tcl : Tcl99instance&';
MM Dsin$ eval&III'
tclIeval&Hp!ts ?Overall Packet Delay is 20I0
seconds@H';
MM Dsin$ evalc&III'
c(ar s?21/@;
strcpy&s)Hp!ts ?Overall Packet Delay is 20I0
seconds@H';
tclIevalc&s';
MM Dsin$ eval&'
8" 3 !inka'e +etween OTcl and CCC in NS2
c(ar s?21/@;
sprint"&tclIb!""er&')Hp!ts ?Overall
Packet Delay is 20I0 seconds@H';
tclIeval&';
MM Dsin$ eval"&III'
"loat delay : 20I0;
tclIeval"&Hp!ts ?Overall
Packet Delay is E1I2" seconds@H)
delay';
Note t&at tcl99b!""er&' returns t&e internal 1ariable bp5)
"./." Pass or Recei#e Res!lts to/fro the Interpreter
*=6=*=% Passing Resu#ts to the ,Tc# -omain
Class Tcl ro1ides two /unctions to pass results to t&e OTcl
domain<
Tcl99res!lt&const c(ar
N
str'< Passes t&e strin' <strK as t&e
result to t&e interreter)
Tcl99res!lt"&const c(ar
N
"mt)III'< 0ses t&e /ormat F"mtGo/
print" &III' in CCC to /ormulate a strin'* and asses t&e /ormulated
strin' to t&e interreter)
E%ample $*1* !et an OTcl command ret!rn20 o/ class %yObject returns
t&e 1alue F1,G to t&e interreter) T&e imlementation o/ t&e OTcl command
ret!rn20 is 'i1en below<
int %yObject99command&int ar$c) const c(ar
N
const
N
ar$v'
7
TclF tcl : Tcl99instance&';
i" &ar$c :: 1' 7
i" &strcmp&ar$v?2@) Hret!rn20H' :: 0' 7
TclF tcl:Tcl99instance&';
tclIres!lt&H20H';
ret!rn TCL5OV;
8
8
ret!rn &NsObject99command&ar$c) ar$v'';
8
3)8 4ccess t&e OTcl .omain /rom t&e CCC .omain 21
Crom OTcl* t&e /ollowin' statement stores t&e 1alue returned /rom t&e OTcl
command Fret!rn20 o/ t&e CCC obBect w&ose class is %yObject in t&e
OTcl 1ariable FvalG)
set obj ?ne, %yObject@
set val ?Pobj ret!rn20@

E%ample $*8* !et an OTcl command ret!rnSal o/ class %yObject return
t&e 1alue stored in t&e CCC 1ariable Fval!eG to t&e interreter) T&e
imlementation o/ t&e OTcl command ret!rnSal is 'i1en below<
int %yObject99command&int ar$c) const c(ar
N
const
N
ar$v'
7
TclF tcl : Tcl99instance&';
i" &ar$c :: 1' 7
i" &strcmp&ar$v?2@) Hret!rnSalH' :: 0' 7
tclIres!lt"&HE2I2"H)val!e';
TclF tcl:Tcl99instance&';
ret!rn TCL5OV;
8
8
ret!rn &NsObject99command&ar$c) ar$v'';
8
T&e OTcl command ret!rnSal can be in1oked as /ollows<
set obj ?ne, %yObject@
set val ?Pobj ret!rnSal@
*=6=*=2 Retrieving Resu#ts from the ,Tc# -omain
Class Tcl ro1ides one /unction to receive results from t&e OTcl domain<
Tcl99res!lt&void'< (etrie1es t&e result /rom t&e interreter as a strin')
E%ample $*9* T&e /ollowin' statements stores t&e 1alue o/ t&e OTcl 1ariable
FvalG in t&e CCC 1ariable Fval!eG<
TclF tcl:Tcl99instance&';
tclIevalc&Hset valH';
c(ar
N
val!e : tclIres!lt&';

Class Tcl uses a ri1ate member 1ariable Ftcl5JKres!ltG to ass results
between t&e two &ierarc&ies* w&ere Ftcl5G is a ointer to a Tcl5Interp
obBect) 6&en assin' a result 1alue to t&e OTcl domain* t&e /unction
res!lt&III' stores
2, 3 !inka'e +etween OTcl and CCC in NS2
t&e result in t&is 1ariable) T&e Tcl interreter is resonsible /or readin' t&e result
1alue /rom t&e 1ariable Ftcl5JKres!lt)G On t&e ot&er &and* w&en assin' a
result 1alue to t&e CCC domain* t&e interreter stores t&e 1alue in t&e same CCC
1ariable* and t&e /unction res!lt&' reads t&e 1alue stored in t&is 1ariable)
"./.$ TclO-8ect Reference Retrie#al
(ecall t&at an obBect in t&e interreted &ierarc&y always &as a s&adow comiled
obBect) NS2 records an association o/ a air o/ obBects as an entry in its &as&
table)
1,
Class Tcl ro1ides t&e /ollowin' t&ree /unctions to deal wit& t&e &as&
table<
Cunction enter&TclObject
N
o'< Inserts a TclObBect F
N
oG into t&e &as&
table* and associates F
N
oG wit& t&e OTcl name strin' stored in t&e 1ari9
able Fname5G o/ t&e TclObBect F
N
o)G T&is /unction is in1oked by /unction
TclClass9create5s(ado,&III ' w&en a TclObBect is created)
Cunction delete&TclObject
N
o'< .eletes t&e entry associated wit& t&e
TclObBect F
N
oG /rom t&e &as& table) T&is /unction is in1oked by /unction
TclClass9delete5s(ado,&III' w&en a TclObBect is destroyed)
Cunction look!p&c(ar
N
str'< (eturns a ointer to t&e TclObBect w&ose
name is Fstr)G
E%ample $*:* Consider t&e OTcl command tar$et/III' o/ t&e CCC class
Connector in Pro'ram 3)13) T&is OTcl command sets t&e inut ar'ument as
t&e /orwardin' NsObBect ?see t&e details in Sect) 3)3@)
Program *=%* Cunction command&III' o/ t&e C>> class Connector
MMUnsMcommonMconnectorIcc
2 int Connector99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 TclF tcl : Tcl99instance&';
= III
> i" &ar$c :: 3' 7
A i" &strcmp&ar$v?2@) Htar$etH' :: 0' 7
B III
/ tar$et5 : &NsObject
N
'TclObject99look!p&ar$v?1@';
G III
20 8
22 III
21 8
23 ret!rn &NsObject99command&ar$c) ar$v'';
2= 8
1,
T&e de/inition o/ a &as& table is 'i1en in Sect) 8)2)3)
3)# EAercises 23
Here* Far$v?1@G is t&e /orwardin' obBect assed /rom t&e OTcl domain) !ine
" eAecutes TclObject99look!p&ar$v?1@' to retrie1e t&e s&adow
comiled
obBect ointer corresondin' to t&e OTcl obBect Far$v?1@)G T&e retrie1ed ointer
is con1erted to a ointer to an obBect w&ose tye is NsObject and stored in t&e
1ariable Ftar$et5)G
*=5 Trans#ation of Tc# $oe
In 'eneral* Tcl is an interreted ro'rammin' lan'ua'e) It does not reDuire
comilation be/ore eAecution) Howe1er* durin' t&e comilation* NS2 translates all
built9in Tcl modules ?e)')* all t&e scrit /iles in directory Tns$tcl$lib@ into t&e CCC
lan'ua'e usin' class EmbeddedTcl* to seed u t&e simulation)
T&e comilation rocess is carried out accordin' to t&e /ile descritor* %ake
"ile ?see Sect) 2)2@) T&e statement related to Tcl translation
is
P&TCLSH' binMtclJe*pandItcl tclMlibMnsJlibItcl P&NS5
TCL5LI.5STL' T
X P&TCL1C' et5ns5lib K $enMns5tclIcc
w&ere P&TCLSH' is t&e eAecutable /ile w&ic& in1okes t&e Tcl intererter* P
&TCL
1C' is a Tcl scrit w&ic& translates Tcl codes to CCC codes* and P
&NS5TCL5LI.
5STL' are t&e list o/ Tcl /iles w&ic& will be translated to CCC
ro'rams)
T&e abo1e statement &as two arts* eac& di1ided by a ieline FXG oerator)
11
4irst Part2 "<&ansion
T&e /irst art is s&own below<
P&TCLSH' binMtclJe*pandItcl tclMlibMnsJlibItcl
P&NS5TCL5LI.5STL'
T&is art asks t&e Tcl to interret ?i)e)* run@ t&e Tcl scrit /ile binMtclJ
e*pandItcl* wit& two inut ar'uments< Tns$tcl$lib$ns9lib)tcl and P&NS5TCL5
LI.5STL') It eAands t&e content o/ all t&e /iles seci/ied in t&e inut ar'uments)
4 art o/ t&e eAansion is to source t&e Tcl /iles seci/ied in t&e inut /iles) +y
sourcin' a Tcl /ile* we mean to relace a source statement wit& t&e /ollowin'
syntaA
so!rce <"ilenameK
11
T&e ieline oerator catures t&e screen outut ?i)e)* stdo!t@ resultin' /rom t&e eAecution o/
22 3 !inka'e +etween OTcl and CCC in NS2
w&at a&ead o/ it) T&e catured strin' is t&en /ed as a keyboard inut ?i)e)* stdin@ /or t&e
eAecution o/ w&at /ollowin' it)
3)# EAercises 23
wit& t&e content in t&e /ile <"ilenameK) EAamle source statements are in t&e
/ile
Tns$tcl$lib$ns9lib)tcl<
so!rce nsJa!tocon"Itcl
so!rce nsJaddressItcl
so!rce nsJnodeItcl
so!rce nsJrtmod!leItcl
III
w&ic& tell NS2 to incororate t&ese /iles into t&e translation
rocess)
Secon Part2 Trans#ation
T&e second art is located be&ind t&e ie oerator ?FXG@*
i)e)*
P&TCL1C' et5ns5lib K $enMns5tclIcc
T&e statement FP&TCL1C' et5ns5libG translates t&e OTcl scrits /rom t&e
/ormer art into CCC ro'rams usin' an EmbeddedTcl obBect
Fet5ns5lib)G T&e outut o/ t&e second art is t&e CCC ro'rams* w&ic& are
redirected usin' a redirection oerator ?i)e)* FKG@* to t&e CCC /ile
$enMns5tclIcc)
*=7 $ha&ter Summary
NS2 is a network simulator tool consistin' o/ OTcl and CCC ro'rammin'
lan'ua'es) T&e main oerations o/ NS2 ?e)')* acket assin'@ are carried out usin'
t&e C>> lan'ua'e* w&ile t&e network con/i'uration rocess ?e)')* creatin' and
connectin' nodes@ is carried out usin' t&e OTcl lan'ua'e) In most cases* ro'ram9
mers create obBect /rom t&e OTcl domain* and NS2 automatically creates shadow
obBect in t&e CCC domain) T&e connection between t&e interreted and comiled
&ierarc&ies is establis&ed t&rou'& TclC!) In t&is c&ater* we &a1e discussed t&e
main /unctionalities o/ TclC! H includin' class bindin'* 1ariable bindin'* met&od
bindin'* s&adow obBect construction rocess* Tcl access mec&anism* and Tcl code
translation)
*=8 "<ercises
1) (ewrite t&e ro'ram in Sect) 1)3 usin' t&ree CCC ro'rammin' styles dis9
cussed in Sect) 3)1)
2) T&e class bindin' rocess consists o/ /our maBor comonents)
2: 3 !inka'e +etween OTcl and CCC in NS2
a) 6&at are t&ose comonentsR 6&at are t&eir de/initionsR
b) !ook into t&e NS2 codes) 6&at are t&e comonents corresondin' to t&e
/ollowin' classes< #enoTcpA$ent* A$ent* Connector)
c) +ind a CCC class %yObject to an OTcl class %yOTclClass) 6&at are
t&e main class bindin' comonentsR Comile and run t&e codes) 7eri/y t&e
bindin' by rintin' out a strin' /rom t&e constructor o/ t&e CCC class)
.iscuss t&e results)
3) Consider EAercise 2)
a) Create an OTcl command named FprintJco!ntG w&ic& rint out t&e
1alue o/ co!nt5 on t&e screen) 6rite a Tcl simulation scrit to test t&e
OTcl command)
b) Create an instroc FprintJco!ntG /or t&e class %yOTclObject) I/
you eAecute FprintJco!nt*G w&ic& body o/ FprintJco!ntG will NS2
eAecute ?i)e)* t&e OTcl command or t&e instroc@R .esi'n an eAeriment to
test your answer) Can you make NS2 to eAecute t&e ot&er bodyR I/ so*
&owR
:) Consider EAercise 2)
a) .eclare a 1ariable my5c5var5 and an inst1ar my5otcl5var5 in
classes
%yObject and %yOTclObject) +ind t&em to'et&er)
b) .esi'n an eAeriment to s&ow t&at a c&an'e in one 1ariable automatically
udates t&e 1alue o/ t&e ot&er 1ariable)
c) How would you de/ine t&e de/ault 1alue o/ a 1ariable in CCC and OTcl
domainR I/ t&e de/ault 1alues are di//erent* w&ic& one would be taken
durin' run timeR .esi'n an eAeriment to ro1e your answer)
3) 6&at are t&e maBor di//erences amon' classes TclObject* TclClass* and
InstSarR EAlain t&eir roles durin' an obBect creation rocess)
8) 6&at are t&e di//erences amon' a CCC /unction* an OTcl instroc* and an
OTcl commandR
2) 6&at are t&e di//erences between /unctions eval&III' and evalc&III'R
") S&ow a CCC statement to retrie1e a Tcl interreter)
#) T&e C>> class TcpA$ent is bound to t&e OTcl class A$entMTCP) T&e
CCC
1ariable Fc,nd5G bound to t&e OTcl Fc,nd5G inst1ar are used to store t&e
con'estion window 1alue)
a) .emonstrate &ow to set t&e de/ault con'estion window o/ TCP in t&e CCC
domain to be 2, and in t&e OTcl domain to be 3,) I/ you set t&e de/ault
1alue in bot& t&e CCC and OTcl domains* w&at would be t&e actual
de/ault 1alue at run timeR
b) S&ow di//erent ways in t&e OTcl domain to c&an'e t&e con'estion window
1alue o/ an A$entMTcp obBect Ptcp to :,)
1,) Can you er/orm t&e /ollowin' actionsR I/ not* w&at are t&e conditions under
w&ic& you can er/orm suc& actions)
3)# EAercises 23
a) +ind 4N; CCC 1ariable to 4N; OTcl 1ariable)
b) Call 4N; CCC statement /rom t&e OTcl domain)
c) Call 4N; OTcl statement /rom t&e CCC domain)
11) 6&at are t&e to9le1el classes in t&e CCC domain and in t&e OTcl domainR
$ha&ter /
'm&#ementation of -iscrete."vent Simu#ation
in NS2
NS2 is a e1ent9dri1en simulator* w&ere actions are associated wit& e1ents rat&er
t&an time) 4n e1ent in a e1ent9dri1en simulator consists o/ eAecution time*
associated actions* and a re/erence to t&e neAt e1ent ?Ci') :)1@) T&ese e1ents
connect to eac& ot&er and /orm a chain of events on t&e simulation timeline ?e)')*
t&at in Ci') :)1@) 0nlike a time9dri1en simulator* in an e1ent9dri1en simulator* time
between a air o/ e1ents does not need to be constant) 6&en t&e simulation starts*
e1ents in t&e c&ain are eAecuted /rom le/t to ri'&t ?i)e)* c&ronolo'ically@)
1
In t&e
neAt section* we will discuss t&e simulation concet o/ NS2) In Sects) :)2H:):* we
will eAlain t&e details o/ classes Event and Handler* class Sc(ed!ler*
and class Sim!lator* resecti1ely) Cinally* we summariJe t&is c&ater in Sect)
:)3)
/=% NS2 Simu#ation $once&t
NS2 simulation consists o/ two maBor &ases)
Phase '2 Network $onfiguration Phase
In t&is &ase* NS2 constructs a network and sets u an initial c&ain o/ e1ents)
T&e initial c&ain o/ e1ents consists o/ e1ents t&at are sc&eduled to occur at certain
times ?e)')* start CTP ?Cile Trans/er Protocol@ tra//ic at 1 s@) T&ese e1ents are called
at)events ?see Sect) :)2@) T&is &ase corresonds to e1ery line in a Tcl simulation
scrit be/ore eAecutin' instroc r!n/' o/ t&e Sim!lator obBect)
1
+y eAecution* we mean takin' actions associated wit& an e1ent)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* 22
.OI 1,)1,,2$#2"919:81:91:,893 :* = Srin'er Science>+usiness %edia* !!C 2,12
2" : Imlementation o/ .iscrete9E1ent Simulation in NS2
create
e(ent
insert
e(ent
+(ent%
time @ 3:A
,ction%
+(ent1
time @ !:B
,ction1
1
+(ent2
time @ 2:2
,ction2
2 3
+(ent3
time @ %
,ction3
4 %
+(ent4
time @ &:
,ction4
& A
'ime
(second)
4ig= /=% 4 samle c&ain o/ e1ents in a e1ent9dri1en simulation) Eac& e1ent contains eAecution
time and a re/erence to t&e neAt e1ent) In t&is /i'ure* E1ent 1 creates and inserts E1ent 3 a/ter
E1ent 2 ?t&e eAecution time o/ E1ent 3 is at 3)2 s@
Phase ''2 Simu#ation Phase
T&is art corresonds to a sin'le line* w&ic& in1okes t&e instroc r!n/' o/ class
Sim!lator) Ironically* t&is sin'le line contributes to most ?e)')* ##P@ o/ t&e
simulation)
In t&is art* NS2 mo1es alon' t&e c&ain o/ e1ents and eAecutes e1ents
c&ronolo'9 ically) Here* t&e instroc r!n/' starts t&e simulation by dispatching
t&e /irst e1ent in t&e c&ain o/ e1ents) In NS2* Fdisatc&in' an e1entG or F/irin' an
e1entG means Ftakin' actions corresondin' to t&at e1ent)G 4n action is* /or
eAamle* startin' CTP tra//ic or creatin' anot&er e1ent and insertin' t&e created
e1ent into t&e c&ain o/ e1ents) In Ci') :)1* at ,)# s* E1ent1 creates E1ent3 w&ic&
will be disatc&ed at 3)2 s* and inserts E1ent3 a/ter E1ent2) 4/ter disatc&in' an
e1ent* NS2 mo1es down t&e c&ain and disatc&es t&e neAt e1ent) T&is rocess
reeats until t&e last e1ent in t&e c&ain is disatc&ed* si'ni/yin' t&e end o/
simulation)
/=2 "vents an Han#ers
$.2.1 An O#er#ie& of *#ents and 7andlers
4s s&own in Ci') :)1* an e1ent is associated wit& an action to be taken at a
certain time) In NS2* an e1ent contains a handler t&at seci/ies t&e action* and t&e
firing time or dispatching time) Pro'ram :)1 s&ows declaration o/ classes Event
and Handler) Class Event declares 1ariables F(andler5G ?w&ose class is
HandlerO !ine 3@ and Ftime5G ?!ine 8@ as its associated &andler and /irin' time*
resecti1ely) To maintain t&e c&ain o/ e1ents* eac& Event obBect contains
ointers Fne*t5G ?!ine 3@ and Fprev5G ?!ine :@ to t&e neAt and re1ious
Event obBects* resecti1ely) T&e 7ariable F!id5G ?!ine 2@ is an I. uniDue to
e1ery e1ent)
Program /=% .eclaration o/ classes Event and
Handler
MMUMnsMcommonMsc(ed!lerI(
2 class Event 7
1 p!blic9
3 Event
N
ne*t5; M
N
event list
N
M
= Event
N
prev5;
> Handler
N
(andler5; M
N
(andler to call ,(en event ready
N
M
A do!ble time5; M
N
time at ,(ic( event is ready
N
M
B sc(ed!ler5!id5t !id5; M
N
!ni+!e ID
N
M
/ Event&' 9 time5&0') !id5&0' 78
G 8;
20 class Handler 7
22 p!blic9
21 virt!al UHandler &' 78
23 virt!al void (andle&Event
N
e' : 0;
2= 8;
Program /=2 Cunction (andle o/ class NsObject
MMUMnsMcommonMobjectIcc
2 void NsObject99(andle&Event
N
e'
1 7
3 recv&&Packet
N
'e';
= 8
!ines 1,H1: in Pro'ram :)1 s&ow t&e declaration o/ an abstract class
Handler) Class Handler seci/ies t&e default action to be taken w&en an
associated e1ent is disatc&ed in its ure 1irtual /unction (andle&e' ?!ine
13@)
2
T&is declaration /orces all its instantiable deri1ed classes to ro1ide t&e
action in /unction (andle&e') In t&e /ollowin's* we will discuss /ew classes
w&ic& deri1e /rom classes Event and Handler) T&ese classes are NsObject*
Packet* AtEvent* and AtHandler)
$.2.2 Class NsObject9 A Child Class of Class Handler
.eri1ed /rom class Handler* class NsObject is one o/ t&e main classes in
NS2) It is a base class /or most o/ network comonents) 6e will discuss t&e
details o/ t&is class in C&a) 3) Here* we only s&ow t&e imlementation o/ t&e
/unction (andle&e' o/ class NsObject in Pro'ram :)2) T&e /unction
(andle&e' casts an Event obBect associated wit& t&e inut ointer ?e@ to a
Packet obBect)
2
6e call actions seci/ied in t&e /unction (andle&e' default actions* since t&ey are taken
by de/ault w&en t&e associated e1ent is disatc&ed)
", : Imlementation o/ .iscrete9E1ent Simulation in NS2
Program /=* .eclaration o/ classes AtEvent and AtHandler* and /unction
(andle o/ cla ss AtHandler
MMUMnsMcommonMsc(ed!lerIcc
2 class AtEvent 9 p!blic Event 7
1 p!blic9
3 AtEvent&' 9 proc5&0' 7
= 8
> UAtEvent&' 7
A i" &proc5' delete ?@ proc5;
B 8
/ c(ar
N
proc5;
G 8;
20 class AtHandler 9 p!blic Handler 7
22 p!blic9
21 void (andle&Event
N
event';
23 8 at5(andler;
2= void AtHandler99(andle&Event
N
e'
2> 7
2A AtEvent
N
at : &AtEvent
N
'e;
2B Tcl99instance&'Ieval&atJKproc5';
2/ delete at;
2G 8
T&en it /eeds t&e casted obBect to t&e /unction recv&p' ?!ine 3@) 0sually*
/unction recv&p'* w&ere FpG is a ointer to a acket* indicates t&at t&e
NsObject &as recei1ed a acket FpG ?see C&a) 3@) 0nless o1erridden* by
deri1ed classes* t&e /unction (andle&e' o/ an NsObBect simly indicates
acket recetion)
$.2." Classes Packet and AtEvent9 Child Classes of
Class
Event
Classes Packet and AtEvent are amon' key NS2 classes w&ic& deri1e
/rom class Event) T&ese two classes can be laced on t&e c&ain o/ e1ents so t&at
t&eir associated &andler will take actions at t&e /irin' time) 6&ile t&e details o/
class AtEvent are discussed in t&is section* t&at o/ class Packet will be
discussed later in C&a) ")
.eclared in Pro'ram :)3* class AtEvent reresents e1ents w&ose action is
t&e eAecution o/ an OTcl statement) It contains one strin' 1ariable Fproc5G
?!ine "@ w&ic& &olds an OTcl statement strin') 4t t&e /irin' time* t&e associated
&andler* w&ose class is AtHandler* will retrie1e and eAecute t&e OTcl strin'
/rom t&is 1ariable)
:)2 E1ents and Handlers "1
Program /=/ Instance rocedure at o/ class Sim!lator and command at
o/ class Sc(ed!ler
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc at ar$s 7
1 Psel" instvar sc(ed!ler5
3 ret!rn ?eval Psc(ed!ler5 at Par$s@
= 8
MMUMnsMcommonMsc(ed!lerIcc
> i" &strcmp&ar$v?2@) HatH' :: 0' 7
A M
N
t < 0 means relative time9 delay : Jt
N
M
B do!ble delay) t : ato"&ar$v?1@';
/ const c(ar
N
proc : ar$v?3@;
G AtEvent
N
e : ne, AtEvent;
20 int n : strlen&proc';
22 eJKproc5 : ne, c(ar?n 4 2@;
21 strcpy&eJKproc5) proc';
23 delay : &t < 0' Y Jt 9 t J clock&';
2= i" &delay < 0' 7
2> tclIres!lt&HcanZt sc(ed!le command in pastH';
2A ret!rn &TCL5E##O#';
2B 8
2/ sc(ed!le&Fat5(andler) e) delay';
2G sprint"&tclIb!""er&') DID5P#INTQ5QO#%AT) eJK!id5';
10 tclIres!lt&tclIb!""er&'';
12 ret!rn &TCL5OV';
11 8
.eri1ed /rom class Handler* class AtHandler seci/ies t&e actions to be
taken at /irin' time in its /unction (andle&e' ?!ines 1:H1#@) Here* !ine 18
casts t&e inut e1ent into an AtEvent obBect) T&en !ine 12 eAtracts and
eAecutes t&e OTcl statement /rom 1ariable Fproc5G o/ t&e cast e1ent)
In t&e OTcl domain* an AtEvent obBect is laced in a c&ain o/ e1ents at a
certain /irin' time by instroc FatG o/ class Sim!lator) 6&ose syntaA is<
Pns at <timeK <statementK
w&ere FPnsG is t&e Sim!lator obBect ?see Sect) :):@* <timeK is t&e /irin'
time* and <statementK is an OTcl statement strin' w&ic& will be eAecuted
w&en t&e simulation time is <timeK second)
Crom !ines 1H: o/ Pro'ram :):* t&e instroc at/III' o/ an OTcl class
Sim!lator in1okes an OTcl command FatG o/ t&e Sc(ed!ler obBect
?!ines
3H22@) T&e OTcl command at/III' o/ class Sc(ed!ler stores t&e /irin' time
in
a 1ariable FtG ?!ine 2@) !ine # creates an AtEvent obBect) !ines " and 1,H12
store
t&e inut OTcl command in t&e 1ariable Fproc5G o/ t&e created AtEvent
obBect)
"2 : Imlementation o/ .iscrete9E1ent Simulation in NS2
!ine 13 con1erts t&e /irin' time to t&e FdelayG time /rom t&e current time)
Cinally* !ine 1" sc&edules t&e created event
N
e at FdelayG seconds in /uture*
/eedin' address o/ t&e 1ariable Fat5(andlerG ?see Pro'ram :)3@ as an inut
ar'ument to /unction sc(ed!le&III')
/=* The Scheu#er
T&e sc&eduler maintains t&e c&ain o/ e1ents and simulation ?1irtual@ time)
4t runtime* it mo1es alon' t&e c&ain and disatc&es one e1ent a/ter anot&er) Since
t&ere is only one c&ain o/ e1ents in a simulation* t&ere is eAactly one Sc(ed!ler
obBect in a simulation) Herea/ter* we will re/er to t&e Sc(ed!ler obBect simly
as t&e Sc&eduler) 4lso* NS2 suorts t&e /our /ollowin' tyes o/ sc&edulers< !ist
Sc&eduler* Hea Sc&eduler* Calendar Sc&eduler ?de/ault@* and (eal9time
Sc&eduler) Cor bre1ity* we do not discuss t&e di//erences amon' all t&ese
sc&edulers &ere) T&e details o/ t&ese sc&edulers can be /ound in M12N)
$.".1 Main Coponents of the Sched!ler
.eclared in Pro'ram :)3* class Sc(ed!ler consists o/ a /ew main 1ariables and
/unctions) 7ariable Fclock5G ?!ine 1#@ contains t&e current simulation time* and
/unction clock&' ?!ine 11@ returns t&e 1alue o/ t&e 1ariable Fclock5G)
7ariable F(alted5G ?!ine 22@ is initialiJed to ,* and is set to 1 w&en t&e
simulation is stoed or aused) 7ariable Finstance5G ?!ine 2,@ is t&e
re/erence to t&e Sc&ed9 uler* and /unction instance&' ?!ine 3@ returns t&e
1ariable Finstance5G) 7ariable !id5 ?!ine 21@ is t&e e1ent uniDue I.) In
NS2* t&e Sc&eduler acts as a sin'le oint o/ uniDue I. mana'ement) 6&en an
e1ent is inserted into t&e simulation timeline* t&e Sc&eduler creates a new uniDue
I. and assi'ns t&e I. to t&e e1ent) +ot& t&e 1ariables Finstance5G and
F!id5G are static* since t&ere is only one Sc&eduler and uniDue I. in a
simulation)
$.".2 )ata *ncaps!lation and Polyorphis Concepts
Pro'ram :)3 imlements t&e concets o/ data encapsulation and polymorphism
?see 4endiA +@) It &ides t&e c&ain o/ e1ents /rom t&e outside world and
declares ure 1irtual /unctions cancel&e'* insert&e'* look!p&!id'*
de+!e&'* and (ead&' in !ines 8H1, to mana'e t&e c&ain) Classes deri1ed
/rom class Sc(ed!ler ro1ide imlementation o/ all o/ t&e abo1e /unctions)
T&e beauty o/ t&is mec&anism is t&e ease o/ modi/yin' t&e sc&eduler
tye at runtime)
:)3 T&e Sc&eduler "3
Program /=0 .eclaration o/ class eI$I) Sc(ed!ler
MMUnsMcommonMsc(ed!lerI(
2 class Sc(ed!ler 9 p!blic TclObject 7
1 p!blic9
3 static Sc(ed!lerF instance&' 7 ret!rn &
N
instance5'; 8
= void sc(ed!le&Handler
N
) Event
N
) do!ble delay';
> virt!al void r!n&';
A virt!al void cancel&Event
N
' : 0;
B virt!al void insert&Event
N
' : 0;
/ virt!al Event
N
look!p&sc(ed!ler5!id5t !id' : 0;
G virt!al Event
N
de+!e&' : 0;
20 virt!al const Event
N
(ead&' : 0;
22 do!ble clock&' const 7 ret!rn clock5j8
21 virt!al void reset&';
23 protected9
2= void dispatc(&Event
N
';
2> void dispatc(&Event
N
) do!ble';
2A Sc(ed!ler&';
2B virt!al USc(ed!ler&';
2/ int command&int ar$c) const c(ar
N
const
N
ar$v';
2G do!ble clock5;
10 static Sc(ed!ler
N
instance5;
12 static sc(ed!ler5!id5t !id5;
11 int (alted5;
11 8;
NS2 imlements most o/ t&e codes in relation to class Sc(ed!ler* not its
deri1ed classes ?e)')* CalendarSc(ed!ler@) 4t runtime ?e)')* in a Tcl
simulation scrit@* we can select a sc&eduler to be o/ any deri1ed class ?e)')*
CalendarSc(ed!ler@ o/ class Sc(ed!ler wit&out &a1in' to modi/y t&e
codes /or t&e base class ?e)')* Sc(ed!ler@)
$."." Main 5!nctions of the Sched!ler
T&ree main /unctions o/ class Sc(ed!ler are r!n&' ?Pro'ram :)8@*
sc(ed!le &()e)delay' ?Pro'ram :)2@ and dispatc(&p)t'
?Pro'ram :)"@) In Pro'ram :)8* /unction r!n&' /irst sets 1ariable
Finstance5G to t&e address o/ t&e sc&eduler ?t(is@ in !ine 3) T&en* it kees
disatc&in' e1ents ?!ine 8@ in t&e c&ain until F(alted5GV , or until all t&e
e1ents are eAecuted ?!ine 3@)
Cunction sc(ed!le&()e)delay' in Pro'ram :)2 takes t&ree inut ar'u9
ments< 4 Handler ointer&('* an Event ointer&e'* and t&e
delay&delay'* resecti1ely) It inserts t&e inut Event obBect&
N
e' into t&e
c&ain o/ e1ents) !ines
3H12 c&eck /or ossible errors) !ine 13 increments t&e uniDue I. o/ t&e Sc&eduler
and assi'ns it to t&e inut Event obBect) !ine 1: associates t&e inut Handler
": : Imlementation o/ .iscrete9E1ent Simulation in NS2
Program /=6 Cunction r!n o/ class
Sc(ed!ler
MMUnsMcommonMsc(ed!lerIcc
2 void sc(ed!ler99r!n&'
1 7
3 instance5 : t(is;
= Event
N
p;
> ,(ile &C(alted5 FF &p : de+!e&''' 7
A dispatc(&p) pJKtime5';
B 8
/ 8
Program /=5 Cunction sc(ed!le o/ class Sc(ed!ler
MMUnsMcommonMsc(ed!lerIcc
2 void Sc(ed!ler99sc(ed!le&Handler
N
() Event
N
e) do!ble delay'
1 7
3 i" &C(' 7 M
N
error9 Do not "eed in NDLL (andler
N
M 8;
= i" &eJK!id5 K 0' 7
> print"&HSc(ed!ler9 Event DID not validCTnTnH';
A abort&';
B 8
/ i" &delay < 0' 7 M
N
error9 ne$ative delay
N
M 8;
G i" &!id5 < 0' 7
20 "print"&stderr) HSc(ed!ler9 DID space e*(a!stedC
22 TnH'; abort&';
21 8
23 eJK!id5 : !id544;
2= eJK(andler5 : (;
2> do!ble t : clock5 4 delay;
2A eJKtime5 : t;
2B insert&e';
2/ 8
Program /=7 Cunction dispatc( o/ class
Sc(ed!ler
MMUnsMcommonMsc(ed!lerIcc
2 void Sc(ed!ler99dispatc(&Event
N
p) do!ble t'
1 7
3 i" &t < clock5' 7 M
N
error
N
M 8;
= clock5 : t;
> pJK!id5 : JpJK!id5; MM bein$ dispatc(ed
A pJK(andler5JK(andle&p'; MM dispatc(
B 8
:)3 T&e Sc&eduler "3
obBect &
N
(' wit& t&e inut Event obBect &
N
e') !ine 13 con1erts inut delay
time ?delay@ to t&e /irin' time ?time5@ o/ t&e Event obBect Fe)G !ine 12
inserts t&e con/i'ured Event obBect
N
e in t&e c&ain o/ e1ents 1ia /unction
insert&e') Since t&e sc&eduler increments its uniDue I. w&en in1okin'
/unction sc(ed!le&III'* e1ery sc&eduled e1ent will &a1e di//erent uniDue I.)
Cinally* t&e errors in !ines 3H12 include
1) Null &andler ?!ine 3@
2) Positi1e Event uniDue I. ?!ines :H2O See Sect)
:)3)3@
3) Ne'ati1e delay ?!ine "@
:) Ne'ati1e Sc(ed!ler uniDue I.
3
?!ines 1#9
12@
Cunction dispatc(&p)t' in Pro'ram :)" is in1oked by /unction r!n&'
at t&e /irin' time ?!ine 8 o/ Pro'ram :)8@) It takes a disatc&in' e1ent &
N
p' and
/irin' time &t' as inut ar'uments) Since t&e sc&eduler mo1es /orward in
simulation time* t&e /irin' time ?t@ cannot be less t&an t&e current simulation time
?clock5@) Crom Pro'ram :)"* !ine 3 will s&ow an error* i/ t < clock5) !ine
: sets t&e current simulation 1irtual time to be t&e /irin' time o/ t&e e1ent) !ine 3
in1erts t&e si'n o/ t&e F!id5G o/ t&e e1ent* indicatin' t&at t&e e1ent is bein'
disatc&ed) !ine 8 in1okes /unction (andle&p' o/ t&e associated &andler
F(andler5*G /eedin' t&e e1ent ?p@ as an inut ar'ument)
$.".$ T&o A!1iliary 5!nctions
4art /rom t&e abo1e t&ree main /unction* class Sc(ed!ler ro1ides two 1ery
use/ul /unctions< instance&' ?!ine 3 in Pro'ram :)3@ and clock ?!ine 11
in Pro'ram :)3@)
Cunction instance&' returns
N
instance5 w&ic& is t&e address o/ t&e
Sc&eduler)
Cunction clock&' returns t&e current simulation 1irtual
time)
6e s&all see t&e use o/ t&ese two /unctions t&rou'&out NS2
ro'rammin')
E%ample /** In order to obtain t&e current 1irtual simulation time in CCC* we
can resort to t&e /ollowin' statements
Sc(ed!lerF s : Sc(ed!ler99instance&';
co!t << HT(e c!rrent time is H << sIclock&' << endl;
Here t&e uer line retrie1es t&e re/erence to t&e Sc(ed!ler* w&ile t&e lower
line in1okes t&e /unction clock&' o/ t&e current simulation time)
3
T&e uniDue I. o/ t&e Sc&eduler is always ositi1e) Its ne'ati1e 1alue indicates ossible
abnormality suc& as memory o1er/low or inad1ertent memory access 1iolation)
"8 : Imlementation o/ .iscrete9E1ent Simulation in NS2
4ig= /=2 .ynamics o/ Event uniDue I. &!id' < Take a ositi1e 1alue /rom
Sc(ed!ler
99!id w&en bein' sc&eduled* and in1ert t&e si'n w&en bein' disatc&ed) Increment uon
sc(ed!le and in1ersion o/ si'n uon
dispatc(
$.".+ )ynaics of the 0ni:!e I) of an *#ent
T&e dynamics o/ t&e e1ent5s uniDue I. ?!id5@ is /airly subtle) In 'eneral* t&e
Sc&ed9 uler maintains t&e uniDue I. and assi'ns t&e uniDue I. to t&e e1ent bein'
sc&eduled) To make F!id5G uniDue* t&e Sc&eduler increments its F!id5G and
assi'ns t&e incremented F!id5G to t&e sc&edulin' e1ent in its /unction
sc(ed!le&III' ?!ine 13 in Pro'ram :)2@) 6&en disatc&in' an e1ent* t&e
sc&eduler in1erts t&e si'n o/ F!id5G o/ t&e disatc&in' e1ent ?!ine 3 in
Pro'ram :)"@) Ci'ure :)2 s&ows t&e dynamics o/ t&e uniDue I. caused by t&e
abo1e sc(ed!le&III' and dispatc(&III' /unctions) 0nless t&e
associated e1ent is bein' disatc&ed* F!id5G o/ an e1ent is always increasin'
and non9ne'ati1e) T&e si'n to''lin' mec&anism o/ uniDue I. ensures t&at e1ents
will be sc&eduled and disatc&ed roerly) I/ a sc&eduled e1ent is not disatc&ed*
or is disatc&ed twice* its uniDue I. will be ositi1e* and an attemt to sc&edule
t&is undisatc&ed e1ent will cause an error ?!ines 3 and 8 in Pro'ram :)2@)
$."./ Sched!ling;)ispatching Mechanis
6e conclude t&is section t&rou'& an eAamle eAlainin' t&e sc&edulin'H
disatc&in' mec&anism) Consider t&e /ollowin' scrit
set ns ?ne, Sim!lator@
Pns at 20 ?p!ts HAn event is dispatc(edH@
Pns r!n
w&ic& rints out t&e messa'e FAn event is dispatc(edG at 1, s a/ter t&e
simulation &as started) Ci'ure :)3 s&ows t&e /unctions ?s&own in rectan'les@
and obBects ?s&own in rounded rectan'les@ related to t&e sc&edulin'Hdisatc&in'
mec&anism* w&ose names are s&own in bold/ace /ont) 4'ain* an AtEvent
obBect is sc&eduled by t&e OTcl command FatG ?in t&e uer9le/t rectan'le@* o/
class Sc(ed!ler) T&e Sc&eduler creates an AtEvent obBect FeG and stores
:)3 T&e Sc&eduler "2
4ig= /=* Sc&edulin' and disatc&in' mec&anism o/ an AtEvent
inut command ?t&e /ourt& inut ar'ument Fstr U p!ts HAn event is
dispatc(edH@G in eJKproc5) T&en* it sc&edules t&e e1ent FeG wit& delay
con1erted /rom time U 1, ?t&e t&ird inut ar'ument@* /eedin' t&e address o/
AtHandler obBect ?at5(andler in t&e lower ri'&t round rectan'le@ as
t&e corresondin' &andler)
T&e lower9le/t rectan'le in Ci') :)3 s&ows details o/ t&e /unction sc(ed!le
&()e)delay' o/ class Sc(ed!ler) +e/ore insertin' e1ent FeG into t&e c&ain
o/ e1ents* /unction sc(ed!le&III' con/i'ures e1ent FeG as /ollows< 0date
F!id5G to be t&e same as t&at o/ Sc(ed!ler* store Fat5(andlerG in t&e
&andler o/ e1ent Fe*G and set /irin' time to be Fclock5G ?current time@ C
Fdelay)G 4t t&e /irin' time* t&e sc&eduled AtEvent obBect is disatc&ed
t&rou'& t&e /unction dispatc(&p)t' ?t&e uer9ri'&t rectan'le in Ci')
:)3@) 6&en t&e sc&eduled Event obBect FeG
:
is disatc&ed* /unction
dispatc(&III' in1erts t&e si'n o/ its 1ariable F!id5*G and in1okes
/unction (andle&e' o/ t&e
:
In Pro'ram :)"* t&e /irst ar'ument o/ /unction dispatc(&III' is Fp)G Here* we use FeG as
t&e /irst ar'ument /or t&e sake o/ eAlanation)
"" : Imlementation o/ .iscrete9E1ent Simulation in NS2
corresondin' &andler /eedin' Event obBect FeG as an inut ar'ument) Since
t&e &andler is Fat5(andlerG ?see t&e uer9le/t rectan'le@* t&e OTcl command
Fp!ts HAn event is dispatc(edHG stored in FeG is eAecuted)
$.".4 %!ll *#ent and )!y *#ent Sched!ling
6&en bein' disatc&ed* an e1ent FpG is /ed to /unction (andle&p' o/ t&e
associ9 ated &andler /or a certain urose) Cor eAamle* t&e /unction (andle&p'
o/ class NsObject eAecutes Frecv&p'G* w&ere FpG is a acket recetion e1ent)
Here* t&e e1ent
N
p must &a1e been created and /ed to t&e /unction
sc(ed!le&III' be/ore t&e on'oin' disatc&in' rocess)
In some cases* an e1ent only indicates t&e time w&ere t&e de/ault action is taken
but takes no art in suc& t&e action) Cor eAamle* a Dueue unblockin' e1ent
in/orms t&e associated !e!e obBect o/ t&e comletion o/ t&e on'oin'
transmission ?see Sect) 2)3@) T&e /unction (andle&p' o/ t&e associated &andler
in t&is case simly in1okes /unction res!me&' w&ic& take no inut ar'ument
?i)e)* action takin'@) Clearly t&e Dueue unblockin' e1ent takes no role in t&e
disatc&in' rocess) In t&is case* we do not need to eAlicitly create an e1ent)
Instead* we can use a null e1ent or a dummy e1ent as an inut ar'ument to t&e
/unction sc(ed!le&III')
/=*=5=% Scheu#ing of a Nu## "vent
Cunction sc(ed!le&()e)delay' takes a ointer to an e1ent as its second
inut ar'ument) 4 null e1ent re/ers to a null ointer w&ic& is /ed as t&e second
inut ar'ument to t&e /unction sc(ed!le&III' ?e)')* sc(ed!le&(andler)
0)delay'@)
4lt&ou'& simle to use* a null e1ent could lead to runtime error w&ic& is
di//icult
to be located) 4 null e1ent is not an actual e1ent) Its uniDue I. does not /ollow
semantic in Ci') :)2) T&e Sc&eduler i'nores t&e uniDue I. w&en sc&edulin' and
disatc&in' a null e1ent* and allows an undisatc&ed e1ent to be resc&eduled) T&is
breaks t&e sc&edulin'Hdisatc&in' rotection mec&anism) 0sin' null e1ents* t&e
users are resonsible /or ensurin' t&e roer seDuence o/ sc&edulin'Hdisatc&in'
by t&emsel1es)
/=*=5=2 Scheu#ing of a -ummy "vent
T&is is anot&er aroac& to sc&edule and disatc& e1ents w&ic& do not take art in
de/ault actions) 4 dummy e1ent is usually declared as a member 1ariable o/ a
CCC class* and is used reeatedly in a sc&edulin'Hdisatc&in' rocess)
Consider a acket dearture e1ent w&ic& is modeled by class LinkDelay ?see
Sect) 2)2@ /or eAamle) .urin' simulation* an NsObBect in/orms a LinkDelay
:): T&e Simulator "#
obBect to sc&edule acket dearture e1ents) 4t t&e /irin' time* t&e acket
comletely dearts t&e NsObBect* and t&e NsObBect is allowed to /etc& anot&er
acket /or transmission) T&e acket dearture e1ent takes no art in t&e de/ault
action* since a new acket is /etc&ed or created by anot&er obBect)
4s we s&all see* a acket dearture e1ent is reresented by a dummy e1ent
1ariable Fintr5G o/ class LinkDelay* and t&e acket dearture is sc&eduled
t&rou'& t&e 1ariable Fintr5G only) Since t&e 1ariable Fintr5G is a dummy
Event* its uniDue I. /ollows t&e semantic in Ci') :)2) 4n attemt to sc&edule an
undisatc&ed e1ent would immediately cause runtime error) Note t&at Fintr5G is
a member 1ariable o/ class LinkDelay) It is used o1er and o1er a'ain to indicate
acket dearture /rom a LinkDelay obBect)
4s a /inal note* under a simle con/i'uration* it is recommended to use t&e null
e1ent sc&edulin' aroac&) Cor a comlicated con/i'uration* on t&e ot&er &and*
t&e dummy e1ent sc&edulin' is re/erable* since it ro1ides a rotection a'ainst
sc&edulin' o/ undisatc&ed e1ents)
/=/ The Simu#ator
OTcl and CCC classes Sim!lator are t&e main classes w&ic& suer1ise t&e
entire simulation) !ike t&e Sc(ed!ler obBect* t&ere can be only one
Sim!lator obBect t&rou'&out a simulation) T&is obBect will be re/erred to as
the Simulator &erea/ter) T&e Simulator contains two tyes o/ key comonents<
simulation obBects and in/ormation9storin' obBects) 6&ile simulation obBects ?e)')*
t&e Sc&eduler@ are t&e key comonents w&ic& dri1e t&e simulation) On t&e ot&er
&and* In/ormation9 storin' obBects ?e)')* t&e re/erence to created nodes@ contain
in/ormation w&ic& is s&ared amon' se1eral obBects) T&ese in/ormation9storin'
obBects are created 1ia 1arious instrocs ?e)')* Sim!lator99node/'@ durin' t&e
Network Con/i'uration P&ase) %ost obBects access t&ese in/ormation9storin'
obBects 1ia its inst1ar Fns5G ?set by eAecutin' Fset ns5 ?Sim!lator
instance@G@* w&ic& is a re/erence to a Simulator)
$.$.1 Main Coponents of a Si!lation
/=/=%=% 'nter&erte Hierarchy
Created by 1arious instrocs* t&e main OTcl simulation comonents are as
/ollows<
The Scheduler ?sc(ed!ler5 created by t&e instroc Sim!lator99init@
maintains t&e c&ain o/ e1ents and eAecutes t&e e1ents c&ronolo'ically)
#, : Imlementation o/ .iscrete9E1ent Simulation in NS2
The null agent ?n!llA$ent5 created by t&e instroc Sim!lator99init@
ro1ides t&e common acket droin' oint)
3
Node reference ?Node5 created by t&e instroc Sim!lator99node@ is an
associati1e array w&ose elements are t&e created nodes and indices are node
I.s)
.ink reference ?link5 created by t&e instrocs simple*Jlink/III' or
d!ple*J link/III'@ is an associati1e array) 4ssociated wit& an indeA wit&
/ormat Fsid9did*G eac& element o/ Flink5G is t&e created unidirectional link
w&ic& carries acket /rom node FsidG to node Fdid)G
#eference to routing ta'le ?ro!tin$Table5 created by t&e instroc
Sim!lator99$etJro!telo$ic/'*@ contains t&e 'lobal routin' table)
/=/=%=2 $om&i#e Hierarchy
In t&e comiled &ierarc&y* class Sim!lator also contains 1ariables and
/unctions as s&own in Pro'ram :)#) 7ariable Finstance5G ?!ine 1"@ is a
ointer to t&e Simulator) It is a static 1ariable* w&ic& means t&at t&ere is only one
1ariable Finstance5G o/ class Sim!lator /or t&e entire simulation)
7ariable Fnode list5G ?!ine 1:@ is t&e link list containin' all created nodes)
T&e link list can contain u to Fsi6e5G elements ?!ine 12@* w&ile t&e total
number o/ nodes is Fnn5G ?!ine 18@) 7ariable rtobject5 ?!ine 13@ is a
ointer to a #o!teLo$ic obBect* w&ic& is resonsible /or t&e routin'
mec&anism ?see C&a) 8@)
Cunction pop!late5"lat5classi"iers&III' ?!ine 2@ ulls out t&e
routin' in/ormation stored in t&e 1ariable
N
rtobject5 and installs t&e routin'
table in t&e created nodes and links ?see Sect) 8)3@) Cunction add5node&III'
?!ine "@ uts t&e inut ar'ument node into t&e link list o/ nodes
?nodelist5@) Cunction $et5link5(ead&III' returns t&e link &ead obBect
?see C&a) 2@ o/ t&e link wit& I. Fn(G w&ic& connects to a ParentNode obBect
N
node) Cunction node5id5by5addr&addr' ?!ine 1,@ con1erts node
address FaddrG to node I.) Cunction alloc&n' ?!ine 11@ allocates saces in
nodelist5 w&ic& can
accommodate u to FnG nodes* and clears all comonents o/ nodelist5 to
NDLL) Cunction c(eck&n' immediately returns i/ FnG is less t&an si6e5)
Ot&erwise* it will create more sace in nodelist5* w&ic& can accommodate u
to FnG nodes) Static /unction instance&' in !ine 3 returns t&e 1ariable
Finstance5G w&ic& is t&e ointer to t&e Simulator)
$.$.2 Retrie#ing the Instance of the Si!lator
Crom t&e interreted &ierarc&y* we can also retrie1e t&e simulator instance by
in1okin' t&e instroc instance/' o/ class Sim!lator ?see ro'ram :)1,@)
3
+y Fdroin' a acket*G we mean Fremo1in' a acketG /rom t&e simulation) 6e will discuss t&e
droin' mec&anism in C&a) 3) Cor t&e moment* it is su//icient to know t&at Fn!llA$ent
G dros or remo1es all recei1ed ackets /rom t&e simulation)
:): T&e Simulator #1
Program /=8 .eclaration o/ class Sim!lator
MMUnsMcommonMsim!latorI(
2 class Sim!lator 9 p!blic TclObject 7
1 p!blic9
3 static Sim!latorF instance&' 7 ret!rn &
N
instance5'; 8
= Sim!lator&' 9 nodelist5&NDLL')
rtobject5&NDLL') nn5&0') si6e5&0' 78
> USim!lator&' 7 delete ?@nodelist5;8
A int command&int ar$c) const c(ar
N
const
N
ar$v';
B void pop!late5"lat5classi"iers&';
/ void add5node&ParentNode
N
node) int id';
G NsObject
N
$et5link5(ead&ParentNode
N
node) int n(';
20 int node5id5by5addr&int address';
22 void alloc&int n';
21 void c(eck&int n';
23 private9
2= ParentNode
NN
nodelist5;
2> #o!teLo$ic
N
rtobject5;
2A int nn5;
2B int si6e5;
2/ static Sim!lator
N
instance5;
2G 8;
Program /=%: (etrie1in' t&e instance o/ t&e Simulator usin' instroc instance
o/ cla ss Sim!lator
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator proc instance 78 7
1 set ns ?Sim!lator in"o instances@
3 i" 7 Pns C: HH 8 7
= ret!rn Pns
> 8
A III
B 8
T&is instroc eAecutes t&e OTcl built9in command Fin"oG wit& an otion
Finstances)G T&is eAecution returns all t&e instances o/ a certain class) Since
t&ere is only one Sim!lator instance* t&e statement FSim!lator in"o
instancesG returns t&e Sim!lator obBect as reDuired)
$.$." Si!lator Initiali<ation
Simulator initialiJation re/ers to t&e rocess in t&e Network Con/i'uration P&ase*
w&ic& creates t&e Simulator as well as its comonents) T&e Simulator is created
by eAecutin' Fne, Sim!latorG) T&is statement in1okes t&e constructor ?i)e)*
t&e instroc init/III' o/ class Sim!lator@ s&own in Pro'ram :)11)
#2 : Imlementation o/ .iscrete9E1ent Simulation in NS2
Program /=%% Instrocs init and !seJsc(ed!ler o/ class
Sim!lator
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc init ar$s 7
1 Psel" create5packet"ormat
3 Psel" !seJsc(ed!ler Calendar
= Psel" set n!llA$ent5 ?ne, A$entMN!ll@
> Psel" setJaddressJ"ormat de"
A eval Psel" ne*t Par$s
B 8
/ Sim!lator instproc !seJsc(ed!ler type 7
G Psel" instvar sc(ed!ler5
20 i" ?in"o e*ists sc(ed!ler5@ 7
22 i" 7 ?Psc(ed!ler5 in"o class@ :: HSc(ed!lerMP
typeH 8 7
21 ret!rn
23 8 else 7
2= delete Psc(ed!ler5
2> 8
2A 8
2B set sc(ed!ler5 ?ne, Sc(ed!lerMPtype@
2/ 8
T&e constructor /irst initialiJes t&e acket /ormat in !ine 2* and eAecutes t&e
OTcl statement F!seJsc(ed!ler/type'G in !ine 3 to seci/y tye o/ t&e
Sc&eduler) +y de/ault* tye o/ t&e Sc&eduler is Calendar) !ine : creates a null
a'ent ?n!llA$ent@) !ine 3 sets t&e address /ormat to t&e de/ault /ormat) T&e
instroc !seJsc(ed!ler/type' ?!ines "H1"@ deletes t&e eAistin' Sc&eduler i/
it is di//erent /rom t&at seci/ied in t&e inut ar'ument Ftype)G T&en it will create
a sc&eduler wit& tye U type* and store t&e created Sc(ed!ler obBect in t&e
inst1ar Fsc(ed!ler5)G
$.$.$ R!nning Si!lation
T&e Simulation P&ase starts at t&e in1ocation o/ t&e instroc r!n/' o/ class
Sim!lator) 4s s&own in Pro'ram :)12* t&is instroc /irst in1okes t&e instroc
con"i$!re/' o/ class #o!teLo$ic ?!ine 2@* w&ic& in turn comutes t&e
otimal routes and creates t&e routin' table ?see C&a) 8@) !ines 3H1, reset
nodes and Dueues) Cinally* !ine 11 starts t&e Sc&eduler by in1okin' t&e OTcl
command r!n/' o/ class Sc(ed!ler* w&ic& in turn in1okes t&e C>> /unction
r!n&' o/ class Sc(ed!ler s&own in Pro'ram :)8) 4'ain* t&is /unction
eAecutes e1ents in t&e c&ain o/ e1ents one a/ter anot&er until t&e Simulator is
&alted ?i)e)* 1ariable F(alted5G o/ class Sc(ed!ler is 1@* or until all t&e
e1ents are eAecuted)
:)3 C&ater Summary #3
Program /=%2 Instroc99r!n o/ class sim!lator
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc r!n 7
1 ?Psel" $etJro!telo$ic@ con"i$!re
3 Psel" instvar sc(ed!ler5 Node5 link5 started5
= set started5 2
> "oreac( nn ?array names Node5@ 7
A PNode5&Pnn' reset
B "oreac( +n ?array names link5@ 7
/ set + ?Plink5&P+n' +!e!e@
G P+ reset
20 8
22 ret!rn ?Psc(ed!ler5 r!n@
21 8
$.$.+ Instprocs of OTcl Class Si!lator
T&e list o/ use/ul instrocs o/ class Sim!lator is s&own
below)
no,/' (etrie1e t&e current simulation time)
n!lla$ent/' (etrie1e t&e s&ared null a'ent)
!seJsc(ed!ler/type' Set t&e sc&eduler to be <typeK)
at/time stm' EAecute t&e statement <stmK at <timeK
second)
r!n/' Start t&e simulation)
(alt/' Terminate t&e simulation)
cancel/e' Cancel t&e sc&eduled e1ent <eK)
/=0 $ha&ter Summary
T&is c&ater eAlains t&e details o/ e1ent9dri1en simulation in NS2) T&e
simulation is carried out by runnin' a Tcl simulation script* w&ic& consists o/
two arts) Cirst* t&e Network Configuration Phase establis&es a network and
con/i'ures all simulation comonents) T&is &ase also creates a c&ain o/ e1ents
by connectin' t&e created e1ents c&ronolo'ically) Second* t&e Simulation Phase
c&ronolo'ically eAecutes ?or disatc&es@ t&e created e1ents until t&e Simulator is
&alted* or until all t&e e1ents are eAecuted)
T&ere are /our main classes in1ol1ed in an NS2 simulation<
Class Sim!lator suer1ises t&e simulation) It contains simulation
comonents suc& as t&e Sc&eduler* t&e null a'ent) It also contains in/ormation
storin' obBects w&ic& are s&ared by ot&er ?simulation@ comonents)
Class Sc(ed!ler maintains t&e c&ain o/ e1ents and c&ronolo'ically
disatc&es t&e e1ents)
#: : Imlementation o/ .iscrete9E1ent Simulation in NS2
Class Event consists o/ t&e /irin' time and t&e associated &andler) E1ents are
ut to'et&er to /orm a c&ain o/ e1ents* w&ic& are disatc&ed one by one by t&e
Sc&eduler) Classes Packet and AtEvent are amon' t&e classes deri1ed
/rom class Event* w&ic& can be laced on t&e simulation timeline ?i)e)* in t&e
c&ain o/ e1ent@) T&ey are associated wit& di//erent &andlers and take di//erent
actions at t&e /irin' time)
Class Handler< 4ssociated wit& an e1ent* a &andler seci/ies de/ault actions
to be taken w&en t&e associated e1ent is disatc&ed) Classes NsObject and
AtHandler are amon' classes deri1ed /rom class Handler) T&ey are
always associated wit& Packet and AtEvent e1ents* resecti1ely) T&eir
actions are to recei1e a Packet obBect and to eAecute an OTcl statement
seci/ied in t&e AtEvent obBect* resecti1ely)
/=6 "<ercises
1) 6&at are t&e de/initions* similarities$di//erences* and relations&i amon' t&e
/ollowin' NS2 comonents<
a) Simulation timeline
b) Sc&eduler
c) E1ent
d) E1ent &andler
e) Simulator
/) Cirin' time or disatc&in' time
S&ow an eAamle to suort your answer)
2) 6&at are t&e similarities$di//erences$relations&i between a TclObBect and an
NSObBectR
3) 6&at is a c&ain o/ e1entsR EAlain &ow NS2 creates a c&ain o/ e1ents* and &ow
NS2 locates a articular e1ent on t&e c&ain)
:) 6&at is e1ent uniDue I.R 6&ere does NS2 store t&is 1alueR 6&at is its data
tyeR 6&at is t&e imlication w&en its 1alue is ositi1e* ne'ati1e* or JeroR
3) 6&at are t&e two simulation &asesR EAlain t&e key obBecti1es o/ eac& o/ t&e
&ases)
8) NS2 &as two tyes o/ built9in e1ents< Packet recetion e1ents and 4T e1ents)
.esi'n anot&er tye o/ e1ents) EAlain t&eir uroses* s&ow &ow t&ese e1ents
can be inte'rated into NS2* and write an NS2 ro'ram to suort your
answer)
2) EAlain t&e seDuence o/ actions t&at occurs at t&e /irin' time) 0se an OTcl
statement eAecution e1ent as an eAamle)
") How does NS2 start a simulation in t&e OTcl domainR 6&at &aens in t&e
CCC domain a/ter t&e simulation &as startedR 6&en and under w&at
condition will t&e simulation terminateR
:)8 EAercises #3
#) 6&at are /our common errors associated wit& e1ent sc&edulin' in NS2R
EAlain t&e reasons and su''est 'eneral solutions)
1,) 6&at are Null e1ents and dummy e1entsR 6&at are t&eir urosesR EAlain
t&eir similarities and di//erences) S&ow eAamle usa'e o/ bot& tyes o/
e1ents)
11) 6rite statements /or t&e /ollowin' uroses) (un NS2 to test your answer)
a) S&ow t&e current 1irtual time on t&e screen in bot& CCC and OTcl
domain) b) 4t 1, s* rint out FHello NS2 0sersWWG on t&e screen) In t&e C>>
domain* use
print"&III' or co!t) In t&e OTcl domain* use p!ts/III'@)
c) Store a Sim!lator obBect in a local 1ariable csim in t&e CCC domain*
and osim in t&e OTcl domain)
d) Send a acket
N
p to an NsObBect
N
obj at 13 s in /uture ?CCC
only@)
$ha&ter 0
Network ,b1ects2 $reation3 $onfiguration3
an Packet 4orwaring
NS2 is a simulation tool desi'ned seci/ically /or communication networks)
T&e main /unctionalities o/ NS2 are to set u a network o/ connectin' nodes and
to ass ackets /rom one node ?w&ic& is a network obBect@ to anot&er)
4 network obBect is one o/ t&e main NS2 comonents* w&ic& is resonsible
/or acket /orwardin') NS2 imlements network obBects usin' t&e olymor&ism
concet in obBect9oriented ro'rammin' ?OOP@) Polymor&ism allows network
obBects to take di//erent actions ways under di//erent conteAts) Cor eAamle* a
Connector obBect immediately asses t&e recei1ed acket to t&e neAt network
obBect* w&ile a !e!e
1
obBect enDueues t&e recei1ed ackets and /orwards only
t&e &ead o/ t&e line acket)
T&is c&ater /irst introduces t&e NS2 comonents by s&owin' /our maBor
classes o/ NS2 comonents* namely* network obBects* acket9related obBects*
simulation9 related obBects* and &eler obBects in Sect) 3)1) 4 art o/ t&e CCC
class &ierarc&y* w&ic& is related to network obBects* is also s&own &ere) Section
3)2 resents class NsObject w&ic& acts as a temlate /or all network obBects) 4n
eAamle o/ network obBects as well as acket /orwardin' mec&anism are
illustrated t&rou'& class Connector in Sect) 3)3) Cinally* t&e c&ater summary
is 'i1en in Sect) 3):) Note t&at t&e readers w&o are not /amiliar wit& OOP are
recommended to 'o t&rou'& a re1iew o/ t&e OOP olymor&ism concet in
4endiA + be/ore roceedin' /urt&er)
1
Class !e!e is a c&ild class o/ class Connector)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* #2
.OI 1,)1,,2$#2"919:81:91:,893 3* = Srin'er Science>+usiness %edia* !!C 2,12
#" 3 Network ObBects< Creation* Con/i'uration* and Packet Corwardin'
0=% ,verview of NS2 $om&onents
+.1.1 5!nctionality(2ased Classification of %S2 Mod!les
+ased on t&e /unctionality* NS2 modules ?or obBects@ can be classi/ied into /our
/ollowin' tyes<
Network o'3ects are resonsible /or sendin'* recei1in'* creatin'* and destroy9
in' acket9related obBects) Since t&ese obBects are t&ose deri1ed /rom class
NsObject* t&ey will be re/erred to &erea/ter as NsObBects)
Packet)related o'3ects are 1arious tyes o/ ackets w&ic& are assed around a
network)
Simulation)related o'3ects control simulation timin' and suer1ise t&e entire
simulation) 4s discussed in C&a) :* eAamles o/ simulation9related obBects are
e1ents* &andlers* t&e Sc&eduler* and t&e Simulator)
<elper o'3ects do not eAlicitly articiate in acket /orwardin') Howe1er*
t&ey imlicitly &el to comlete t&e simulation) Cor eAamle* a routin' module
calculates routes /rom a source to a destination* w&ile network address
identi/ies eac& o/ t&e network obBects)
In t&is c&ater* we /ocus only on network obBects) Note t&at* t&e simulation9
related obBects were discussed in C&a) :) T&e acket9related obBects will be
discussed in C&a) ") T&e main &eler obBects will be discussed in C&a) 13)
+.1.2 CCC Class 7ierarchy
T&is section 'i1es an o1er1iew o/ CCC class &ierarc&ies) T&e entire &ierarc&y
consists o/ o1er 1,, CCC classes and str!ct data tyes) Here* we only s&ow
a art o/ t&e &ierarc&y ?in Ci') 3)1@) T&e readers are re/erred to M1"N /or t&e
comlete class &ierarc&y)
4s discussed in C&a) 3* all classes deri1in' /rom class TclObject /orm t&e
comiled &ierarc&y) Classes in t&is &ierarc&y can be accessed /rom t&e OTcl
domain) Cor eAamle* t&ey can be created by t&e 'lobal OTcl rocedure
Fne,/III')G Classes deri1ed directly /rom class TclObject include network
classes ?e)')* NsObject@* acket9related classes ?e)')* Packet!e!e@*
simulation9 related classes ?e)')* Sc(ed!ler@* and &eler classes ?e)')*
#o!tin$J %od!le@) 4'ain* classes t&at do not need OTcl counterarts
?e)')* classes deri1ed /rom class Handler@ /orm t&eir own standalone
&ierarc&ies) T&ese &ierarc&ies are not a art o/ t&e comiled &ierarc&y nor t&e
interreted &ierarc&y)
4s discussed in C&a) :* class Handler seci/ies an action associated wit&
an e1ent) 4'ain* class Handler contains a ure 1irtual /unction (andle&e'
?see Pro'ram :)1@) T&ere/ore* its deri1ed classes are resonsible /or ro1idin'
3)1 O1er1iew o/ NS2 Comonents ##
*'cl /nterface
Default ,ction
'cl*b7ect
Handler
Simulator
Pac1et5ueue )s*b7ect ,tHandler 5ueueHandler
=outin4Module
)et>or1 0om6onent
0lassifier
0onnector Lan=outer
?ni$directional Point$to$
6oint *b7ect 0onnector
5ueue
,4ent +rrorModel Lin1Delay 'race
4ig= 0=% 4 art o/ NS2 CCC class &ierarc&y ?t&is c&ater em&asiJes on classes in 'o%es wit&
thick solid lines@
imlementation o/ t&e /unction (andle&e') Cor eAamle* t&e /unction
(andle&e' o/ class NsObject tells t&e NsObBect to recei1e an incomin'
acket ?Pro'ram :)2@* w&ile t&at o/ class !e!eHandler in1okes /unction
res!me&' o/ t&e associated !e!e obBect ?!ines 1H: in Pro'ram 3)1O also see
Sect) 2)3)2@)
Program 0=% Cunction (andle&e' o/ class !e!eHandler
MMUMnsM+!e!eM+!e!eIcc
2 void !e!eHandler99(andle&Event
N
'
1 7
3 +!e!e5Ires!me&';
= 8
T&ere are t&ree main classes deri1in' /rom class NsObject< Connector*
Classi"ier* and Lan#o!ter) Connectin' two NsObBects* a Connector ob9
Bect immediately /orwards a recei1ed acket to t&e connectin' NsObBect
?see Sect) 3)3@) Connectin' an NsObBect to se1eral NsObBects* a Classi"ier
obBect classi/ies ackets based on acket &eader ?e)')* destination address* /low
I.@ and /orwards t&e ackets wit& t&e same classi/ication to t&e same connectin'
NsObBect ?see Sect) 8)2@) Class Lan#o!ter also &as multile connectin' NsOb9
Bects) Howe1er* it /orwards e1ery recei1ed acket to all connectin' NsObBects)
1,, 3 Network ObBects< Creation* Con/i'uration* and Packet Corwardin'
0=2 Ns,b1ects2 A Network ,b1ect Tem&#ate
+.2.1 Class NsObject
(eresentin' NsObBects* class NsObject is t&e base class /or all network
obBects in NS2 ?see t&e declaration in Pro'ram 3)2@) 4'ain* t&e main
resonsibility o/ an NsObBect is to /orward ackets) T&ere/ore* class NsObject
de/ines a ure 1irtual /unction recv&p)(' ?see !ine 3 in Pro'ram 3)2@ as a
uni/orm acket recetion inter/ace to /orce all its deri1ed classes to imlement t&is
/unction)
Program 0=2 .eclaration o/ class NsObject
MMUMnsMcommonMobjectI(
2 class NsObject 9 p!blic TclObject) p!blic Handler 7
1 p!blic9
3 NsObject&';
= virt!al UNsObject&';
> virt!al void recv&Packet
N
) Handler
N
callback : 0' : 0;
A virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
B protected9
/ virt!al void reset&';
G void (andle&Event
N
';
20 int deb!$5;
22 8;
.eri1ed directly /rom class TclObject and Handler ?see Pro'ram
3)2@* class NsObject is t&e temlate class /or all NS2 network obBects) It
in&erits OTcl inter/aces /rom class TclObject and t&e de/ault action ?i)e)*
/unction (andle&e'@ /rom class Handler) In addition* it de/ines a acket
recetion tem9 late and /orces all its deri1ed classes to ro1ide acket recetion
imlementation)
Cunction recv&p)(' is t&e 1ery essence o/ acket /orwardin' mec&anism
in NS2) In NS2* an ustream obBect maintains a re/erence to t&e connectin'
downstream obBect) It asses a acket to t&e downstream obBect by in1okin'
t&e /unction recv&p)(' o/ t&e downstream obBect and /eedin' t&e acket and
otionally a &andler as an inut ar'ument) Since NS2 /ocuses mainly on
/orwardin' ackets in a downstream direction* NsObBects do not need to &a1e a
re/erence to its ustream obBects) In most cases* NsObBect con/i'uration in1ol1es
downstream ?not ustream@ obBects only)
Cunction recv&p)(' takes two inut ar'uments< a acket F
N
pG to be
recei1ed and a &andler F
N
()G %ost in1ocation o/ /unction recv&p)(' in1ol1es
only acket F
N
p*G not t&e &andler)
2
Cor eAamle* a !e!e obBect ?see Sect)
2)3)3@ uts t&e recei1ed acket in t&e bu//er and transmits t&e acket at t&e
&ead o/ t&e bu//er)
2
6e will discuss t&e call'ack mec&anism w&ic& in1ol1es a &andler in Sect) 2)3)3)
3)3 Connectors 1,1
4n Error%odel obBect ?see Sect) 13)3@ imoses error robability on t&e recei1ed
acket and /orwards t&e acket to t&e connectin' obBect i/ t&e transmission is not
in error)
+.2.2 Pac'et 5or&arding Mechanis of
%sO-8ects
4n NsObBect /orwards ackets in two /ollowin'
ways<
Immediate packet forwarding< To /orward a acket to a downstream obBect* an
ustream obBect needs to obtain a re/erence ?e)')* a ointer@ to t&e downstream
obBect and in1okes /unction recv&p)(' o/ t&e downstream obBect t&rou'&
t&e obtained re/erence) Cor eAamle* a Connector ?see Sect) 3)3@ &as a ointer
Ftar$et5G to its downstream obBect) T&ere/ore* it /orwards a acket to its
downstream obBect by eAecutin' tar$et5JKrecv&p)(')
4elayed packet forwarding< To delay acket /orwardin'* a Packet obBect
is
cast to be an Event obBect* associated wit& a acket recei1in' NsObBect* and
laced on t&e simulation timeline at a 'i1en simulation time) 4t t&e /irin' time*
t&e /unction (andle&e' o/ t&e NsObBect will be in1oked* and t&e acket
will be recei1ed t&rou'& /unction recv&p)(' ?see an eAamle o/ delayed
acket /orwardin' in Sect) 3)3@)
0=* $onnectors
4s s&own in Ci') 3)2* a Connector is an NsObBect w&ic& connects t&ree NsObBects
in a unidirectional manner) It recei1es a acket /rom an ustream NsObBect) +y
de/ault* a Connector immediately /orwards t&e recei1ed acket to its downstream
NsObBect) 4lternati1ely* it can dro t&e acket by /orwardin' t&e acket to a
acket droin' obBect)
3
Crom Ci') 3)2* a Connector is interested in seci/yin' its downstream NsObBect
and acket droin' NsObBect only) T&e connection /rom an ustream obBect to
a Connector* on t&e ot&er &and* is con/i'ured by t&e ustream obBect* not by t&e
connector)
3
4 acket droin' network obBect ?e)')* a null a'ent@ is resonsible /or destroyin' ackets)
1,2 3 Network ObBects< Creation* Con/i'uration* and Packet Corwardin'
0onnector
)s*b7ect
?6stream
)s*b7ect
tar4etC
dro6C
Pac1et for>ardin4 6ath
)s*b7ect
Do>nstream
)s*b7ect
Pac1et
dro66in4
6ath
)s*b7ect
Pac1et Dro66in4
)s*b7ect
4ig= 0=2 .ia'ram o/ a connector< T&e solid arrows reresent ointers* w&ile t&e dotted arrows
s&ow acket /orwardin' and droin' at&s
Program 0=* .eclaration and /unction recv&p)(' o/ class
Connector
MMUMnsMcommonMconnectorI(
2 class Connector 9 p!blic NsObject 7
1 p!blic9
3 Connector&';
= inline NsObject
N
tar$et&' 7 ret!rn tar$et5; 8
> void tar$et &NsObject
N
tar$et' 7 tar$et5 : tar$et; 8
A virt!al void drop&Packet
N
p';
B void setDropTar$et&NsObject
N
dt' 7drop5 : dt; 8
/ protected9
G virt!al void drop&Packet
N
p) const c(ar
N
s';
20 int command&int ar$c) const c(ar
N
const
N
ar$v';
22 void recv&Packet
N
) Handler
N
callback : 0';
21 inline void send&Packet
N
p) Handler
N
('7tar$et5JKrecv
&p) (';8
23
2= NsObject
N
tar$et5;
2> NsObject
N
drop5; MM drop tar$et "or t(is connector
2A 8;
MMUMnsMcommonMconnectorIcc
2B void Connector99recv&Packet
N
p) Handler
N
('7send&p) (';8
+.".1 Class )eclaration
Pro'ram 3)3 s&ows t&e declaration o/ class Connector) Class Connector
con9 tains two ointers ?!ines 1: and 13 in Pro'ram 3)3@ to NsObjects
:
<
Ftar$et5G
:
Since class Connector contains two ointers to abstract obBect ?i)e)* class NsObject@* it
can be re'arded as an abstract user class /or class comosition discussed in Sect) +)") 6e will
discuss t&e details o/ &ow t&e class comosition concet alies to a Connector in t&e neAt
section)
and Fdrop5)G Crom Ci') 3)2* Ftar$et5G is t&e ointer to t&e connectin' down9
stream NsObject* w&ile Fdrop5G is t&e ointer to t&e acket droin' obBect)
Class Connector deri1es /rom t&e abstract class NsObject) It o1errides
t&e ure 1irtual /unction recv&p)('* by simly in1okin' /unction send&p)('
?see !ine 12 in ro'ram 3)3@) Cunction send&p)(' simly /orwards t&e
recei1ed acket to its downstream obBect by in1okin' /unction recv&p)(' o/
t&e down9 stream obBect ?i)e)* tar$et5JKrecv&p)(' in !ine 12@)
Program 0=/ Cunction drop o/ class
connector
MMUMnsMcommonMconnectorIcc
2 void Connector99drop&Packet
N
p'
1 7
3 i" &drop5 C: 0'
= drop5JKrecv&p';
> else
A Packet99"ree&p';
B 8
Pro'ram 3): s&ows t&e imlementation o/ /unction drop&p'* w&ic& dros
or destroys a acket) Cunction drop&p' takes one inut ar'ument* w&ic& is
a acket to be droed) I/ t&e droin' NsObBect eAists ?i)e)* Fdrop5GV ,@*
t&is /unction will /orward t&e acket to t&e droin' NsObBect by in1okin'
drop5JKrecv&p)(') Ot&erwise* it will destroy t&e acket by eAecutin'
FPacket99"ree&p'G ?see C&a) "@) Note t&at /unction drop&p' is declared
as 1irtual ?!ine #@) Hence* classes deri1ed /rom class Connector may o1erride
t&is /unction wit&out any /unction ambi'uity)
3
+.".2 OTcl Config!ration Coands
4s discussed in Sect) :)1* NS2 simulation consists o/ two &ases< Network Con9
/i'uration P&ase and Simulation P&ase) In t&e Network Con/i'uration P&ase* a
Connector is set u as s&own in Ci') 3)2) 4'ain* a Connector con/i'ures its
downstream and acket droin' NsObBects only)
Suose OTcl &as instantiated t&ree /ollowin' obBects< a Connector ob9
Bect ?conn5obj@* a downstream obBect ?do,n5obj@* and a droin' obBect
?drop5obj@) T&en* t&e Connector is con/i'ured usin' t&e /ollowin' two OTcl
commands ?see Pro'ram 3)3@<
3
Cunction ambi'uity is discussed in 4endiA +)2)
1,: 3 Network ObBects< Creation* Con/i'uration* and Packet Corwardin'
Program 0=0 OTcl commands tar$et and dropJtar$et o/ class
Connector
MMUMnsMcommonMconnectorIcc
2 int Connector99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 TclF tcl : Tcl99instance&';
= i" &ar$c :: 1' 7
> i" &strcmp&ar$v?2@) Htar$etH' :: 0' 7
A i" &tar$et5 C: 0'
B tclIres!lt&tar$et5JKname&'';
/ ret!rn &TCL5OV';
G 8
20 i" &strcmp&ar$v?2@) HdropJtar$etH' :: 0' 7
22 i" &drop5 C: 0'
21 tclIres!lt"&HEsH) drop5JKname&'';
23 ret!rn &TCL5OV';
2= 8
2> 8
2A else i" &ar$c :: 3' 7
2B i" &strcmp&ar$v?2@) Htar$etH' :: 0' 7
2/ i" &
N
ar$v?1@ :: Z0Z' 7
2G tar$et5 : 0;
10 ret!rn &TCL5OV';
12 8
11 tar$et5 : &NsObject
N
'TclObject99look!p&ar$v?1@';
13 i" &tar$et5 :: 0' 7
1= tclIres!lt"&Hno s!c( object EsH) ar$v?1@';
1> ret!rn &TCL5E##O#';
1A 8
1B ret!rn &TCL5OV';
1/ 8
1G i" &strcmp&ar$v?2@) HdropJtar$etH' :: 0' 7
30 drop5 : &NsObject
N
'TclObject99look!p&ar$v?1@';
32 i" &drop5 :: 0' 7
31 tclIres!lt"&Hno object EsH) ar$v?1@';
33 ret!rn &TCL5E##O#';
3= 8
3> ret!rn &TCL5OV';
3A 8
3B 8
3/ ret!rn &NsObject99command&ar$c) ar$v'';
3G 8
OTcl command tar$et wit& one inut ar'ument con/orms to t&e /ollowin'
syntaA<
Pconn5obj tar$et Pdo,n5obj
T&is command casts t&e inut ar'ument do,n5obj to be o/ tye NsObject
N
and stores it in t&e 1ariable Ftar$et5G ?!ine 22@)
c
a
s
t
i
n
4
3)3 Connectors 1,3
)s*b7ect
?6stream
net>or1
0onnector
tar4etC
-y declaration
)s*b7ect
rec((6Dh)@!E
com6onent rec((6Dh) F G HE
by
6olymor6hism
'c6,4ent
rec((6Dh)F:::HE
4ig= 0=* 4 olymor&ism imlementation o/ a connector< 4 connector declares tar$et as an
NsObject ointer) In t&e network con/i'uration &ase* t&e OTcl command tar$et is
in1oked to setu a downstream obBect o/ t&e Connector* and t&e NsObBect
N
tar$et is cast to a
TcpA$ent obBect
OTcl command tar$et wit& no inut ar'ument ?e)')* Pconn5obj
tar$et@ returns OTcl instance corresondin' to t&e CCC 1ariable
Ftar$et5G ?!ine 3H#@) Note t&at /unction name&' o/ class TclObject
returns t&e OTcl re/erence strin' associated wit& t&e inut ar'ument)
OTcl command dropJtar$et wit& one inut ar'ument is 1ery similar to
t&at o/ t&e OTcl command tar$et but t&e inut ar'ument is cast and stored
in t&e 1ariable Fdrop5G instead o/ t&e 1ariable Ftar$et5)G
OTcl command dropJtar$et wit& no inut ar'ument is 1ery similar to t&at
o/ t&e OTcl command tar$et but it returns t&e OTcl instance corresondin'
to t&e 1ariable Fdrop5G instead o/ t&e 1ariable Ftar$et5)G
E%ample 1** Consider t&e connector con/i'uration in Ci's) 3)2H3)3) !et t&e down9
stream obBect be o/ class TcpA$ent* w&ic& corresonds to class A$entMTcp in
t&e OTcl domain) 4lso* let a A$entMN!ll obBect be a acket droin'
NsObBect) T&e /ollowin' ro'ram s&ows &ow t&e network is set u /rom t&e OTcl
domain<
set conn5obj ?ne, Connector@
set tcp ?ne, A$entMTCP@
set n!ll ?ne, A$entMN!ll@
Pconn5obj tar$et Ptcp
Pconn5obj dropJtar$et Pn!ll
T&e /irst t&ree lines create a Connector ?conn@* a TCP obBect ?tcp@* and a
acket droin' obBect ?n!ll@) T&e last two lines use t&e OTcl commands
tar$et and dropJtar$et to set FtcpG and Fn!llG as t&e downstream
obBect and t&e droin' obBect o/ t&e Connector* resecti1ely)
Connector con/i'uration comlies wit& t&e class comosition ro'rammin'
concet discussed in 4endiA +)") Table 3)1 s&ows t&e comonents in EAamle
3)1
1,8 3 Network ObBects< Creation* Con/i'uration* and Packet Corwardin'
Tab#e 0=% Class comosition
o/ network comonents in
EAamle 3)1
4bstract class NsObject
.eri1ed class A$entMTcp and A$entMN!ll
4bstract user class Connector
0ser class 4 Tcl simulation scrit
and t&e corresondin' class comosition) Classes A$entMTCP and
A$entMN!ll are OTcl classes w&ose corresondin' CCC classes deri1e /rom
class NsObject) Class Connector stores ointers ?i)e)* Ftar$et5G and
Fdrop5G@ to NsObBects* and is t&ere/ore considered to be an abstract user class)
Cinally* as a user class* t&e Tcl Simulation Scrit instantiates NsObBects tcp*
and n!ll /rom classes A$entMTcp* and A$entMN!ll* resecti1ely* and
binds tcp and n!ll to 1ariables tar$et5 and drop5* resecti1ely)
6&en in1okin' tar$et and dropJtar$et* tcp and n!ll are /irst
tye9 cast to NsObject ointers) T&en t&ey are assi'ned to ointers tar$et5
and to drop5* resecti1ely) Cunctions recv&p)(' o/ bot& tcp and n!ll are
associated wit& class A$entMTCP and A$entMN!ll* resecti1ely* since t&ey
bot& are 1irtual /unctions)
+."." Pac'et 5or&arding Mechanis of
Connectors
Crom Sect) 3)2)2* an NsObBect /orwards a acket in two ways< immediate and
delayed acket /orwardin') T&is section demonstrates bot& t&e acket /orwardin'
mec&anisms t&rou'& a Connector)
0=*=*=% 'mmeiate Packet 4orwaring
Immediate acket /orwardin' is carried out by in1okin' /unction recv&p)(' o/
a downstream obBect) In EAamle 3)1* t&e Connector /orwards a acket to t&e TCP
ob9 Bect by in1okin' /unction recv&p)(' o/ t&e TCP obBect ?i)e)* tar$et5J
Krecv &p)('* w&ere tar$et5 is con/i'ured to oint to a TCP obBect@) CCC
olymor9 &ism is resonsible /or associatin' t&e /unction recv&p)(' to class
A$entMTCP ?i)e)* t&e construction tye@* not class NsObject ?i)e)* t&e
declaration tye@)
0=*=*=2 -e#aye Packet 4orwaring
.elayed acket /orwardin' is imlemented wit& t&e aid o/ t&e Sc&eduler) Here*
a acket is cast to an e1ent* associated wit& a recei1in' NsObBect* and laced on
t&e simulation timeline) Cor eAamle* to delay acket /orwardin' in EAamle 3)1
by FdG seconds* we may in1oke t&e /ollowin' statement instead o/ tar$et5JK
recv&p)(')
4ig= 0=/ .elayed acket /orwardin' mec&anism
Sc(ed!lerF s : Sc(ed!ler99instance&';
sIsc(ed!le&tar$et5) p) d';
Consider Ci') 3): and Pro'ram 3)8 alto'et&er) Ci'ure 3): s&ows t&e dia'ram
o/ delayed acket /orwardin'* w&ile Pro'ram 3)8 s&ows t&e details o/ /unctions
sc(ed!le&()e)delay' as well as dispatc(&p)t' o/ class
Sc(ed!ler) T&e statement Fsc(ed!le&tar$et5) p) d'G casts acket
N
p
and t&e NsOb9 Bect
N
tar$et5 into Event and Handler objects*
resecti1ely ?!ine 1 o/ Pro'ram 3)8@) !ine 3 o/ Pro'ram 3)8 associates t&e
acket
N
p wit& t&e NsObBect
N
tar$et5) !ines 8 and 2 insert t&e acket
N
p into t&e simulation timeline at t&e
aroriate time) 4t t&e /irin' time* t&e e1ent ?
N
p@ is disatc&ed ?!ines #H1:@) T&e
Sc&eduler in1okes /unction (andle&p' o/ t&e &andler associated wit& e1ent
N
p)
In t&is case* t&e associated &andler is t&e NsObBect
N
tar$et5) T&ere/ore* in !ine
13* t&e de/ault action (andle&p' o/ Ftar$et5G* in1okes /unction
recv&p)(' to recei1e t&e sc&eduled acket ?see Pro'ram :)2@)
1," 3 Network ObBects< Creation* Con/i'uration* and Packet Corwardin'
Program 0=6 Cunctions sc(ed!le and dispatc( o/ class Sc(ed!ler
MMUMnsMcommonMsc(ed!lerIcc
2 void Sc(ed!ler99sc(ed!le&Handler
N
() Event
N
e) do!ble delay'
1 7
3 III
= eJK!id5 : !id544;
> eJK(andler5 : (;
A eJKtime5 : clock5 4 delay;
B insert&e';
/ 8
G void Sc(ed!ler99dispatc(&Event
N
p) do!ble t'
20 III
22 clock5 : t;
21 pJK!id5 : JpJK!id5; MM bein$ dispatc(ed
23 pJK(andler5JK(andle&p'; MM dispatc(
2= 8
0=/ $ha&ter Summary
(e/erred to as an NsObBect* a network obBect is resonsible /or sendin'* recei1in'*
creatin'* and destroyin' ackets) 4s an obBect o/ class NsObject* it deri1es
OTcl inter/aces /rom class TclObject and t&e de/ault action ?i)e)* /unction
(andle&e'@ /rom class Handler) It de/ines a ure 1irtual /unction
recv&p)(' as a uni/orm acket recetion inter/ace /or t&e deri1ed classes)
+ased on t&e olymor&ism concet* t&e deri1ed classes must ro1ide t&eir own
imlementation o/ &ow to recei1e a acket)
In NS2* an NsObBect needs to create a connection to its downstream obBect
only) Normally* an NsObBect /orwards a acket to a downstream obBect by
in1okin' /unction recv&p)(' o/ its downstream obBect) In addition* an
NsObBect can de/er acket /orwardin' by associatin' a acket to t&e downstream
obBect and insertin' t&e acket on t&e simulation timeline) 4t t&e /irin' time* t&e
sc&eduler disatc&es t&e acket* and t&e de/ault action o/ t&e downstream obBect is
in1oked to recei1e t&e acket)
4s an eAamle* we s&ow t&e details o/ class Connector* one o/ t&e main
NsObBect classes in NS2) Class Connector contains two ointers to NsObBects<
Ftar$et5G ointin' to a downstream obBect and Fdrop5G ointin' to a acket
droin' obBect) To con/i'ure a Connector* an obBect w&ose class deri1es /rom
class NsObject can be set as downstream and droin' obBects 1ia OTcl
command tar$et/III' and dropJtar$et/III'* resecti1ely) T&ese two
OTcl commands cast t&e downstream and droin' obBects to NsObBects* and
assi'n t&em to CCC 1ariables
N
tar$et5 and
N
drop5* resecti1ely)
3)3 EAercises 1,#
0=0 "<ercises
1) 6&at are t&e /our tyes o/ NS2 obBectsR EAlain t&eir roles and di//erences
amon' t&em)
2) Class NsObject contains a ure 1irtual /unction) 6&at is t&e name o/ t&e
/unctionR Li1e a 'eneral descrition o/ t&e /unction) 6&y does it &a1e to be
declared as ure 1irtualR
3) 6&at is t&e /unction w&ic& is central to acket recetion mec&anismR
:) 6&at are t&e two acket recetion met&odsR EAlain t&eir uroses and &ow
t&ey are imlemented in NS2) Cormulate an eAamle /rom class Connector
to s&ow t&e rocess in time seDuence)
3) .emonstrate &ow a acket is droed in t&e CCC domain) Can you dro a
acket /rom wit&in any CCC classR EAlain your answer 1ia an eAamle CCC
class)
$ha&ter 6
Noes as Routers or $om&uter Hosts
T&is c&ater /ocuses on a basic network comonent* Node) In NS2* a Node acts as
a comuter &ost ?e)')* a source or a destination@ and a router ?e)')* an intermediate
node@) It recei1es ackets /rom an attac&ed alication or an ustream obBect* and
/orwards t&em to t&e attac&ed links seci/ied in t&e routin' table ?as a router@ or
deli1ers t&em /rom$to transort layer a'ents ?as a &ost@)
In t&e /ollowin'* we /irst 'i1e an o1er1iew o/ routin' mec&anism and Nodes
in Sect) 8)1) Sections 8)2H8): discuss t&ree main routin' comonents< classi/iers*
routin' modules* and route lo'ic* resecti1ely) In Sect) 8)3* we s&ow &ow t&e
a/orementioned Node comonents are assembled to comose a Node) Cinally* t&e
c&ater summary is ro1ided in Sect) 8)8)
6=% An ,verview of Noes in NS2
/.1.1 Ro!ting Concept and Terinology
In NS2* routin' &as a broader de/inition t&an t&at usually used in ractice) (outin'
usually re/ers to a network layer oeration w&ic& determines t&e route alon' w&ic&
a acket s&ould be /orwarded to its destination) In NS2* routin' is an act o/
/orwardin' a acket /rom one NsObBect to anot&er) It can occur wit&in a Node
?i)e)* no communication@* /rom a Node to a link ?i)e)* network layer@* between a
Node and an a'ent ?i)e)* transort layer@* and so on) In order to a1oid con/usion*
let us de/ine t&e /ollowin' terminolo'ies<
#outing mechanism< 4n act o/ determinin' and assin' ackets accordin' to
rede/ined routin' rules
#outing rule or route entry< 4 rule w&ic& determines w&ere a acket s&ould be
/orwarded toO it is usually eAressed in t&e /orm o/ &dst)tar$et' H
meanin' t&at ackets destined /or FdstG s&ould be /orwarded to Ftar$et)G
#outing ta'le< 4 collection o/ routin' rules
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 8* = Srin'er Science>+usiness %edia* !!C 2,12
111
112 8 Nodes as (outers or Comuter Hosts
4ig= 6=% Node arc&itecture
#outing algorithm< 4n al'orit&m w&ic& comutes routin' rules ?e)')* .iBkstra
al'orit&m M1#N@
#outing protocol< 4 communication rotocol desi'ned to udate t&e routin'
rules accordin' to dynamic en1ironment ?e)')* 4d &oc On9demand .istance
7ector ?4O.7@ M2:N@
#outing agent< 4n entity w&ic& 'at&ers arameters ?e)')* network toolo'y@
necessary to comute routin' rules)
#oute logic< 4n NS2 comonent w&ic& runs t&e routin' al'orit&m ?i)e)*
comut9 in' routin' rules@
#outer< 4n entity w&ic& run routin' mec&anismO in NS2* t&is entity is an
address classifier)
#outing module< 4 sin'le oint o/ mana'ement* w&ic& mana'es a 'rou o/
classi/iers
T&is c&ater /ocuses on static routin'* w&ic& in1ol1es t&e /ollowin' main NS2
comonents< Nodes* classi/iers* routin' modules* route lo'ic)
/.1.2 Architect!re of a %ode
4 Node is an OTcl comosite obBect w&ose arc&itecture is s&own in Ci') 8)1)
Nodes are de/ined in an OTcl class Node* w&ic& is bound to CCC class wit&
t&e same name) 4 Node consists o/ two main comonents< an address classi9
/ier ?inst1ar classi"ier5@ and a ort classi/ier ?inst1ar dm!*5@) T&ese two
comonents &a1e one entry oint and multile /orwardin' tar'ets) 4n address
classi/ier acts as a router w&ic& recei1es a acket /rom an ustream obBect and
/orwards t&e acket to one o/ its connectin' links based on t&e address embedded
in acket &eader) 4 ort classi/ier acts as a transort layer brid'e H takin' a
acket /rom t&e address classi/ier ?in case t&at t&e acket is destined to t&is
articular node@* and /orwardin' t&e acket to one o/ t&e attac&ed transort layer
a'ents)
8)1 4n O1er1iew o/ Nodes in NS2 113
/.1." )efa!lt %odes and %ode Config!ration Interface
4 de/ault NS2 Node is based on /lat9addressin' and static routin') 6it& /lat9
addressin'* an address o/ e1ery new node is incremented by one /rom t&at o/ t&e
re1iously created node) Static routin' assumes no c&an'e in toolo'y) T&e
routin' table is comuted once at t&e be'innin' o/ t&e Simulation &ase and does
not c&an'e t&erea/ter) +y de/ault* NS2 uses t&e .iBkstra5s s&ortest at& al'orit&m
M1#N to comute otimal routes /or all airs o/ Nodes) 4'ain* t&is c&ater /ocuses
on Nodes wit& /lat9addressin' and static routin' only) T&e details about ot&er
routin' rotocols as well as &ierarc&ical addressin' can be /ound in t&e NS manual
M12N)
To ro1ide a de/ault Node wit& more /unctionalities suc& as link layer or
%edium 4ccess Control ?%4C@ rotocol /unctionalities* we may use t&e instroc
node9 con"i$ o/ class Sim!lator w&ose syntaA is as /ollows<
Pns nodeJcon"i$ J<optionK ?<val!eK@
w&ere Pns is t&e Sim!lator
obBect)
4n eAamle use o/ t&e instroc nodeJcon"i$/ar$s' /or t&e de/ault settin' is
s&own below<
Pns5 nodeJcon"i$ JaddressType "lat
Jad(oc#o!tin$
JllType
JmacType
JpropType
Ji"+Type
Ji"+Len
Jp(yType
JantType
Jc(annel
Jc(annelType
Jtopolo$yInstance
+y de/ault* almost e1ery otion is seci/ied as NDLL wit& t&e eAcetion o/
addressType* w&ic& is set to be /lat addressin') T&e instroc nodeJcon"i$
&as an otion reset* i)e)*
Pns nodeJcon"i$ Jreset
w&ic& is used to restore de/ault arameter settin') T&e details o/ instroc nodeJ
con"i$ ?e)')* ot&er otions@ can be /ound in t&e /ile Tns$tcl$lib$ns9lib)tcl and
M12N)
Note t&at t&is instroc does not immediately con/i'ure t&e Nodes as seci/ied
in t&e <optionK) Instead* it stores <val!eK in t&e inst1ars o/ t&e Sim!lator
corresondin' to <optionK) T&is stored con/i'uration will be used durin' a
Node construction rocess) 4s a result* t&e instroc nodeJcon"i$ must be
eAecuted be/ore Node construction)
11: 8 Nodes as (outers or Comuter Hosts
6=2 $#assifiers2 Mu#ti.Target Packet
4orwarers
4 classi/ier is a acket /orwardin' obBect wit& multile connectin' tar'ets) It
classi/ies incomin' ackets accordin' to a rede/ined criterion ?e)')* destination
address or transort layer ort@) Packets wit& t&e same cate'ory are /orwarded to
t&e same NsObBect)
NS2 imlements classi/iers usin' t&e concet o/ slots) 4 slot is a lace&older
/or a ointer to an NsObBect) It is associated wit& a acket cate'ory) 6&en a
acket arri1es* a classi/ier determines t&e acket cate'ory and /orwards t&e
acket to t&e NsObBect w&ose ointer was installed in t&e associated slot)
In t&e /ollowin'* we s&all discuss t&e details o/ two main rocesses o/
classi/iers< con/i'uration and internal mec&anism) Con/i'uration de/ines w&at t&e
users ask a classi/ier to er/orm) It includes t&e /ollowin' main stes<
1) .e/ine t&e cate'ories
2) Identi/y a corresondin' slot as well as a /orwardin' NsObBect /or eac&
cate'ory
3) Install t&e NsObBect ointer in t&e selected slot
Internal mec&anism is w&at a classi/ier does to carry out t&e reDuirement
ro1ided by users) It usually be'ins wit& t&e CCC /unction recv&p)(')
Cor eAamle* suose we would like to attac& a node to a transort layer a'ent at
t&e ort number 3,) In t&e con/i'uration* we install t&e a'ent in slot number 3,)
T&e internal mec&anism is to tell t&e classi/ier t&e /ollowin'< send all t&e ackets
w&ose ort number is 3, to t&e NsObBect w&ose ointer is in t&e slot number 3,)
/.2.1 Class Classifier and Its Main
Coponents
NS2 imlements classi/iers in a CCC class Classi"ier ?see t&e declaration
in Pro'ram 8)1@* w&ic& is bound to an OTcl class wit& t&e same name) T&e main
comonents o/ a classi/ier include t&e /ollowin')
6=2=%=% $CC >ariab#es
T&e CCC class Classi"ier &as two key 1ariables< slot5 and
de"a!lt5 tar$et5 ?!ines 13 and 1: in Pro'ram 8)1@) T&e 1ariable slot5
is a link list w&ose entries are ointers to downstream NsObBects) Eac& o/ t&ese
NsObBects corresonds to a rede/ined criterion) Packets matc&in' wit& a
certain criterion are /orwarded to t&e corresondin' NsObBect) T&e 1ariable
de"a!lt5tar$et5 oints to a downstream NsObBect /or ackets w&ic&
do not matc& wit& any rede/ined criterion)
8)2 Classi/iers< %ulti9Tar'et Packet
Corwarders
113
Program 6=% .eclaration o/ class Classi"ier
MMUMnsMclassi"ierMclassi"ierI(
2 class Classi"ier 9 p!blic NsObject 7
1 p!blic9
3 Classi"ier&';
= virt!al UClassi"ier&';
> virt!al void recv&Packet
N
p) Handler
N
(';
A virt!al NsObject
N
"ind&Packet
N
';
B virt!al int classi"y&Packet
N
';
/ virt!al void clear&int slot';
G virt!al void install&int slot) NsObject
N
';
20 inline int ms(i"t&int val' 7ret!rn&&val KK s(i"t5' F
mask5';8
22 protected9
21 virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
23 NsObject
NN
slot5;
2= NsObject
N
de"a!lt5tar$et5;
2> int s(i"t5;
2A int mask5;
2B 8;
T&e class Classi"ier also &a1e two sulementary 1ariables< s(i"t5
?!ine 13@ and mask5 ?!ine 18@) T&ese two 1ariables are used in /unction
ms(i"t &val' ?!ine 1,@ to re/ormat t&e address ?see also Sect) 13):@)
6=2=%=2 $CC 4unctions
T&e main CCC /unctions o/ class Classi"ier are s&own below<
Configuration &unctions
install&slot)p' Store t&e inut NsObject ointer FpG in t&e slot
number Fslot5)
install5ne*t&node' Install t&e NsObject ointer FnodeG in t&e neAt
a1ailable slot)
do5install Similar to install/slot)p' but t&e inut
&dst)tar$et' arameter dst is a strin' instead o/ an inte'er)
clear&slot' (emo1e t&e NsObBect ointer installed in t&e slot
number Fslot)G
ms(i"t&val' S&i/t val to t&e le/t by Fs(i"t5G bits) %asks t&e
s&i/ted 1alue usin' a lo'ical 4N. ?F@ oeration
wit& Fmask5)G
118 8 Nodes as (outers or Comuter Hosts
Packet &orwarding -i*e*= Internal0
&unctions
recv&p)(' (ecei1e a acket
N
p and &andler
N
()
"ind&p' (eturn a /orwardin' NsObBect ointer /or an incomin'
acket
N
p)
classi"y&p' (eturn a slot number w&ose associated criterion matc&es wit&
t&e &eader o/ an incomin' acket
N
p)
6=2=%=* Main $onfiguring 'nterface
CCC &unctions
Pro'ram 8)2 s&ows t&e details o/ key CCC con/i'uration /unctions) Cunction
install&slot)p' stores t&e inut NsObject ointer FpG in t&e slot
number FslotG o/ t&e 1ariable Fslot5G ?!ine 3@) Cunction
install5ne*t&node' installs t&e inut NsObject ointer FnodeG in
t&e neAt a1ailable slot ?!ines
1, and 11@) Cunction do5install&dst)tar$et' con1erts FdstG to be an
inte'er 1ariable ?!ine 21@* and installs t&e NsObBect ointer Ftar$etG in t&e slot
corresondin' to FdstG ?!ine 22@) Cinally* /unction clear&slot' remo1es t&e
installed NsObject ointer /rom t&e slot number FslotG o/ t&e 1ariable
Fslot5G ?!ine 18@)
(Tcl Commands
Class Classi"ier also de/ines t&e /ollowin' key OTcl commands in a
CCC /unction command&III' o/ class Classi"ier ?in t&e /ile
Tns$classi/ier$ classi/ier)cc@)
slot/inde*' (eturn t&e NsObBect stored in t&e slot
number inde*
clear/slot' Clear t&e NsObBect ointer installed in t&e
slot number slot)
install/inde* object' Install object in t&e slot number
inde*)
installNe*t/object' Install object in t&e neAt a1ailable slot)
de"a!lttar$et/object' Store object in t&e CCC 1ariable
de"a!lt5tar$et5)
6=2=%=/ Main 'nterna# Mechanism
4s an NsObBect* a classi/ier recei1es a acket by &a1in' its ustream obBect in1oke
its /unction recv&p)('* assin' a acket ointer FpG and a &andler ointer F(G
as
8)2 Classi/iers< %ulti9Tar'et Packet
Corwarders
112
Program 6=2 Cunctions install* install ne*t* clear* and do install
o/ class Classi"ier
MMUnsMclassi"ierMclassi"ierIcc
2 void Classi"ier99install&int slot) NsObject
N
p'
1 7
3 i" &slot K: nslot5'
= alloc&slot';
> slot5?slot@ : p;
A i" &slot K: ma*slot5'
B ma*slot5 : slot;
/ 8
G int Classi"ier99install5ne*t&NsObject
N
node' 7
20 int slot : ma*slot5 4 2;
22 install&slot) node';
21 ret!rn &slot';
23 8
2= void Classi"ier99clear&int slot'
2> 7
2A slot5?slot@ : 0;
2B i" &slot :: ma*slot5'
2/ ,(ile &JJma*slot5 K: 0 FF slot5?ma*slot5@ :: 0';
2G 8
MMUnsMclassi"ierMclassi"ierI(
10 virt!al void do5install&c(ar
N
dst) NsObject
N
tar$et' 7
12 int slot : atoi&dst';
11 install&slot) tar$et';
13 8
inut ar'uments) In Pro'ram 8)3* !ine 3 determines a /orwardin' NsObBect
FnodeG /or an incomin' acket
N
p* by in1okin' /unction "ind&
N
p') T&en* !ine
" asses t&e acket ointer FpG and t&e &andler ointer F(G to its /orwardin'
NsObBect
N
node by eAecutin' nodeJ
Krecv&p)(')
Cunction "ind&p' ?!ines 1,H1" in Pro'ram 8)3@ eAamines t&e incomin'
acket
N
p and retrie1es t&e matc&ed NsObject ointer installed in t&e 1ariable
slot5) !ine 13 in1okes /unction classi"y&p' to retrie1e t&e slot number
?i)e)* t&e 1ariable cl@ corresondin' to t&e acket
N
p) T&en* !ines 1: and 12
return t&e NsObject ointer ?i)e)* node@ stored in t&e slot number cl o/ t&e
1ariable slot5)
Cunction classi"y&p' is er&as t&e most imortant /unction o/ a clas9
si/ier) T&is is t&e lace w&ere t&e classi/ication criterion is de/ined) Cunction
classi"y&p' returns t&e slot number w&ic& matc&es wit& t&e inut acket
N
p under t&e rede/ined criterion) Since t&e classi/ication criteria could be
di//erent /or di//erent tyes o/ classi/iers* /unction classi"y&p' is usually
11" 8 Nodes as (outers or Comuter Hosts
Program 6=* Cunctions recv and "ind o/ class
Classi"ier
MMUMnsMclassi"ierMclassi"ierIcc
2 void Classi"ier99recv&Packet
N
p) Handler
N
('
1 7
3 NsObject
N
node : "ind&p';
= i" &node :: NDLL' 7
> Packet99"ree&p';
A ret!rn;
B 8
/ nodeJKrecv&p)(';
G 8
20 NsObject
N
Classi"ier99"ind&Packet
N
p'
22 7
21 NsObject
N
node : NDLL;
23 int cl : classi"y&p';
2= i" &cl < 0 XX cl K: nslot5 XX &node : slot5?cl@' :: 0' 7
2> M
N
T(ere is no potential tar$et in t(e slot;
N
M
2A 8
2B ret!rn &node';
2/ 8
Program 6=/ Cunction classi"y o/ class PortClassi"ier
MMUnsMclassi"ierMclassi"ierJportIcc
2 int PortClassi"ier99classi"y&Packet
N
p'
1 7
3 (dr5ip
N
ip( : (dr5ip99access&p';
= ret!rn ip(JKdport&';
> 8
o1erridden in t&e deri1ed classes o/ class Classi"ier) In Sects) 8)2)2 and 8)2)3*
we s&ow two eAamle imlementations o/ /unction classi"y&p' in classes
PortClassi"ier and DestHas(Classi"ier* resecti1ely)
/.2.2 Port Classifiers
.eri1ed /rom class Classi"ier* class PortClassi"ier classi/ies ackets
based on t&e destination ort) Crom !ines 3 and : in Pro'ram 8):* /unction
classi"y&p' returns t&e destination ort number o/ t&e IP &eader o/ t&e
incomin' acket
N
p)
4 ort classi/ier is used as a demultileAer w&ic& brid'es a node to recei1in'
transort layer a'ents) It determines t&e transort layer ort number stored in
t&e &eader o/ t&e recei1ed acket
N
p) Suose t&e ort number is cl) T&en t&e
8)2 Classi/iers< %ulti9Tar'et Packet
Corwarders
11#
4ig= 6=2 Has& terminolo'y and rele1ant /unctions o/ class Has(Classi"ier
acket is /orwarded to t&e NsObBect associated wit& slot5?cl@) +y installin' a
ointer to a recei1in' transort layer a'ent in slot5?cl@* t&e classi/ier /orwards
ackets w&ose destination ort is FclG to t&e associated a'ent) T&e details o/ &ow
a ort classi/ier brid'es a Node to a transort layer a'ent will be discussed later in
Sect) 8)3)3)
/.2." 7ash Classifiers
Crom Ci') 8)1* anot&er imortant classi/ier in a Node is address classi/ier) In NS2*
address classi/iers are imlemented in so9called &as& classi/iers)
6=2=*=% An ,verview of Hash $#assifiers
Has& table is a data structure w&ic& /acilitates a key91alue looku rocess)
1
T&e
looku rocess is /acilitated by &as&in' t&e key into a readily mana'eable /orm)
T&e results are stored in a so9called &as&9table) T&e looku is carried out o1er t&e
&as& table instead o/ t&e ori'inal table to eAedite t&e looku rocess)
+e/ore roceedin' /urt&er* let us introduce t&e /ollowin' &as&in'
terminolo'ies) In t&is resect* consider* as an eAamle* a &as& classi/ier w&ic&
classi/ies ackets based on t&ree inut arameters< /low I.* source address* and
destination address in Ci') 8)2)
1
Suose we &a1e a table w&ic& associates keys and 1alues) Li1en a key* t&e looku
rocess searc&es in t&e table /or t&e matc&ed key* and returns t&e corresondin' 1alue)
12, 8 Nodes as (outers or Comuter Hosts
+ key< Keywords we would like to /ind ?e)')* /low I.* source address* and
destination address@
+ value< 4n entry aired wit& a key ?e)')* a ointer to an
NsObBect@
+ hash function< 4 /unction w&ic& &as&es ?i)e)* trans/orms@ a key into a &as&
key
+ hash key< 4 trans/ormed keyO a looku rocess will searc& o1er &as& keys*
rat&er t&an t&e ori'inal keys)
+ hash value< 4n entry aired wit& a &as& key ?e)')* indeA o/ t&e 1ariable
slot5@
+ lookup ta'le< 4 table consists o/ ?key*1alue@
airs)
+ hash ta'le< 4 table consists o/ ?&as&9key* &as&91alue@
airs)
+ record -or an entry0< 4 air o/
?key*1alue@
+ hash record -or a hash entry0< 4 air o/ ?&as&91alue* &as&9
1alue@
2
4ddress classi/iers classi/y ackets based on t&e destination address) In t&is
resect* an address and an NsObBect are 1iewed as a key and a 1alue* resecti1ely)
4 &as& classi/ier &as&es an address into a &as& key ?internal to NS2@* w&ic& is
associated wit& a &as& 1alue ?i)e)* t&e slot number in w&ic& t&e NsObBect is
installed@ by t&e underlyin' &as& table) 6&en recei1in' a acket* an address
classi/ier looks u t&e slot number /rom t&e &as& table* rat&er t&an t&e ori'inal
looku table) T&is eliminates t&e need to comare records one by one and 'reatly
eAedites t&e looku rocess)
6=2=*=2 $CC 'm&#ementation of $#ass HashClassifier
T&e &as& classi/iers classi/y ackets based on one or more o/ t&e /ollowin'
criteria< /low I.* source address* and destination address) NS2 de/ines a CCC
class Has(Classi"ier as a temlate) 4ll t&e &eler /unctions are de/ined &ere*
but t&e key /unction classi"y&p'* w&ic& de/ines acket classi/ication criteria* is
de/ined by its deri1ed classes)
Pro'ram 8)3 s&ows t&e details o/ a CCC class Has(Classi"ier w&ic& is
maed to an OTcl class Classi"ierMHas() Class Has(Classi"ier &as
t&ree main 1ariables) Cirst* 1ariable de"a!lt5 ?!ine 13@ contains t&e de/ault slot
/or a acket w&ic& does not matc& wit& any entry in t&e table) Second* 1ariable
(t5 ?!ine 18@ is t&e &as& table) Cinally* 1ariable keylen5 ?!ine 12@ is t&e
number o/ comonents in a key) +y de/ault* a key consists o/ /low I.* source
address* and destination address* and t&e 1alue o/ keylen5 is 3)
T&e key /unctions o/ class Has(Classi"ier are s&own below ?see also
Ci') 8)2@<
8)2 Classi/iers< %ulti9Tar'et Packet
Corwarders
121
2
Since a record and a &as& record &a1e one9to9one relations&i* we s&all use t&ese two terms
interc&an'eably)
12, 8 Nodes as (outers or Comuter Hosts
Program 6=0 .eclaration o/ class Has(Classi"ier
MMUnsMclassi"ierMclassi"ierJ(as(I(
2 class Has(Classi"ier 9 p!blic Classi"ier 7
1 p!blic9
3 Has(Classi"ier&int keylen'9 de"a!lt5&J2')
keylen5&keylen';
= UHas(Classi"ier&';
> virt!al int classi"y&Packet
N
p';
A virt!al lon$ look!p&Packet
N
p' ;
B void set5de"a!lt&int slot' 7 de"a!lt5 : slot; 8
/ protected9
G lon$ look!p&nsaddr5t src) nsaddr5t dst) int "id';
20 void reset&';
22 int set5(as(&nsaddr5t src) nsaddr5t dst) int "id) lon$
slot';
21 lon$ $et5(as(&nsaddr5t src) nsaddr5t dst) int "id';
23 virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
2= virt!al const c(ar
N
(as(key&nsaddr5t) nsaddr5t) int':0;
2> int de"a!lt5;
2A Tcl5Has(Table (t5;
2B int keylen5;
2/ 8;
look!p&p' (eturn t&e slot number w&ic& matc&es wit& t&e in9
comin' acket p)
look!p&src)III
(eturn t&e slot number w&ose corresondin'
dst)"id' source address* destination address* and /low I.
are src* dst* and "id* resecti1ely)
set5(as(&src)III Has& t&e key ?src)dst)"id@ into a &as& key* and
dst)"id)slot' associates t&e &as& key wit& t&e slot number slot)
$et5(as(&src)III (eturn t&e slot number w&ic& matc&es wit& t&e
dst)"id'
key ?src)dst)"id@)
(as(key&src)III' (eturn a &as& key /or t&e inut key ?src)dst)"id@)
dst)"id' T&is /unction is ure 1irtual and s&ould be
o1erridden by c&ild classes o/ class
Has(Classi"ier)
Pro'ram 8)8 s&ows t&e details o/ /unctions look!p&p' and
$et5(as(&src) dst)"id' o/ class Has(Classi"ier) Cunction
look!p&p' retrie1es a key associated wit& t&e acket
N
p) It t&en asks t&e
/unction $et5(as(&III' /or t&e corresondin' &as& 1alue ?i)e)* slot number@)
In !ine 8* /unction $et5(as(&III' in1okes /unction (as(key&III'
to determine t&e &as& key corresondin' to t&e inut key ?src)dst)"id@)
T&en* /unction Tcl5QindHas(Entry )< < <$ locates t&e &as& record in t&e
&as& table w&ic& matc&es wit& t&e &as& key) I/ t&e record was /ound* /unction
Tcl5-etHas( Sal!e&ep' will retrie1e and return t&e corresondin'
&as& 1alue ?i)e)* slot
8)2 Classi/iers< %ulti9Tar'et Packet
Corwarders
123
Program 6=6 Cunctions look!p and $et (as( o/ class Has(Classi"ier
MMUnsMclassi"ierMclassi"ierJ(as(Icc
2 lon$ Has(Classi"ier99look!p&Packet
N
p' 7
1 (dr5ip
N
( : (dr5ip99access&p';
3 ret!rn $et5(as(&ms(i"t&(JKsaddr&'')ms(i"t&(JKdaddr&'')
(JK"lo,id&'';
= 8
> lon$ Has(Classi"ier99$et5(as(&nsaddr5t src)
nsaddr5t dst) int "id' 7
A Tcl5Has(Entry
N
ep: Tcl5QindHas(Entry&F(t5)
(as(key&src) dst) "id'';
B i" &ep'
/ ret!rn &lon$'Tcl5-etHas(Sal!e&ep';
G ret!rn J2;
20 8
number@ to t&e caller) Note t&at t&e /unction (as(key&III' is declared as ure
1irtual in class Has(Classi"ier and must be o1erridden by t&e c&ild classes
o/ class Has(Classi"ier)
6=2=*=* $hi# $#asses of $#ass HashClassifier
Class Has(Classi"ier &as /our maBor c&ild classes ?class names on t&e le/t
and ri'&t are comiled and interreted classes* resecti1ely@<
DestHas(Classi"ier * Classi"ierMHas(MDest< classi/ies
ackets based on t&e destination address)
SrcDestHas(Classi"ier * Classi"ierMHas(MSrcDest<
classi/ies ackets based on source and destination addresses)
QidHas(Classi"ier * Classi"ierMHas(MQid< classi/ies
ackets based on a /low I.)
SrcDestQidHas(Classi"ier *
Classi"ierMHas(MSrcDestQid<
classi/ies ackets based on source address* destination address* and /low
I.)
6=2=*=/ $CC $#ass DestHashClassifier
4s an eAamle* consider class DestHas(Classi"ier ?Pro'ram 8)2@* a c&ild
class o/ class Has(Classi"ier* w&ic& classi/ies incomin' ackets by t&e
destination address only) Class DestHas(Classi"ier o1errides /unctions
classi"y&p'* do5install&dst)tar$et'* and (as(key&III'* and uses
ot&er /unctions ?e)')* look!p&p'@ o/ class Has(Classi"ier ?i)e)* its arent
class@)
122 8 Nodes as (outers or Comuter Hosts
Program 6=5 .eclaration o/ class DestHas(Classi"ier
MMUnsMclassi"ierMclassi"ierJ(as(I(
2 class DestHas(Classi"ier 9 p!blic Has(Classi"ier 7
1 p!blic9
3 DestHas(Classi"ier&' 9 Has(Classi"ier&TCL5ONE5WO#D5VE[S'
78
= virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
> int classi"y&Packet
N
p';
A virt!al void do5install&c(ar
N
dst) NsObject
N
tar$et';
B protected9
/ const c(ar
N
(as(key&nsaddr5t) nsaddr5t dst) int' 7
G lon$ key : ms(i"t&dst';
20 ret!rn &const c(ar
N
' key;
22 8
21 8;
Program 6=7 Cunctions classi"y and do install o/ class DestHas(
Classi"ier
MMUnsMclassi"ierMclassi"ierJ(as(Icc
2 int DestHas(Classi"ier99classi"y&Packet
N
p' 7
1 int slot : look!p&p';
3 i" &slot K: 0 FF slot <:ma*slot5'
= ret!rn &slot';
> else i" &de"a!lt5 K: 0'
A ret!rn &de"a!lt5';
B else ret!rn &J2';
/ 8
G void DestHas(Classi"ier99do5install&c(ar
N
dst) NsObject
N
tar$et' 7
20 nsaddr5t d : atoi&dst';
22 int slot : $etn*t&tar$et';
21 install&slot) tar$et';
23 i" &set5(as(&0) d) 0) slot' < 0'
2= M
N
s(o, error
N
M
2> 8
Pro'ram 8)" s&ows t&e imlementation o/ /unction classi"y&p' o/ class
DestHas(Classi"ier) T&is /unction obtains a matc&in' slot number FslotG
by in1okin' look!p&p' ?!ine 2O See also Ci') 8)3@* and returns FslotG i/ it is
1alid ?!ine :@) Ot&erwise* !ine 8 will return t&e 1ariable Fde"a!lt5)G
3
I/ neit&er
slot nor de"a!lt5 is 1alid* !ine 2 will return H1* indicatin' no matc&in'
entry in t&e &as& table)
3
T&e 1ariable Fde"a!lt G contains t&e de/ault slot number) It is de/ined on !ine 13 o/
Pro'ram 8)3)
8)3 (outin' %odules 123
=etrie(in4 source address (src)D
destination address (dst)D and flo> /D (fid)
from the header of 6ac1et 6
src dst fid
hash1ey(srcD dstD fid)
(const charI) mshift(dst)
e6@'clC.indHash+ntry(JhtCD )
e6
4ig= 6=* Clowc&art o/
/unction look!p&p'
in1oked /rom class
DestHas(Classi"ier
loo1u6(6)
6
4etChash(srcD dstD fid)
dst
Hash0lassifier
Hash0lassifier
DestHash0lassifier
(lon4)'clCKetHash9alue(e6)
=eturn slot
number
Cunction do5install&dst)tar$et' installs ?!ine 12@ an NsObject
ointer tar$et in t&e neAt a1ailable slot* and re'isters t&is installation in t&e
&as& table ?!ine 13@) .e/ined in class Classi"ier* /unction
$etn*t&tar$et' returns t&e a1ailable slot w&ere tar$et will be installed
?see /ile Tns$classi/ier$ classi/ier)cc@) 4'ain* t&e statement
set5(as(&0)d)0)slot' &as&es t&e key wit& source address F0*G
destination address Fd*G and /low I. F0*G and associates t&e result wit& t&e slot
number Fslot)G Cinally /unction (as(key&III' in !ines "H11 o/ Pro'ram
8)2 returns t&e destination address* re/ormatted by /unction ms(i"t&III')
Ci'ure 8)3 s&ows a rocess w&en a DestHas(Classi"ier obBect in1okes
/unction look!p&p') In t&is /i'ure* t&e /unction name is indicated at t&e to
o/ eac& boA* w&ile t&e corresondin' class is s&own in t&e ri'&t o/ a block
arrow) T&e rocess /ollows w&at we &a1e discussed earlier) T&e imortant oint
&ere is t&at t&e only /unction de/ined in class DestHas(Classi"ier is t&e
/unction (as(key&III') Cunctions look!p&p' and $et5(as(&III'
belon' to class Has(Classi"ier) T&is is a beauty o/ OOP* since we only
need to o1erride one /unction /or a deri1ed class ?e)')* class
DestHas(Classi"ier@* and are able to reuse t&e rest o/ t&e code /rom
t&e arent class ?e)')* class Has(Classi"ier@)
!ater in Sect) 8)3):* we s&all discuss &ow a destination &as& classi/ier is used to
er/orm routin' /unctionality)
/.2.$ Creating 6o!r O&n
Classifiers
Here are t&e key stes /or de/inin' your own
classi/iers)
1) 4esign< .e/ine criteria wit& tules &criterion)slot)NsObject') I/ a
acket matc&es wit& t&e criterion* send t&e acket to t&e NsObject
installed in slot5?slot@)
2) Class construction< .eri1e your CCC classi/ier class* /or eAamle* class
[o!rClassi"ier /rom class Classi"ier) Create a s&adow OTcl class)
3) Internal mechanism< O1erride /unction classi"y&p' accordin' to t&e
desi'n
in Ste 1)
:) Configuration< In t&e OTcl domain* install t&e NsObject in t&e slot number
slot o/ t&e [o!rClassi"ier obBect) Cor eAamle* let Pcls"r be a
[o!rClassi"ier obBect and and Pobj be an NsObBect in t&e OTcl
domain) ;ou can install Pobj in t&e slot number 1, o/ Pcls"r by
eAecutin' t&e /ollowin' statement< Pcls"r install 20 Pobj)
6=* Routing Mou#es
/.".1 An O#er#ie& of Ro!ting Mod!les
T&e main /unctionality o/ routin' modules is to /acilitate classi/ier mana'ement)
Cor eAamle* consider Ci') 8):* w&ere ten address classi/iers are connected to eac&
ot&er) It would be rat&er incon1enient to con/i'ure all t&ese ten classi/iers usin'
ten OTcl statements)
T&e con/i'uration rocess can be /acilitated by maintainin' a linear toolo'y)
E1en i/ t&e toolo'y o/ classi/iers is as comlicated as a /ull mes&* t&e toolo'y
o/ routin' modules is always linear) 6e can /eed a con/i'uration command to t&e
/irst routin' module in line* and let t&e routin' modules roa'ate t&e
con/i'uration command toward t&e end o/ t&e line) Since e1ery classi/ier is
connected to one o/ t&ese routin' modules* t&e con/i'uration command will
e1entually reac& all t&e classi/iers)
+ased on t&e abo1e idea* NS2 uses t&e /ollowin' route con/i'uration rinciles<
1) 4ssi'n a routin' module /or a classi/ier and connect all related routin' modules
in a linear toolo'y)
2) Con/i'ure classi/iers t&rou'& t&e &ead routin' module
only)
3) .isallow direct classi/ier
con/i'uration)
T&ese rinciles are imlemented in 1arious NS2 comonents suc& as routin'
a'ents* t&e route lo'ic* and Nodes) 4s we s&all see later on* class Node makes
no
8)3 (outin' %odules 122
=
o
u
t
i
n
4

M
o
d
u
l
e
s
:
:
:
=M1
nextCrtmC
classifierC
=M2
nextCrtmC
classifierC
:::
=M11
nextCrtmC
!
classifierC
Port0lassifier
,4ent
slot 1!
slot 1
,ddress classifier 1!
,4ent
.lo> classifer
(classifierC)
,ddress classifier 1
Lin1 Lin1
4ig= 6=/ T&e relations&i amon' routin' modules and classi/iers in a node
attemt to directly modi/y its classi/iers ?e)')* inst1ars classi"ier5 and
dm!*5 in Ci') 8)1@) Instead* it ro1ides instrocs addJro!te/III' and
attac(/III'* w&ic& ask t&e related routin' modules to roa'ate t&e
con/i'uration commands on its be&al/)
/.".2 CCC Class Routingodule
Pro'ram 8)# s&ows t&e declaration o/ class #o!tin$%od!le* w&ic& &as t&ree
main 1ariables) 7ariable classi"ier5 in !ine 13 is a ointer to a
Classi"ier obBect) T&is 1ariable is bound to an OTcl inst1ar wit& t&e same
name ?!ine 28@)
4 linear toolo'y o/ routin' modules is created usin' o/ a ointer ne*t5rtm5
?!ine 12@* w&ic& oints to anot&er #o!tin$%od!le obBect) Cinally* 1ariable
Fn5G in !ine 1: is a ointer to t&e associated Node obBect) T&ese t&ree
1ariables are initialiJed to NDLL in t&e constructor ?!ine 13@)
T&e key /unctions o/ class #o!tin$%od!le include t&e /ollowin's ?see
Pro'ram 8)1,@<
Program 6=8 .eclaration and t&e constructor o/ a CCC class #o!tin$%od!le
w& ic& is bound to an OTcl c la ss #t%od!le
MMUnsMro!tin$Mrtmod!leI(
2 class #o!tin$%od!le 9 p!blic TclObject 7
1 p!blic9
3 #o!tin$%od!le&';
= inline Node
N
node&' 7 ret!rn n5; 8
> virt!al int attac(&Node
N
n' 7 n5 : n; ret!rn TCL5OV; 8
A virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
B virt!al const c(ar
N
mod!le5name&' const 7 ret!rn NDLL; 8
/ void ro!te5noti"y&#o!tin$%od!le
N
rtm';
G void !nre$5ro!te5noti"y&#o!tin$%od!le
N
rtm';
20 virt!al void add5ro!te&c(ar
N
dst) NsObject
N
tar$et';
22 virt!al void delete5ro!te&c(ar
N
dst) NsObject
N
n!lla$ent';
21 #o!tin$%od!le
N
ne*t5rtm5;
23 protected9
2= Node
N
n5;
2> Classi"ier
N
classi"ier5;
2A 8;
2B static class #o!tin$%od!leClass 9 p!blic TclClass 7
2/ p!blic9
2G #o!tin$%od!leClass&' 9 TclClass&H#t%od!leH' 78
10 TclObject
N
create&int) const c(ar
N
const
N
' 7
12 ret!rn &ne, #o!tin$%od!le';
11 8
13 8 class5ro!tin$5mod!le;
1= #o!tin$%od!le99#o!tin$%od!le&' 9
1> ne*t5rtm5&NDLL') n5&NDLL') classi"ier5&NDLL' 7
1A bind&Hclassi"ier5H) &TclObject
NN
'Fclassi"ier5';
1B 8
node&' (eturn t&e attac&ed Node obBect n5)
attac(&n' Store an inut Node obBect FnG in t&e
1ariable n5)
mod!le5name&' (eturn t&e name o/ t&e routin' module)
ro!te5noti"y&rtm' 4dd an inut #o!tin$%od!le
N
rtm
to t&e end o/ t&e link list)
!nre$5ro!te5noti"y&rtm' (emo1e an inut #o!tin$%od!le
ointer
N
rtm /rom t&e link list)
add5ro!te&dst)tar$et' In/orm e1ery classi/ier associated wit&
t&e link list to add a routin' rule
&dst)tar$et')
delete5ro!te&III In/orm e1ery classi/ier in t&e link list to
dst)n!lla$ent'
delete a routin' rule wit& destination dst)
8)3 (outin' %odules 12#
Program 6=%: Cunctions ro!te noti"y* !nre$ ro!te noti"y*
add ro!te* and delete ro!te o/ class #o!tin$%od!le
MMUnsMro!tin$Mrtmod!leIcc
2 void #o!tin$%od!le99ro!te5noti"y&#o!tin$%od!le
N
rtm' 7
1 i" &ne*t5rtm5 C: NDLL'
3 ne*t5rtm5JKro!te5noti"y&rtm';
= else
> ne*t5rtm5 : rtm;
A 8
B void #o!tin$%od!le99!nre$5ro!te5noti"y&#o!tin$%od!le
N
rtm' 7
/ i" &ne*t5rtm5' 7
G i" &ne*t5rtm5 :: rtm' 7
20 ne*t5rtm5 : ne*t5rtm5JKne*t5rtm5;
22 8
21 else 7
23 ne*t5rtm5JK!nre$5ro!te5noti"y&rtm';
2= 8
2> 8
2A 8
2B void #o!tin$%od!le99add5ro!te&c(ar
N
dst) NsObject
N
tar$et'
2/ 7
2G i" &classi"ier5'
10 classi"ier5JKdo5install&dst)tar$et';
12 i" &ne*t5rtm5 C: NDLL'
11 ne*t5rtm5JKadd5ro!te&dst)tar$et';
13 8
1= void #o!tin$%od!le99delete5ro!te&c(ar
N
dst) NsObject
N
n!lla$ent'
1> 7
1A i" &classi"ier5'
1B classi"ier5JKdo5install&dst)n!lla$ent';
1/ i" &ne*t5rtm5'
1G ne*t5rtm5JKadd5ro!te&dst)n!lla$ent';
30 8
Consider Pro'ram 8)1,) !ines 1H18 s&ow t&e details o/ /unctions ro!te5
noti"y&rtm'and !nre$5ro!te5noti"y&rtm') Cunction ro!te5noti"y
&rtm' recursi1ely in1okes itsel/ ?!ine 3@ until it reac&es t&e last routin' mod9
ule in t&e link list* w&ere ne*t5rtm5 is NDLL) T&en* it attac&es t&e inut
routin' module
N
rtm as t&e last comonent o/ t&e link list ?!ine 3@) Cunction
!nre$5ro!te5noti"y&rtm' recursi1ely searc&es down t&e link list ?!ine
13@ until it /inds and remo1es t&e inut routin' module ointer FrtmG ?!ines # and
1,@)
!ines 12H3, s&ow t&e details o/ /unctions add5ro!te&dst) tar$et'
and delete5ro!te&dst)n!lla$ent') Cunction
add5ro!te&dst)tar$et' takes a destination node FdstG and a /orwardin'
NsObject ointer Ftar$etG as inut ar'uments) It installs t&e ointer
Ftar$etG in all t&e associated classi/iers
12" 8 Nodes as (outers or Comuter Hosts
?!ine 2,@) 4'ain* t&is routin' rule is roa'ated down t&e link list ?!ine 22@*
until reac&in' t&e last element o/ t&e link list) Cunction delete5ro!te&dst)
n!lla$ent' does t&e oosite) It recursi1ely installs a null a'ent
Fn!lla$entG ?i)e)* a acket droin' oint@ as t&e tar'et /or ackets destined
/or a destination node FdstG in all t&e classi/iers* essentially remo1in' t&e
routin' rule wit& t&e destination FdstG /rom all t&e classi/iers)
/."." OTcl Class Rtodule
In t&e OTcl domain* t&e routin' module is de/ined in class #t%od!le bound
to t&e CCC class #o!tin$%od!le) Class #t%od!le &as two inst1ars<
classi"ier5 and ne*t5rtm5) T&e inst1ar classi"ier5 is bound to t&e
class 1ariable in t&e CCC domain wit& t&e same name* w&ile t&e inst1ar ne*t5
rtm5 is not)
:
T&e OTcl class #t%od!le also de/ines t&e /ollowin' instrocs and OTcl
commands) Cor bre1ity* we s&ow t&e details o/ some instrocs in Pro'ram 8)11)
T&e details o/ ot&er instrocs and OTcl command can be /ound in /ile
Tns$tcl$lib$ns9 rtmodule)tcl and Tns$routin'$rtmodule)cc* resecti1ely)
6=*=*=% 'nitia#iCation 'nst&rocs
re$ister/node' Create two9way connection to t&e in9
ut node ?!ines 1H13@)
!nre$ister/' (emo1e itsel/ /rom t&e associated
node and t&e c&ain o/ routin'
modules ?see t&e /ile@)
attac(Jnode/node' Set t&e CCC 1ariable n5 to oint to
t&e inut node ?OTcl commandO see
t&e /ile@)
ro!teJnoti"y/mod!le' Store t&e incomin' mod!le as t&e
last element in t&e OTcl c&ain o/
rout9 in' modules ?!ines 1:H21@)
!nre$Jro!teJnoti"y/mod!le' (emo1e t&e incomin' mod!le /rom
t&e OTcl c&ain o/ routin' modules
?see t&e /ile@)
:
Caution< 6&en creatin' a c&ain o/ routin' modules* use instroc ro!te noti"y/III') I/
you directly con/i'ure t&e inst1ar ne*t rtm * t&e CCC 1ariable ne*t rtm will not
be automatically con/i'ured)
8)3 (outin' %odules 131
Program 6=%% (elated Instrocs o/ OTcl classes #t%od!le and #t%od!leM
.ase
MMUMnsMtclMlibMnsJrtmod!leItcl
2 #t%od!le instproc re$ister 7 node 8 7
1 Psel" attac(Jnode Pnode
3 Pnode ro!teJnoti"y Psel"
= Pnode portJnoti"y Psel"
> 8
A #t%od!leM.ase instproc re$ister 7 node 8 7
B Psel" ne*t Pnode
/ Psel" instvar classi"ier5
G set classi"ier5 ?ne, Classi"ierMHas(MDest 31@
20 Pclassi"ier5 set mask5 ?AddrParams Node%ask 2@
22 Pclassi"ier5 set s(i"t5 ?AddrParams NodeS(i"t 2@
21 Pnode installJentry Psel" Pclassi"ier5
23 8
2= #t%od!le instproc ro!teJnoti"y 7 mod!le 8 7
2> Psel" instvar ne*t5rtm5
2A i" 7Pne*t5rtm5 :: HH8 7
2B set ne*t5rtm5 Pmod!le
2/ 8 else 7
2G Pne*t5rtm5 ro!teJnoti"y Pmod!le
10 8
12 8
11 #t%od!le instproc addJro!te 7 dst tar$et 8 7
13 Psel" instvar ne*t5rtm5
1= ?Psel" set classi"ier5@ install Pdst Ptar$et
1> i" 7Pne*t5rtm5 C: HH8 7
1A Pne*t5rtm5 addJro!te Pdst Ptar$et
1B 8
1/ 8
1G #t%od!le instproc attac( 7 a$ent port 8 7
30 Pa$ent tar$et ??Psel" node@ entry@
32 ??Psel" node@ dem!*@ install Pport Pa$ent
31 8
6=*=*=2 'nst&rocs for $onfiguring $#assifiers
addJro!te/dst tar$et' Proa'ate a routin' rule ?dst)
tar$et@ to all t&e attac&ed classi9
/iers ?!ines 22H2"@)
deleteJro!te/dst n!lla$ent' (emo1e a routin' rule w&ose desti9
nation is FdstG ?see t&e /ile@)
13, 8 Nodes as (outers or Comuter Hosts
attac(/a$ent port' Install t&e Fa$entG in t&e slot number FportG
o/ t&e demultileAer Fdm!*5G o/ t&e associated
Node ?!ines 2#H32@) 6e s&all discuss t&e details
o/ transort layer a'ent attac&ment in Sect) 8)3)3)
/.".$ 2!ilt(in Ro!ting Mod!les
6=*=/=% The +ist of Bui#t.in Routing Mou#es
T&e CCC class #o!tin$%od!le and t&e OTcl class #t%od!le are not
actually in use) T&ey are Bust t&e base classes /rom w&ic& t&e /ollowin' routin'
module classes deri1e)
(ou ti n ' m odu l e C CC c l ass O Tcl c l ass
(outin' module #o!tin$%od!le #t%od!le
+ase routin' module ?de/ault@ .ase#o!tin$%od!le #t%od!leM.ase
%ulticast routin' module %cast#o!tin$%od!le #t%od!leM%cast
Hierarc&ical routin' module Hier#o!tin$%od!le #t%od!leMHier
%anual routin' module %an!al#o!tin$%od!le #t%od!leM%an!al
Source routin' module So!rce#o!tin$%od!le #t%od!leMSo!rce
Iuick start /or TCP$IP routin' module
?determine initial con'estion window@
S#o!tin$%od!le #t%od!leMS
7irtual classi/ier routin' module SC#o!tin$%od!le #t%od!leMSC
Pra'matic 'eneral multicast routin'
module ?reliable multicast@
!i'&t9wei'&t multicast ser1ices routin'
module ?reliable multicast@
P$m#o!tin$%od!le #t%od!leMP-%
Lms#o!tin$%od!le #t%od!leML%S
4mon' t&ese classes* t&e base routin' module are t&e most widely used) 4s an
eAamle* we s&all discuss t&e details o/ t&e base routin' module)
6=*=/=2 $CC $#ass !aseRoutingodule an ,Tc#
$#ass
Rtodule"!ase
+ase routin' modules are t&e de/ault routin' modules used /or static routin')
4'ain* t&ey are reresented in t&e CCC class .ase#o!tin$%od!le bound
to t&e OTcl class #t%od!leM.ase) Crom Pro'ram 8)12* class
.ase#o!tin$%od!le deri1es /rom class #o!tin$%od!le) It o1errides
/unction mod!le5name&'* by settin' its name to be F.aseG ?!ine :@) 4 base
routin' module classi/ies ackets based on its destination address only) T&ere/ore*
t&e tye o/ t&e 1ariable classi"ier5 is de/ined as a
DestHas(Classi"ier ointer ?!ine 2@)
8): (oute !o'ic 133
Program 6=%2 .eclaration o/ class .ase#o!tin$%od!le w&ic& is bound to
t&e
OTcl class #t%od!leM.ase
MMUnsMro!tin$Mrtmod!leI(
2 class .ase#o!tin$%od!le 9 p!blic #o!tin$%od!le 7
1 p!blic9
3 .ase#o!tin$%od!le&' 9 #o!tin$%od!le&' 78
= virt!al const c(ar
N
mod!le5name&' const 7 ret!rn H.aseH;
8
> virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
A protected9
B DestHas(Classi"ier
N
classi"ier5;
/ 8;
MMUnsMro!tin$Mrtmod!leIcc
G static class .ase#o!tin$%od!leClass 9 p!blic TclClass 7
20 p!blic9
22 .ase#o!tin$%od!leClass&' 9 TclClass&H#t%od!leM.aseH' 78
21 TclObject
N
create&int) const c(ar
N
const
N
' 7
23 ret!rn &ne, .ase#o!tin$%od!le';
2= 8
2> 8 class5base5ro!tin$5mod!le;
In t&e OTcl domain* class #t%od!leM.ase also o1errides instroc
re$ister/node' o/ class #t%od!le ?!ines 8H13 in Pro'ram 8)11@) In
addition to creatin' a two9way connection to t&e inut Node obBect node
?er/ormed by its base class@* t&e base routin' module creates ?!ine #@ and
installs ?!ine 12@ a destination &as& classi/ier inside t&e node) 6e s&all discuss
t&e details o/ t&e instroc installJentry/III' later in Sect) 8)3)2)
6=/ Route +ogic
T&e main resonsibility o/ a route lo'ic obBect is to comute t&e routin' table)
(oute lo'ic is imlemented in a CCC class #o!teLo$ic w&ic& is bound to
t&e OTcl class wit& t&e same name ?see Pro'ram 8)13@)
/.$.1 CCC Ipleentation
T&e CCC Class #o!teLo$ic &as two key 1ariables< Fadj5G ?!ine 1:@* w&ic&
is t&e adBacency matriA used to comute t&e routin' table* and Fro!te5G ?!ine
13@* w&ic& is t&e routin' table) It &as t&e /ollowin' t&ree main /unctions<
132 8 Nodes as (outers or Comuter Hosts
Program 6=%* .eclaration o/ class #o!teLo$ic and t&e corresondin' OTcl
main' class
MMUMnsMro!tin$Mro!teI(
2 class #o!teLo$ic 9 p!blic TclObject 7
1 p!blic9
3 #o!teLo$ic&';
= U#o!teLo$ic&';
> int command&int ar$c) const c(ar
N
const
N
ar$v';
B virt!al int look!p5"lat&int sid) int did';
/ protected9
G void reset&int src) int dst';
20 void reset5all&';
22 void comp!te5ro!tes&';
21 void insert&int src) int dst) do!ble cost';
23 void insert&int src) int dst) do!ble cost) void
N
entry';
2= adj5entry
N
adj5;
2> ro!te5entry
N
ro!te5;
2A 8;
MMUMnsMro!tin$Mro!teIcc
2B class #o!teLo$icClass 9 p!blic TclClass 7
2/ p!blic9
2G #o!teLo$icClass&' 9 TclClass&H#o!teLo$icH' 78
10 TclObject
N
create&int) const c(ar
N
const
N
' 7
12 ret!rn &ne, #o!teLo$ic&'';
11 8
13 8 ro!telo$ic5class;
insert&src)III In/orm t&e route lo'ic o/ t&e cost to 'o /rom t&e
dst)cost'
Node src to t&e Node dst
comp!te5ro!tes&' Comute t&e otimal routes /or all source9
destination airs and store t&e comuted routes in
t&e 1ariable ro!te5)
look!p5"lat&III
Searc& wit&in t&e 1ariable ro!te /or an entry
sid)did' wit& matc&in' source I. ?sid@ and destination I.
?did@* and returns t&e indeA o/ t&e /orwardin'
obBect ?e)')* connectin' link@)
/.$.2 OTcl Ipleentation
In t&e interreted &ierarc&y* t&e OTcl class #o!teLo$ic &as one key inst1ar
rtprotos5) T&e inst1ar rtprotos5 is an associati1e array w&ose indeA is t&e
name o/ t&e routin' rotocol and 1alue is t&e routin' a'ent obBect) 4'ain* we are
dealin' wit& static routin') T&ere/ore* t&e inst1ar rtprotos5 does not eAist)
8)3 Node Construction and Con/i'uration 133
Program 6=%/ Instrocs con"i$!re and look!p o/ class #o!teLo$ic
MMUMnsMtclMlibMnsJro!teItcl
2 #o!teLo$ic instproc con"i$!re 78 7
1 Psel" instvar rtprotos5
3 i" ?in"o e*ists rtprotos5@ 7
= "oreac( proto ?array names rtprotos5@ 7
> eval A$entMrtProtoMPproto initJall Prtprotos5
&Pproto'
A 8
B 8 else 7
/ A$entMrtProtoMStatic initJall
G 8
20 8
22 #o!teLo$ic instproc look!p 7 nodeid destid 8 7
21 i" 7 Pnodeid :: Pdestid 8 7
23 ret!rn Pnodeid
2= 8
2> set ns ?Sim!lator instance@
2A set node ?Pns $etJnodeJbyJid Pnodeid@
2B Psel" cmd look!p Pnodeid Pdestid
2/ 8
T&e OTcl class #o!teLo$ic also &as two maBor instrocs as s&own in
Pro'ram 8)1:@)
con"i$!re/' InitialiJe all t&e routin' rotocols ?!ines 1H1,@)
look!p/sid)did' (eturn t&e /orwardin' obBect /or ackets 'oin' /rom
Node sid to Node did ?!ines 11H1"@)
6=0 Noe $onstruction an $onfiguration
So /ar in t&is c&ater* we &a1e discussed maBor comonents o/ a Node H
classi/iers* routin' modules* and route lo'ic) 6e now resent &ow NS2 creates and
uts to'et&er t&ese main comonents)
In t&e /ollowin'* we /irst s&ow t&e key inst1ars o/ t&e OTcl class Node and
t&eir relations&is in Sect) 8)3)1) T&en* we s&ow an aroac& to ut classi/iers into
a Node obBect in Sect) 8)3)2) Sections 8)3)3 and 8)3): s&ow &ow a Node is
brid'ed to t&e transort ?i)e)* uer@ layer and to t&e routin' ?i)e)* lower@ layer*
resec9 ti1ely) Cinally* Sect) 8)3)3 discusses t&e key stes to create and con/i'ure
a Node obBect)
13: 8 Nodes as (outers or Comuter Hosts
/.+.1 =ey .aria-les of the OTcl Class Node
and Their Relationship
T&e list o/ maBor inst1ars o/ t&e OTcl class Node is 'i1en
below)
id5 Node I.
a$ents5 !ist o/ attac&ed transort layer a'ents
nn5 Total number o/ Nodes
nei$(bor5 !ist o/ nei'&borin' nodes
nodetype5 Node tye ?e)')* re'ular node or mobile node@
ns5 T&e Simulator
classi"ier5 4ddress classi/ier* w&ic& is t&e de/ault node entry
dm!*5 T&e demultileAer or ort classi/ier
mod!le5list5 !ist o/ enabled routin' modules
re$5mod!le5 !ist o/ re'istered routin' modules
rtnoti"5 T&e &ead o/ t&e c&ain o/ routin' modules w&ic& will be
noti/ied o/ route udates
ptnoti"5 !ist o/ routin' modules w&ic& will be noti/ied o/ ort
attac&ment$detac&ment
(ook5assoc5 SeDuence o/ t&e c&ain o/ classi/iers
mod5assoc5 4ssociation o/ classi/iers and routin' modules
6=0=%=% Routing.Re#ate 'nstvars
T&e /ollowin' /i1e inst1ars o/ an OTcl Node lays a maBor role in acket routin'<
mod!le5list5* re$5mod!le5* rtnoti"5* ptnoti"5* and mod5assoc5)
T&e inst1ar mod!le5list5 is a list o/ strin's* eac& o/ w&ic& reresents
t&e name o/ enabled routin' module) T&e inst1ar re$5mod!le5 is an associati1e
array w&ose indeA and 1alue are t&e name o/ t&e routin' module and t&e routin'
module instance)
T&e inst1ars rtnoti"5 and ptnoti"5 contain t&e obBects w&ic& s&ould
be noti/ied o/ a route c&an'e and an a'ent attac&ment$detac&ment* resecti1ely)
6&ile rtnoti"5 is t&e &ead o/ t&e link list o/ t&e routin' modules*
ptnoti"5 is simly an OTcl list w&ose elements are t&e routin' modules)
Cinally* inst1ar mod5assoc5 is an associati1e array w&ose indeAes and 1alues
are classi/iers and t&e associated routin' modules* resecti1ely)
Ci'ure 8)3 s&ows an eAamle o/ routin'9related 1ariable settin' bot& in CCC
and OTcl domain) Here* we assume t&at t&ere are two classi/iers) T&e /irst*
s,itc(5* classi/ies t&e 'eometry ?i)e)* circle$trian'le$sDuare@) T&e second classi9
/ies* classi"ier5* color ?i)e)* black$w&ite@)
T&e abo1e two classi/iers are controlled by routin' modules #t%od!leM%cast
and #t%od!leM.ase* resecti1ely) Since t&ere are two routin' modules* t&e
inst1ar re$5mod!les5 &as two
entries)
8)3 Node Construction and Con/i'uration 132
s
,
i
t
c
(
5
c
l
a
s
s
i
"
i
e
r
5
#t%od!leM%cast #t%od!leM.ase
classi"ier5 ne*t5rtm5 ne*t5rtm5 classi"ier5
Node
M0ast -ase
re$5mod!le5
:::
ptnoti"5 rtnoti"5
n5 ne*t5rtm5
!
classi"ier5
%cast#o!tin$%od!le
ne*t5rtm5 n5
classi"ier5
.ase#o!tin$%od!le
Point a to b -ind a to b Store a in b
a b a b a b
Arrow legend
4ig= 6=0 4n eAamle o/ node con/i'uration wit& two
classi/iers
Suose /urt&er t&at bot& t&e classi/iers need to be in/ormed o/ routin' c&an'e
and a'ent attac&ment$detac&ment) 6e need to ut bot& t&e associated routin'
modules in t&e list inst1ar ptnoti"5) On t&e ot&er &and* we only set one
routin' module ?i)e)* #t%od!leM.ase associated wit& classi"ier5 in t&is
case@ as t&e inst1ar rtnoti"5) T&e route con/i'uration command can be
roa'ated to #t%od!leM%cast 1ia t&e 1ariable ne*t5rtm5 o/ t&e &ead
?i)e)* +ase@ routin' module)
6=0=%=2 $#assifier.Re#ate 'nstvars
Class Node &as t&ree inst1ars related to classi/iers< classi"ier5* (ook5
assoc5* and mod5assoc5) Inst1ar classi"ier5 is t&e de/ault Node entry
as well as t&e &ead o/ t&e c&ain o/ classi/iers) Inst1ar (ook5assoc5 is an
associati1e
4ig= 6=6 4n eAamle o/ 1alues stored in 1ariables (ook assoc and mod assoc
array w&ose indeA is a classi/ier and 1alue is t&e downstream classi/ier in t&e
c&ain) T&e indeA and 1alue o/ t&e associati1e array mod5assoc5 are classi/iers
and t&e associated routin' modules* resecti1ely)
Consider Ci') 8)8 /or eAamle) Here* we install classi/iers 5o2* 5o1* 5o3* and
5o= into a Node* and associate t&em wit& routin' modules 5o>* 5oA* 5oB* and
5o/* resecti1ely) T&en* t&e inst1ar classi"ier5 would be 5o2) T&e
indeAes
and 1alues o/ (ook5assoc5 and mod5assoc5 would be as s&own in t&e
/i'ure)
/.+.2 Installing Classifiers in a %ode
Class Node ro1ides t&ree instrocs to con/i'ure classi/iers) Cirst* as s&own
in Pro'ram 8)13* t&e instroc insertJentry/mod!le cls"r (ook' takes
t&ree inut ar'uments< a routin' module Fmod!leG* a classi/ier Fcls"rG* and
an otional ar'ument F(ook)G It installs t&e current &ead classi/ier in t&e slot
number F(ookG o/ t&e inut classi/ier cls"r ?!ine "@* and relaces t&e &ead
classi/ier wit& t&e inut classi/ier cls"r ?!ine 12@) T&e inst1ars
(ook5assoc5 and mod5assoc5 are udated in !ines : and 11* resecti1ely)
T&e inut ar'ument F(ookG can &a1e one o/ t&e t&ree /ollowin' 1alues<
4 number< T&e inut Fcls"rG will be con/i'ured as eAlained abo1e)
4 strin' Ftar$etG< T&e eAistin' &ead classi/ier will be con/i'ured as a
tar$et
o/ t&e inut NsObBect cls"r)
3
Null< T&e inut Fcls"rG will not be con/i'ured) 6e mi'&t &a1e to con/i'ure it
later)
3
Note t&at t&e inut cls"r needs not be a classi/ier)
8)3 Node Construction and Con/i'uration 13#
Program 6=%0 Instrocs insertJentry and installJdem!* o/ class
Node
MMUnsMtclMlibMnsJnodeItcl
2 Node instproc insertJentry 7 mod!le cls"r 7(ook HH8 8 7
1 Psel" instvar classi"ier5 mod5assoc5 (ook5assoc5
3 i" 7 P(ook C: HH 8 7
= set (ook5assoc5&Pcls"r' Pclassi"ier5
> i" 7 P(ook :: Htar$etH 8 7
A Pcls"r tar$et Pclassi"ier5
B 8 elsei" 7 P(ook C: HH 8 7
/ Pcls"r install P(ook Pclassi"ier5
G 8
20 8
22 set mod5assoc5&Pcls"r' Pmod!le
21 set classi"ier5 Pcls"r
23 8
2= Node instproc installJdem!* 7dem!* 7port HH8 8 7
2> Psel" instvar dm!*5 address5
2A i" 7 Pdm!*5 C: HH 8 7
2B Psel" deleteJro!te Pdm!*5
2/ i" 7 Pport C: HH 8 7
2G Pdem!* install Pport Pdm!*5
10 8
12 8
11 set dm!*5 Pdem!*
13 Psel" addJro!te Paddress5 Pdm!*5
1= 8
T&e second classi/ier con/i'uration is t&e instroc installJentry/mod!le
cls"r (ook'* w&ic& is 1ery similar to instroc insertJentry/III') T&e
only di//erence is t&at it also destroys t&e eAistin' &ead classi/ier* i/ any) T&e details
o/ t&e instroc installJentry/III' can be /ound in t&e /ile Tns$tcl$lib$ns9
node)tcl)
T&e last classi/ier con/i'uration is t&e instroc installJdem!*/dem!*
port'* w&ose details are s&own in !ines 1:H2: o/ Pro'ram 8)13) T&is instroc
takes two inut ar'uments< dem!* ?mandatory@ and port ?otional@) It relaces
t&e eAistin' demultileAer
8
Fdm!*5G wit& t&e inut demultileAer dem!* ?!ine
22@) I/ FportG eAists* t&e current demultileAer Fdm!*5G will be installed in t&e
slot number FportG o/ t&e inut demultileAer Fdem!*G ?!ines 1"H2,@)
/.+." 2ridging a %ode to a Transport Layer Protocol
To attac& an a'ent to a Node* we use instroc attac(Ja$ent/node a$ent'
o/ class Sim!lator* w&ere FnodeG and Fa$entG are Node and A$ent
obBects*
8
4 demultileAer classi/ies ackets based on t&e ort number seci/ied in t&e acket &eader ?see
Sect) 8)2)2 /or more details@)
13" 8 Nodes as (outers or Comuter Hosts
Program 6=%6 4'ent attac&ment instrocs
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc attac(Ja$ent 7 node a$ent 8 7
1 Pnode attac( Pa$ent
3 8
MMUnsMtclMlibMnsJnodeItcl
= Node instproc attac( 7 a$ent 7 port HH 8 8 7
> Psel" instvar a$ents5 address5 dm!*5
A lappend a$ents5 Pa$ent
B Pa$ent set node5 Psel"
/ Pa$ent set a$ent5addr5 ?AddrParams addr1id Paddress5@
G i" 7 Pdm!*5 :: HH 8 7
20 set dm!*5 ?ne, Classi"ierMPort@
22 Psel" addJro!te Paddress5 Pdm!*5
21 8
23 i" 7 Pport :: HH 8 7
2= set port ?Pdm!*5 allocJport ??Sim!lator
instance@ n!lla$ent@@
2> 8
2A Pa$ent set a$ent5port5 Pport
2B Psel" addJtar$et Pa$ent Pport
2/ 8
2G Node instproc addJtar$et 7 a$ent port 8 7
10 Psel" instvar ptnoti"5
12 "oreac( m ?Psel" set ptnoti"5@ 7
11 Pm attac( Pa$ent Pport
13 8
1= 8
resecti1ely) Pro'ram 8)18 s&ows t&e instrocs related to an a'ent attac&ment
rocess) T&e rocess roceeds as /ollows<
1) Sim!lator99attac(Ja$ent/node a$ent'< In1oke FPnode attac(
Pa$entG ?!ine 2@)
2) Node99attac(/a$ent port'< 0date inst1ar Fa$entG ?!ines 8H" and
!ine 18@* create Fdm!*5G i/ necessary ?!ines #H13@* and in1oke FPsel" addJ
tar$et Pa$ent PportG ?!ine 12@)
3) Node99addJtar$et/a$ent port'< Crom Sect) 8)3)1* routin' modules re9
lated to ort attac&ment are stored in t&e list inst1ar ptnoti"5) T&ere/ore*
!ines
22 and 23 eAecute instroc attac(/a$ent port' o/ all t&e routin' modules
stored in t&e inst1ars ptnoti"5)
2
:) #t%od!le99attac(/a$ent port'< Consider !ines 2#H32 in Pro'ram
8)11) 4s a sendin' a'ent* t&e inut Fa$entG is set as an ustream obBect o/
t&e node entry ?!ine 3,@) 4s a recei1in' a'ent* it is installed in t&e slot number
FportG o/ demultileAer Fdm!*5G ?!ine 31@)
2
4'ain* Nodes do not directly con/i'ure ort classi/iers) It asks routin' modules stored in
ptnoti" to do so on its be&al/)
8)3 Node Construction and Con/i'uration 1:1
Program 6=%5 Instrocs addJro!te o/ class Node
MMUnsMtclMlibMnsJnodeItcl
2 Node instproc addJro!te 7 dst tar$et 8 7
1 Psel" instvar rtnoti"5
3 i" 7Prtnoti"5 C: HH8 7
= Prtnoti"5 addJro!te Pdst Ptar$et
> 8
A Psel" incrJrt$tableJsi6e
B 8
Note t&at alt&ou'& an a'ent can be either a sendin' a'ent or a recei1in' a'ent*
t&is instroc assi'ns bot& roles to e1ery a'ent) T&is does not cause any roblem
at runtime due to t&e /ollowin' reasons) 4 sendin' a'ent is attac&ed to a source
node* and always transmits ackets destined to a destination node) It takes no
action w&en recei1in' a acket /rom a demultileAer) 4 recei1in' a'ent* on t&e
ot&er &and* does not 'enerate a acket) T&ere/ore* it can ne1er send a acket to t&e
node entry)
/.+.$ Adding/)eleting a Ro!ting R!le
Class Node ro1ides an instroc addJro!te/dst tar$et' to add a routin'
rule ?dst)tar$et@ to t&e routin' table) In Pro'ram 8)12* instroc addJro!te
/dst tar$et' o/ class Node in1okes t&e instroc addJro!te/III' o/ t&e
routin' module rtnoti"5 w&ic& is o/ class #t%od!le
"
?!ine :@) Crom
!ines 22H2# o/ Pro'ram 8)11* t&e instroc addJro!te/III' o/ class
#t%od!le installs t&e routin' rule ?dst)tar$et@ in t&e classi"ier5 o/
all t&e related routin' module)
T&e mec&anism /or deletin' a routin' rule is similar to t&at /or addin' a routin'
rule* and is omitted /or bre1ity) T&e readers may /ind t&e details o/ route entry
deletion in t&e instroc deleteJro!te/dst n!lla$ent' o/ classes Node
and #t%od!le ?see /ile Tns$tcl$lib$ns9node)tcl and /ile Tns$tcl$lib$ns9rtmodule)tcl@)
/.+.+ %ode Constr!ction and Config!ration
T&ere are two key stes to ut to'et&er a Node ?e)')* as s&own in Ci's) 8)1 and
8)3@) 6e now discuss t&e details o/ node construction and con/i'uration in
seDuence)
"
4'ain* class Node makes no attemt to directly modi/y t&e classi/iers) It asks t&e routin'
modules in t&e c&ain* w&ose &ead is rtnoti" * to do so on its be&al/)
1:, 8 Nodes as (outers or Comuter Hosts
Program 6=%7 .e/ault 1alue o/ inst1ar node "actory and instroc node
o/ class Sim!lator
MMUnsMtclMlibMnsJde"a!ltItcl
2 Sim!lator set node5"actory5 Node
MMUnsMtclMlibMnsJlibItcl
1 Sim!lator instproc node ar$s 7
3 Psel" instvar Node5 ro!tin$A$ent5
= set node ?eval ne, ?Sim!lator set node5"actory5@ Par$s@
> set Node5&?Pnode id@' Pnode
A Psel" addJnode Pnode ?Pnode id@
B Pnode nodeid ?Pnode id@
/ Pnode set ns5 Psel"
G ret!rn Pnode
20 8
6=0=0=% Noe $onstruction
4 Node obBect is created usin' an OTcl statement FPns node*G w&ere Pns is
t&e Sim!lator instance) T&e Instroc FnodeG o/ class Sim!lator uses
instroc Fne,/III'G to create a Node obBect ?!ine : w&ere node5"actory5
is set to Node in !ine 1 o/ Pro'ram 8)1"@) It also udates inst1ars o/ t&e
Simulator so t&at t&ey can later be used by ot&er simulation obBects t&rou'&out t&e
simulation)
T&e construction o/ an OTcl Node obBect ?usin' ne,/III'@ consists o/ se1en
main stes ?see also Pro'ram 8)1#@)
Ste& %2 $onstructor of the ,Tc# $#ass Noe
Instroc init/III' sets u inst1ars o/ class Node* and in1okes instroc mkJ
de"a!ltJclassi"ier/' o/ t&e Node obBect ?!ine 22 in Pro'ram 8)1#@)
Ste& 22 'nst&roc mk#default#classifier/'
T&e instroc mkJde"a!ltJclassi"ier/' creates ?usin' ne,/III'@ and
re'is9 ters ?usin' re$isterJmod!le/mod'@ routin' modules w&ose names are
stored in t&e inst1ar mod!le5list5 ?!ines 22H2# in Pro'ram 8)1#@) +y
de/ault* only F.aseG routin' module is stored in t&e inst1ar
mod!le5list5 ?!ine 1 in Pro'ram 8)1#@)
To enable$disable ot&er routin' modules* t&e /ollowin' two instrocs o/ class
#t%od!le must be in1oked be/ore t&e eAecution o/ FPns
nodeG<
enableJmod!le7<nameK8
disableJmod!le7<nameK8
w&ere <nameK is t&e name o/ t&e routin' module* w&ic& is to be enabled$
disabled)
8)3 Node Construction and Con/i'uration 1:3
Program 6=%8 Instrocs related to t&e Node Construction Process
MMUMnsMtclMlibMnsJnodeItcl
2 Node set mod!le5list5 7 .ase 8
1 Node instproc init ar$s 7
3 eval Psel" ne*t Par$s
= Psel" instvar id5 a$ents5 dm!*5 nei$(bor5 rtsi6e5
> address5 T nodetype5 m!ltiPat(5 ns5 rtnoti"5 ptnoti"5
A set ns5 ?Sim!lator instance@
B set id5 ?Node $etid@
/ Psel" nodeid Pid5 ;O Propa$ate id5 into c44 space
G i" 7?llen$t( Par$s@ C: 08 7
20 set address5 ?linde* Par$s 0@
22 8 else 7
21 set address5 Pid5
23 8
2= Psel" cmd addr Paddress5; O Propa$ate address5 into
C44 space
2> set nei$(bor5 HH
2A set a$ents5 HH
2B set dm!*5 HH
2/ set rtsi6e5 0
2G set ptnoti"5 78
10 set rtnoti"5 78
12 set nodetype5 ?Pns5 $etJnodetype@
11 Psel" mkJde"a!ltJclassi"ier
13 set m!ltiPat(5 ?Pclass set m!ltiPat(5@
1= 8
1> Node instproc mkJde"a!ltJclassi"ier 78 7
1A Node instvar mod!le5list5
1B "oreac( modname ?Node set mod!le5list5@ 7
1/ Psel" re$isterJmod!le ?ne, #t%od!leMPmodname@
1G 8
30 8
32 Node instproc re$isterJmod!le 7 mod 8 7
31 Psel" instvar re$5mod!le5
33 Pmod re$ister Psel"
3= set re$5mod!le5&?Pmod mod!leJname@' Pmod
3> 8
Ste& *2 'nst&roc register#module/mod' of $#ass Node
T&is instroc in1okes t&e instroc re$ister/node' o/ t&e inut routin' module
FmodG and udates t&e inst1ar Fre$5mod!le5G ?see !ines 31H33@)
1:2 8 Nodes as (outers or Comuter Hosts
Ste& /2 'nst&roc register/node' of $#ass Rtodule"!ase
T&is instroc /irst in1okes instroc re$ister/node' o/ its arent class ?by t&e
statement Psel" ne*t Pnode in !ine 2 o/ Pro'ram 8)11@) T&en* !ines #H12
create ?usin' ne,/III'@ and con/i'ure ?usin' installJentry/III'@ t&e &ead
classi/ier ?i)e)* classi"ier5@ o/ t&e Node)
Ste& 02 'nst&roc register/node' of $#ass Rtodule
Crom Pro'ram 8)11* t&is instroc attac&es inut Node obBect FnodeGto t&e
routin' module ?!ine 2@) It also in1okes instroc ro!teJnoti"y/mod!le'
?!ine 3@ and portJnoti"y/mod!le' ?!ine :@ o/ t&e associated Node to
include t&e routin' module into t&e route noti/ication list rtnoti"5 and ort
noti/ication list ptnoti"5 o/ t&e associated Node)
Ste& 62 'nst&roc route#notif$/module' of $#ass Node
4s s&own in Pro'ram 8)2,* t&e instroc ro!teJnoti"y/mod!le' ?!ines 1H#@
stores t&e inut routin' module Fmod!leG as t&e last element o/ t&e link list o/
routin' modules) It also in1okes t&e OTcl command ro!teJnoti"y o/ t&e
inut routin' module ?!ine "@) T&e OTcl command ro!teJnoti"y in1okes t&e
CCC /unction ro!te5noti"y&rtm' associated wit& t&e attac&ed Node ?see
!ines 1,H
18@ to store t&e routin' module as t&e last routin' module in t&e link list ?see !ines
12H22@)
Ste& 52 'nst&roc %ort#notif$/module'of $#ass Node
4s s&own in !ines 23H28 o/ Pro'ram 8)2,* t&e instroc portJ
noti"y/mod!le'
aends t&e inut ar'ument Fmod!leG to t&e end o/ t&e list inst1ar
ptnoti"5)
6=0=0=2 Agent an Route $onfiguration
6e &a1e discussed &ow NS2 creates and uts main comonents wit&in a Node
obBect) T&e /inal ste is to instruct t&ese comonents w&at to do w&en recei1in' a
acket)
Crom Ci') 8)1* a Node obBect contains two key comonents< an address
classi/ier classi"ier5* and a ort classi/ier$demultileAer* dm!*5) Class
Sim!lator ro1ides two instrocs to con/i'ure t&ese two classi/iers)
#
#
Since t&e Sim!lator obBect is accessible to t&e Tcl simulation scrit* users 'enerally use
t&ese two instrocs to con/i'ure Nodes)
8)3 Node Construction and Con/i'uration 1:3
Program 6=2: Instrocs and /unctions w&ic& are related to instrocs ro!teJ
noti"y and portJnoti"y o/ t&e OTcl class Node
MMUMnsMtclMlibMnsJnodeItcl
2 Node instproc ro!teJnoti"y 7 mod!le 8 7
1 Psel" instvar rtnoti"5
3 i" 7Prtnoti"5 :: HH8 7
= set rtnoti"5 Pmod!le
> 8 else 7
A Prtnoti"5 ro!teJnoti"y Pmod!le
B 8
/ Pmod!le cmd ro!teJnoti"y Psel"
G 8
MMUnsMro!tin$Mrtmod!leIcc
20 int .ase#o!tin$%od!le99command&int ar$c) const c(ar
N
const
N
ar$v' 7
22 TclF tcl : Tcl99instance&';
21 i" &ar$c :: 3' 7
23 i" &strcmp&ar$v?2@ ) Hro!teJnoti"yH' :: 0' 7
2= n5JKro!te5noti"y&t(is';
2> 8
2A 8
MMUnsMcommonMnodeIcc
2B void Node99ro!te5noti"y&#o!tin$%od!le
N
rtm' 7
2/ i" &rtnoti"5 :: NDLL'
2G rtnoti"5 : rtm;
10 else
12 rtnoti"5JKro!te5noti"y&rtm';
11 8
MMUMnsMtclMlibMnsJnodeItcl
13 Node instproc portJnoti"y 7 mod!le 8 7
1= Psel" instvar ptnoti"5
1> lappend ptnoti"5 Pmod!le
1A 8
'nst&roc attac(Ja$ent/III'< Connect a Node to a transort layer a'ent
?see t&e details in Sect) 8)3)3@)
'nst&roc r!n/'< Create* comute* and install routin' tables in classi/iers o/ all
t&e Nodes) 4'ain* by de/ault* NS2 uses t&e .iBkstra5s al'orit&m to comute
routin' tables /or all airs o/ Nodes) T&e key stes in t&e instroc r!n/' are
s&own below<
Ste& %2 'nst&roc run/' of $#ass &imulator
S&own in !ine 2 o/ Pro'ram :)12* instroc r!n/' o/ class Sim!lator eAecutes
t&e instroc con"i$!re/' o/ t&e #o!teLo$ic obBect)
1:: 8 Nodes as (outers or Comuter Hosts
Program 6=2% Instrocs related to t&e route con/i'uration rocess
MMUnsMtclMrt$libMro!teJprotoItcl
2 A$entMrtProtoMStatic proc initJall ar$s 7
1 ?Sim!lator instance@ comp!teJro!tes
3 8
MMUnsMtclMlibMnsJro!teItcl
= Sim!lator instproc comp!teJro!tes 78 7
> Psel" comp!teJ"latJro!tes
A 8
B Sim!lator instproc comp!teJ"latJro!tes 78 7
/ Psel" instvar Node5 link5
G set r ?Psel" $etJro!telo$ic@
20 Psel" cmd $etJro!telo$ic Pr
22 "oreac( ln ?array names link5@ 7
21 set L ?split Pln 9@
23 set srcID ?linde* PL 0@
2= set dstID ?linde* PL 2@
2> i" 7 ?Plink5&Pln' !pY@ :: H!pH 8 7
2A Pr insert PsrcID PdstID ?Plink5&Pln' costY@
2B 8 else 7
2/ Pr reset PsrcID PdstID
2G 8
10 8
12 Pr comp!te
11 set n ?Node set nn5@
13 Psel" pop!lateJ"latJclassi"iers Pn
1= 8
Ste& 22 'nst&roc configure/' of $#ass Route'ogic
.e/ined in !ines 1H1, o/ Pro'ram 8)1:* t&e instroc con"i$!re/' o/ class
#o!te Lo$ic con/i'ures t&e routin' table /or all t&e Nodes by in1okin'
instroc initJall/' o/ class A$entMrtProtoMStatic)
Ste& *2 'nst&roc init#all/' of $#ass Agent"rtProto"&tatic
.e/ined in !ines 1H3 o/ Pro'ram 8)21* t&e instroc initJall/' o/ class A$ent
MrtProtoMStatic in1okes t&e instroc comp!teJro!tes/' o/ t&e
Simulator)
Ste& /2 'nst&roc com%ute#routes/' of $#ass &imulator
+y de/ault* t&is instroc in1okes t&e instroc comp!teJ"latJro!tes/' to
comute and setu t&e routin' table ?see !ines :H8 in Pro'ram 8)21@)
1:8 8 Nodes as (outers or Comuter Hosts
2G sprint"&tmp) HEdH) j';
10 nodelist5?i@JKadd5ro!te&tmp) l5(ead';
12 8
11 8
13 8
13 8
1> 8
Program 6=22 4n OTcl command pop!lateJ"latJclassi"iers* a /unc9
tion pop!late "lat classi"iers o/ class Sim!lator* and a
/unction add ro!te o/ cla s s Node
MMUnsMcommonMsim!latorIcc
2 int Sim!lator99command&int ar$c) const c(ar
N
const
N
ar$v' 7
1 III
3 i" &strcmp&ar$v?2@) Hpop!lateJ"latJclassi"iersH' :: 0' 7
= nn5 : atoi&ar$v?1@';
> pop!late5"lat5classi"iers&';
A ret!rn TCL5OV;
B 8
/ III
G 8
20 void Sim!lator99pop!late5"lat5classi"iers&' 7
22 III
21 "or &int i:0; i<nn5; i44' 7
23 "or &int j:0; j<nn5; j44' 7
2= i" &i C: j' 7
2> int n( : J2;
2A n( : rtobject5JKlook!p5"lat&i) j';
2B i" &n( K: 0' 7
2/ NsObject
N
l5(ead:$et5link5(ead&nodelist5?i@)
n(';
MMUnsMcommonMnodeIcc
1A void Node99add5ro!te&c(ar
N
dst) NsObject
N
tar$et' 7
1B i" &rtnoti"5'
1/ rtnoti"5JKadd5ro!te&dst) tar$et';
1G 8
Ste& 02 'nst&roc com%ute#flat#routes/' of $#ass &imulator
.e/ined in !ines 2H2: o/ Pro'ram 8)21* t&is instroc comutes and installs t&e
routin' table in all related address classi/iers)
(etrie1e and store t&e route lo'ic in a local 1ariable Pr ?!ines #H1,@
Collect and insert toolo'y in/ormation into t&e retrie1ed route lo'ic Pr ?!ines
11H2,@
Comute t&e otimal route ?!ine 21@
4dd routin' rules into all related classi/iers ?!ines 22 and 23@
8)8 C&ater Summary 1:2
Pro'ram 8)22 s&ows t&e details o/ &ow t&e comuted routin' rules are
roa'ated to all t&e nodes) !ines 1H# s&ow t&e details o/ OTcl command
pop!lateJ"latJ classi"iers/n') T&is OTcl command stores t&e
inut number o/ nodes FnG in t&e 1ariable nn5 ?!ine :@* and in1okes t&e
/unction pop!late5"lat5 classi"iers&' ?!ine 3@ to install t&e
comuted routin' rules in all t&e classi/iers)
Cunction pop!late5"lat5classi"iers&' adds t&e routin' rules /or all
airs ?i)j@ o/ nn5 nodes ?!ines 1,H23@) Cor eac& air* !ine 18 retrie1es t&e
neAt &o ?i)e)* /orwardin'@ re/erencin' oint Fn(G o/ a /orwardin' obBect /or a
acket tra1elin' /rom Node FiG to Node Fj)G !ine 1" retrie1es t&e link entry
oint Fl5(eadG corresondin' to t&e 1ariable Fn()G !ines 1# and 2, add a new
routin' rule /or t&e node i ?i)e)* nodelist5?i@@) T&e rule seci/ies t&e link
entry Fl5(eadG as a /orwardin' tar'et /or acket destined /or a destination node
j) T&e rule is added to t&e Node FiG 1ia its /unction
add5ro!te&dst)tar$et')
Cunction add5ro!te&dst)tar$et' simly in1okes /unction add5ro!te
&dst)tar$et' o/ t&e associated #o!tin$%od!le obBect rtnoti"5
?!ines
28H2#@) .e/ined in Pro'ram 8)1,* /unction add5ro!te&dst)tar$et' o/
class
#o!tin$%od!le recursi1ely installs t&e inut routin' rule &dst)tar$et'
down t&e link list o/ routin' modules)
6=6 $ha&ter Summary
4 Node is a basic comonent w&ic& acts as a router and a comuter &ost) Its
main resonsibilities are to /orward ackets accordin' to a routin' table and to
brid'e t&e &i'&9layer rotocols to a low9le1el network) 4 Node consists o/ t&ree
key comonents< classi/iers* routin' modules* and t&e route lo'ic) 4 classi/ier is a
multi9tar'et acket /orwarder) It /orwards ackets in t&e same cate'ory to t&e same
/orwardin' NsObBect) In a Node* an address classi/ier and a ort classi/ier act as a
router and a brid'e to t&e transort layer* resecti1ely)
(outin' modules are resonsible /or mana'in' classi/iers) +y con1ention* all
t&e con/i'uration commands must 'o t&ou'& routin' modules only) Cinally* t&e
route lo'ic collects network toolo'y* comutes t&e otimal routin' rules* and
install t&e resultin' rules in all t&e Nodes)
.urin' t&e Network Con/i'uration P&ase* a Node is created by eAecutin'
Pns node w&ere Pns is t&e Sim!lator obBect) Here* address classi/iers
and routin' modules are installed in t&e Node) T&e instruction o/ w&at to do w&en
recei1in' a acket is ro1ided later w&en t&e /ollowin' two OTcl statements
are eAecuted) Cirst* t&e transort layer connections are created usin' t&e instroc
attac(Ja$ent/III' o/ class Sim!lator) Second* t&e instroc r!n/' o/
class Sim!lator comutes t&e otimal routes /or all airs o/ nodes and
installs t&e comuted routin' tables in rele1ant classi/iers)
1:" 8 Nodes as (outers or Comuter Hosts
6=5 "<ercises
1) 6&at is a Classi/ierR 6&at are t&e similarities$di//erences between a Connector
and a Classi/ierR
2) EAlain and 'i1e eAamle /or t&e /ollowin' terminolo'ies<
a) (outin' mec&anism* b) (outin' rules* c) (outin' table*
d) (outin' al'orit&m* e) (outin' rotocol* /) (outin' a'ent*
') (oute lo'ic* &) (outers* i) (outin' module)
3) 6&at are routin' modulesR EAlain t&eir roles and necessities)
:) EAlain &ow classi/iers work)
a) 6&at are slotsR 6&at does Finstallin' an NsObBect in a slotG meanR
b) How does a acket enter a classi/ierR EAlain t&e acket /low mec&anism
since a acket enters a classi/ier until it lea1es t&e classi/ier) Li1e an
eAamle and draw a dia'ram to suort your answer)
3) 6&at is a &as& /unctionR EAlain your answer and s&ow /ew alications
w&ic& use &as& /unctions)
8) 6&at are t&e comonents in NS2 w&ic&
a) Cind t&e otimal route*
b) Proa'ate toolo'y and routin' in/ormation*
c) Corward acket based on t&e routin' in/ormation)
2) Consider a acket siJe classi/ier w&ic& classi/ies acket into small ?smaller t&an
:, bytes@* medium ?not smaller t&an :, bytes but smaller t&an 1*,,, bytes@*
and lar'e ?not smaller t&an 1*,,, bytes@ ackets)
a) Create a acket siJe classi/ier)
b) Con/i'ure t&e classi/ier suc& t&at small* medium* and lar'e ackets are sent
to t&e NsObBect w&ose addresses are stored in 1ariables Fsm*G Fmd*G and
Fl$*G resecti1ely)
c) EAlain t&e acket /low mec&anism and run an NS2 ro'ram to test your
answer)
Hint< Packet siJe can be obtained by CCC statements F(dr5cmn
N
c( :
(dr5cmn99access&p'; c(JKsi6e5GO see C&a) ")
") .raw a Node dia'ram) 6&at OTcl commands do you use to create a Node like
in t&e dia'ram) EAlain* ste9by9ste* &ow NS2 creates t&e Node)
#) 6&at is t&e de/ault routin' al'orit&m in NS2R How does NS2 setu t&e
routin' in a NodeR
1,) 6&at is a node entryR S&ow an OTcl statement to retrie1e a re/erence to t&e
node entry)
8)2 EAercises 1:#
11) How does NS2 in/orm a Node o/
a) New route*
b) New a'ent w&ic& s&all be attac&ed to a certain ortR
S&ow t&e ste9by9ste rocesses in NS2 1ia eAamles)
$ha&ter 5
+ink an Buffer Management
4 !ink is an OTcl obBect t&at connects two nodes and carries ackets /rom t&e
be'innin' node to t&e terminatin' node) T&is c&ater /ocuses on a class o/ most
widely used !ink obBects* namely* SimpleLink obBects) Con1eyin' ackets
/rom one node to anot&er* a SimpleLink obBect models acket transmission
time* link roa'ation delay* and acket bu//erin') Here* acket transmission
time re/ers to t&e time reDuired by a transmitter to send out a acket) It is
determined by t&e link bandwidt& and acket siJe) !ink roa'ation delay is t&e
time needed to con1ey a data bit /rom t&e be'innin' to t&e end o/ a link) In t&e
resence o/ bursty tra//ic* a transmitter may recei1e ackets w&ile transmittin' a
acket) T&e ackets enterin' a busy transmitter could be laced in a bu//er /or
/uture transmission) SimpleLink also models t&is acket bu//erin' mec&anism)
In t&e /ollowin's* we /irst 'i1e an introduction to classes Link and
SimpleLink in Sect) 2)1) T&en* we s&ow &ow NS2 models acket transmission
time and roa9 'ation delay in Sect) 2)2) NeAt* t&e acket bu//erin'* Dueue
blockin'* and callback mec&anisms are discussed in Sect) 2)3) Section 2): s&ows
a network construction and acket /low eAamle) Cinally* t&e c&ater summary is
ro1ided in Sect) 2)3)
5=% 'ntrouction to Sim&#e+ink ,b1ects
NS2 models a link usin' classes deri1ed /rom OTcl class Link obBect* amon'
w&ic& OTcl class SimpleLink is t&e simlest one w&ic& can be used to
connect two Nodes)
4.1.1 Main Coponents of a SipleLin'
Ci'ure 2)1 s&ows t&e comosition o/ class SimpleLink* w&ic& consists o/ t&e
/ollowin' basic obBects and tracin' obBects in t&e interreted &ierarc&y<
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 2* = Srin'er Science>+usiness %edia* !!C 2,12
131
132 2 !ink and +u//er %ana'ement
4ig= 5=% 4rc&itecture o/ a SimpleLink obBect
5=%=%=% Basic ,b1ects
(ead5 T&e entry oint o/ a SimpleLink obBect)
+!e!e5 4 !e!e obBect w&ic& models acket bu//erin' o/ a real router
?see Sect) 2)3@)
link5 4 DelayLink obBect w&ic& models acket transmission
time and link roa'ation delay ?see Sect) 2)2@)
ttl5 4 time to live c&ecker obBect w&ose class is TTLC(ecker)
It decrements t&e time to li1e /ield o/ an incomin' acket)
4/ter t&e decrement* i/ t&e time to li1e /ield is still ositi1e*
t&e acket will be /orwarded to t&e neAt element in t&e link)
Ot&erwise* it will be remo1ed t&e acket /rom t&e simulation
?see /ile Tns$common$ttl)&*cc@)
drop(ead5 T&e common acket droin' oint /or t&e link) T&e droed
ackets are /orwarded to t&is obBect) It is usually connected to
a null a'ent so t&at all SimpleLink obBects s&are t&e same
droin' oint)
5=%=%=2 Tracing ,b1ects
T&ese obBects will be inserted only i/ inst1ar PtraceAllQile5 o/ t&e
Sim!lator obBect is de/ined) 6e will describe t&e details o/ tracin' obBects
in detail in C&a) 13) T&ese obBects are
en+T5 Trace ackets enterin' +!e!e5)
de+T5 Trace ackets lea1in' +!e!e5)
drpT5 Trace ackets droed /rom +!e!e5)
rcvT5 Trace ackets lea1in' t&e SimpleLink or eDui1alently recei1ed
by t&e neAt node)
21
23 8
2= 8
2> 8
2)1 Introduction to Simle!ink ObBects 133
Program 5=% Instroc simple*Jlink o/ class Sim!lator
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc simple*Jlink 7 n2 n1 b, delay +type
ar$s 8 7
1 Psel" instvar link5 +!e!e%ap5 n!llA$ent5 !seasim5
3 s,itc( Je*act P+type 7
= III
> de"a!lt 7
A set + ?ne, !e!eMP+type Par$s@
B 8
/ 8
G s,itc( Je*act P+typeOri$ 7
20 III
22 de"a!lt 7
set link5&Psid9Pdid' ?ne, SimpleLink T
Pn2 Pn1 Pb, Pdelay P+@
4.1.2 Instprocs for Config!ring a &im%le'ink
O-8ect
In t&e OTcl domain* a SimpleLink obBect is created usin' t&e instrocs
simple*Jlink/II' and d!ple*Jlink/III' o/ class Sim!lator w&ose
syntaA is as /ollows<
Pns simple*Jlink Pn2 Pn1 <band,idt(K <delayK <+typeK
Pns d!ple*Jlink Pn2 Pn1 <band,idt(K <delayK <+typeK
w&ere Pns is t&e Sim!lator obBect* and Pn2 and Pn1 are Node
obBects)
Instroc simple*Jlink/III' abo1e creates a unidirectional SimpleLink
obBect connectin' Node Pn2 to Node Pn1 ?Pro'ram 2)1@) T&e seed and t&e
roa'ation delay o/ t&e link are 'i1en as <band,idt(K ?in bs@ and
<delayK
?in seconds@* resecti1ely) 4s oosed to a FrealG router* NS2 incororates a
Dueue
in a SimpleLink obBect* not in a Node obBect) T&e tye o/ t&e Dueue in t&e
link is seci/ied by <+typeK)
Pro'ram 2)1 s&ows details o/ instroc Sim!lator99simple*Jlink/III')
!ine 8 creates an obBect o/ class !e!eMP+type) !ine 12 constructs a
SimpleLink obBect* connectin' node Pn2 to Pn1) It seci/ies delay*
bandwidt&* and !e!e obBect o/ t&e link to be Pb,* Pdelay* and P+*
resecti1ely) T&e Simulator stores t&e created SimpleLink obBect in its
instance associati1e array Flink5G &Psid9Pdid'* w&ere Psid is t&e source
node I.* and Pdid is t&e destination node I.* resecti1ely* ?see C&a) :@)
2)2 %odelin' Packet .earture 133
Program 5=2 T&e constructor o/ t&e OTcl class SimpleLink
MMUnsMtclMlibMnsJlinkItcl
2 SimpleLink instproc init 7 src dst b, delay + 7
lltype HDelayLinkH8 8 7
1 set ns ?Sim!lator instance@
3 set drop(ead5 ?ne, Connector@
= Pdrop(ead5 tar$et ?Pns set n!llA$ent5@
> set (ead5 ?ne, Connector@
A i" 7 ??P+ in"o class@ in"o (erita$e Err%od!le@ ::
HError%od!leH 8 7
B P(ead5 tar$et ?P+ classi"ier@
/ 8 else 7
G P(ead5 tar$et P+
20 8
22 set +!e!e5 P+
21 set link5 ?ne, Plltype@
23 Plink5 set band,idt(5 Pb,
2= Plink5 set delay5 Pdelay
2> P+!e!e5 tar$et Plink5
2A Plink5 tar$et ?Pdst entry@
2B P+!e!e5 dropJtar$et Pdrop(ead5
2/ set ttl5 ?ne, TTLC(ecker@
2G Pttl5 tar$et ?Plink5 tar$et@
10 Psel" ttlJdropJtrace
12 Plink5 tar$et Pttl5
11 8
Instroc d!ple*Jlink/III' creates two SimpleLink obBects< one
connectin' Node Pn2 to Node Pn1 and anot&er connectin' Node Pn1 to Node
Pn2) T&e readers are encoura'ed to /ind details o/ t&e instroc d!ple*J
link/III' in /ile Tns$tcl$lib$ns9lib)tcl)
4.1." The Constr!ctor of Class &im%le'ink
Pro'ram 2)2 s&ows details o/ t&e instroc init/III' ?i)e)* t&e constructor@ o/
class SimpleLink* w&ic& constructs and connects obBects accordin' to Ci') 2)1)
!ines 3* 3* 11* 12* and 1" create inst1ars Fdrop(ead5*G F(ead5*G F+!e!e5*G
Flink5*G and Fttl5*G w&ose OTcl classes are Connector* Connector*
!e!e* DelayLink* and TTLC(ecker* resecti1ely) +andwidt& and delay o/
t&e inst1ar Flink5G are con/i'ured in !ines 13 and 1:)
4art /rom creatin' t&e abo1e obBects* t&e constructor also connects t&e created
obBects as in Ci') 2)1) .eri1ed /rom class Connector* eac& o/ t&e created obBects
uses commands tar$et/III' and dropJtar$et/III' to seci/y t&e neAt
downstream obBect and t&e droin' oint* resecti1ely ?see C&a) 3@) !ine # sets
t&e tar'et o/ F(ead5G to be F+)G !ine 13 sets t&e tar'et o/ F+!e!e5G ?w&ic& is
set
13: 2 !ink and +u//er %ana'ement
to F+G in !ine 11@ to be Flink5)G !ine 18 sets t&e tar'et o/ Flink5G to be t&e
entry o/ t&e neAt node) !ines 1# and 21 insert Fttl5G between Flink5G and t&e
entry o/ t&e neAt node) !ine 12 sets t&e droin' oint o/ F+!e!e5G to be
Fdrop(ead5)G Cinally* !ine : sets t&e tar'et o/ Fdrop(ead5G to be t&e null
a'ent o/ t&e Simulator)
5=2 Moe#ing Packet -e&arture
4.2.1 Pac'et )epart!re
Mechanis
NS2 models acket dearture usin' a CCC class Linkdelay ?see Pro'ram
2)3@* w&ic& is bound to an OTcl class DelayLink) 4'ain* t&e OTcl class
DelayLink is used to instantiate t&e inst1ar SimpleLink99link5 w&ic&
models t&e acket dearture rocess)
Program 5=* .eclaration o/ class LinkDelay
MMUnsMlinkMdelayI(
2 class LinkDelay 9 p!blic Connector 7
1 p!blic9
3 LinkDelay&'9 dynamic5&0') latest5time5&0') it+5&0'7
= bind5b,&Hband,idt(5H) Fband,idt(5';
> bind5time&Hdelay5H) Fdelay5';
A 8
B void recv&Packet
N
p) Handler
N
';
/ void send&Packet
N
p) Handler
N
';
G void (andle&Event
N
e';
20 inline do!ble t*time&Packet
N
p' 7Packet TLT Time
22 ret!rn &/I
N
(dr5cmn99access&p'JKsi6e&' M
band,idt(5';
21 8
23 protected9
2= int command&int ar$c) const c(ar
N
const
N
ar$v';
2> do!ble band,idt(5;
2A do!ble delay5;
2B Packet!e!e
N
it+5;
2/ Event intr5; M
N
In transit
N
M
2G 8;
MMUnsMlinkMdelayIcc
10 static class LinkDelayClass 9 p!blic TclClass 7
12 p!blic9
11 LinkDelayClass&' 9 TclClass&HDelayLinkH' 78
13 TclObject
N
create&int ar$c ) const c(ar
N
const
N
ar$v ' 7
1= ret!rn &ne, LinkDelay';
1> 8
1A 8 class5delay5link;
2)2 %odelin' Packet .earture 132
acket siJe
4 acket dearture rocess consists o/ acket transmission time and link
roa'ation delay) 6&ile t&e /ormer de/ines t&e time a acket stays in an
ustream node* t&e summation o/ t&e /ormer and t&e latter determines t&e time
needed to deli1er t&e entire acket to t&e connectin' downstream node)
Concetually* w&en a LinkDelay obBect recei1es a acket* it laces t&ese two
e1ents on t&e simulation timeline<
1) Packet departure /rom an ustream obBect< .e/ine packet transmission time .
bandwidt&
as time needed to transmit a acket o1er a link) 4/ter a eriod o/ acket
transmission time* t&e acket comletely lea1es ?or dearts@ t&e transmitter* and
t&e transmitter is allowed to transmit anot&er acket) 0on a acket recetion* a
LinkDelay obBect waits /or a eriod o/ acket transmission time* and
in/orms its ustream obBect t&at it is ready to recei1e anot&er acket)
2) Packet arrival at a downstream node< .e/ine propagation delay as t&e time
needed to deli1er a data bit /rom t&e be'innin' to t&e end o/ t&e link) 4'ain* an
entire acket needs a eriod o/ Facket transmission time C roa'ation delayG
to reac& t&e destination) 4 LinkDelay obBect* t&ere/ore* sc&edules a acket
recetion e1ent at t&e downstream node a/ter t&is eriod)
4.2.2 CCC Class 'inkDela$
Pro'ram 2)3 s&ows t&e declaration o/ CCC class LinkDelay* w&ic& is maed
to t&e OTcl class DelayLink) Class LinkDelay &as t&e /ollowin' /our main
1ariables) 7ariables Fband,idt(5G ?!ine 13@ and Fdelay5G ?!ine 18@ store t&e
link bandwidt& and roa'ation delay* resecti1ely) In !ines : and 3* t&ese two
1ariables are bound to OTcl inst1ars wit& t&e same name) In a link wit& lar'e
bandwidt&9delay roduct* a transmitter can send a new acket be/ore t&e re1ious
acket reac&es t&e destination) Class LinkDelay stores all ackets in)transit in
its bu//er Fit+5G ?!ine 12@* w&ic& is a ointer to a Packet!e!e obBect ?see
Sect) 2)3)1@) Cinally* 1ariable Fintr5G ?!ine 1"@ is a dummy Event obBect*
w&ic& reresents a acket dearture ?/rom t&e transmittin' node@ e1ent) 4s
discussed in Sect) :)3)2* t&e acket dearture is sc&eduled usin' 1ariable
Fintr5G w&ic& does not take art in e1ent disatc&in')
1
T&e main /unctions o/ class LinkDelay are recv&p)('* send&p)('*
(andle &e'* and t*ttime&p') Cunction t*ttime&p' calculates t&e acket
transmission time o/ acket
N
p ?!ines 1,H12 in Pro'ram 2)3@) Cunction
send&p)(' sends acket
N
p to t&e connectin' downstream obBect ?see !ine 12
in Pro'ram 3)3@) Cunction (andle&e' is in1oked w&en t&e Sc&eduler
disatc&es an e1ent corresondin' to t&e LinkDelay obBect ?see C&a) :@)
Cunction recv&p)('
1
4s a dummy Event obBect* 1ariable Fintr G ensures t&at an error messa'e will be s&own
on t&e screen* i/ an undisatc&ed e1ent is resc&eduled)
138 2 !ink and +u//er %ana'ement
Program 5=/ Cunction recv&p)(' o/ class LinkDelay
MMUnsMlinkMdelayIcc
2 void LinkDelay99recv&Packet
N
p) Handler
N
('
1 7
3 do!ble t*t : t*time&p';
= Sc(ed!lerF s : Sc(ed!ler99instance&';
> i" &dynamic5' 7 III 8
A else i" &avoid#eorderin$5' 7 III 8
B else 7
/ sIsc(ed!le&tar$et5) p) t*t 4 delay5';
G 8
20 sIsc(ed!le&() Fintr5) t*t';
22 8
?Pro'ram 2):@ takes a acket
N
p and a &andler
N
( as inut ar'uments* and
sc&edules acket dearture and acket arri1al e1ents)
1) Packet departure event< Since a acket sends Facket transmission timeG ?t*t
in !ine 3@ at t&e ustream obBect* /unction recv&p)(' sc&edules a acket
dearture e1ent at Ft*tG seconds a/ter t&e LinkDelay obBect recei1es t&e
acket) To do so* !ine 1, in1okes /unction sc(ed!le&()Fintr)t*t' o/
class Sc(ed!ler* w&ere t&e /irst* second* and t&ird inut ar'uments are a
&andler ointer* a dummy e1ent ointer* and delay* resecti1ely ?see C&a) :@)
4/ter Ft*tG seconds* t&e Sc&eduler disatc&es t&is e1ent by in1okin' /unction
(andle&e' associated wit& t&e &andler intr to in/orm t&e ustream obBect
o/ a acket dearture) In most cases* t&e ustream obBect resonds by
transmittin' anot&er acket* i/ a1ailable ?see Sect) 2)3)3 /or t&e callback
mec&anism@)
2) Packet arrival< Class LinkDelay also asses t&e acket to its downstream
obBect ?
N
tar$et5@) !ine " sc&edules an e1ent cast /rom t&e inut acket
N
p
wit& delay t*t4delay5 seconds* w&ere Ft*tG is t&e acket transmission
time and Fdelay5G is t&e link roa'ation delay) Here*
N
tar$et5 is
assed to t&e /unction sc(ed!le&III' as a &andler ointer) 4/ter
Ft*t4delay5G seconds* (I(andle&p' will in1oke /unction recv&p'
?see Pro'ram :)2@* and acket
N
p will be assed to
N
tar$et5 a/ter
t*t4delay5 seconds)
T&e maBor di//erence between sc&edulin' acket dearture and arri1al e1ents is
as /ollows) 6&ile a node can &old only one ?&ead o/ t&e line@ acket* a link can
contain more t&an one acket) Corresondin'ly* at an instance* a link can sc&edule
only one acket dearture e1ent ?usin' Fintr5G@* and more t&an one acket
arri1al e1ent ?usin'
N
p w&ic& reresents a acket@) E1ery time a LinkDelay
obBect recei1es a acket* it sc&edules t&e acket dearture e1ent usin' t&e same
1ariable Fintr5)G I/ 1ariable Fintr5G &as not been disatc&ed* suc& a
sc&edulin' will cause runtime error* because it attemts to lace a acket in t&e
&ead o/ t&e bu//er w&ic& is
currently occuied by anot&er acket) 4 acket arri1al e1ent* at t&e connectin'
node on t&e ot&er &and* is tied to incomin' acket) 4 LinkDelay obBect
sc&edules a
2)3 +u//er %ana'ement 13#
new acket arri1al e1ent /or e1ery recei1ed acket ?see !ine " in Pro'ram 2):@)
T&ere/ore* a link can sc&edule anot&er acket arri1al e1ent* e1en i/ t&e re1ious
arri1al e1ent &as not been disatc&ed) T&is is essentially t&e case /or a link ?wit&
lar'e bandwidt&9delay roduct@ w&ic& can contain se1eral ackets)
5=* Buffer Management
4not&er maBor comonent o/ a SimpleLink obBect is a !e!e obBect)
Imle9 mented wit&* class !e!e* it models t&e bu//erin' mec&anism in a
network router) It stores t&e recei1ed ackets in t&e bu//er and /orwards t&em to
its downstream obBect w&en t&e on'oin' transmission is comlete)
4s s&own in Pro'ram 2)3* class !e!e deri1es /rom class Connector
and can be used to connect two NsObBects) It uses a Packet!e!e obBect
?see Sect) 2)3)1@*
N
p+5 in !ine 2,* /or acket bu//erin') T&e bu//er siJe is
seci/ied in 1ariable F+lim5G ?!ine 18@) T&e 1ariables Fblocked5G ?!ine 12@*
F!nblock5on5res!me5G ?!ine 1"@* and F+(5G ?!ine 1#@ are related to t&e so9
called callback mec&anism and s&all be discussed later in Sect) 2)3)3)
Program 5=0 .eclaration o/ class !e!e
MMUnsM+!e!eM+!e!eI(
2 class !e!e 9 p!blic Connector 7
1 p!blic9
3 virt!al void en+!e&Packet
N
' : 0;
= virt!al Packet
N
de+!e&' : 0;
> virt!al void recv&Packet
N
) Handler
N
';
A void res!me&';
B int blocked&' const 7 ret!rn &blocked5 :: 2'; 8
/ void !nblock&' 7 blocked5 : 0; 8
G void block&' 7 blocked5 : 2; 8
20 int limit&' 7 ret!rn +lim5; 8
22 int len$t(&' 7 ret!rn p+5JKlen$t(&'; 8
21 virt!al U!e!e&';
23 protected9
2= !e!e&';
2> void reset&';
2A int +lim5;
2B int blocked5;
2/ int !nblock5on5res!me5;
2G !e!eHandler +(5;
10 Packet!e!e
N
p+5;
12 8;
13" 2 !ink and +u//er %ana'ement
Program 5=6 .eclaration o/ class Packet!e!e
MMUnsM+!e!eM+!e!eI(
2 class Packet!e!e 9 p!blic TclObject 7
1 p!blic9
3 Packet!e!e&' 9 (ead5&0') tail5&0') len5&0')
bytes5&0' 78
= virt!al int len$t(&' const 7 ret!rn &len5'; 8
> virt!al Packet
N
en+!e&Packet
N
p';
A virt!al Packet
N
de+!e&';
B virt!al void remove&Packet
N
';
/ Packet
N
(ead&' 7 ret!rn (ead5; 8
G Packet
N
tail&' 7 ret!rn tail5; 8
20 protected9
22 Packet
N
(ead5;
21 Packet
N
tail5;
23 int len5;
2= 8;
T&ere are a number o/ imortant /unctions o/ class !e!e) Cunction
en+!e&p' and de+!e&' ?!ines 3 and :@ lace and take* resecti1ely* a
acket /rom t&e Packet!e!e obBect
N
p+5) T&ey are declared as ure
1irtual and must be imlemented by instantiable deri1ed classes o/ class !e!e)
In&erited /rom class NsObject* t&e /unction recv&p)(' ?!ine 3@ is t&e
main acket recetion /unction) Cunction blocked&' in !ine 2 indicates
w&et&er t&e !e!e obBect is in a blocked state) Cunctions res!me&' ?!ine
8@* !nblock&' ?!ine "@* and block&' ?!ine #@ are used in t&e callback
mec&anism w&ic& will be discussed in Sect) 2)3)3) Cinally* /unctions limit&'
and len$t(&' return t&e bu//er siJe and current bu//er occuancy* resecti1ely)
4.".1 Class Packet(ueue9 A Model for Pac'et
2!ffering
.eclared in Pro'ram 2)8* class Packet!e!e models low9le1el oerations o/
t&e bu//er includin' storin'* enDueuin'* and deDueuin' acket) It contains se1eral
1ariables and /unctions w&ic& imlement a link list o/ Packets) 7ariable
F(ead5G in !ine 11 is t&e ointer to t&e be'innin' o/ t&e link list) 7ariable
Ftail5G in !ine
12 is t&e ointer to t&e end o/ t&e link list) T&e 1ariable Flen5G in !ine 13 is
t&e number o/ ackets in t&e bu//er) Cunction en+!e&p' in !ine 3 uts t&e inut
acket
N
p to t&e end o/ t&e bu//er) Cunction de+!e&' in !ine 8 returns t&e
&ead o/ t&e line Packet ointer or returns NDLL w&en t&e bu//er is nonemty
or emty* resecti1ely) Cunction remove&p' in !ine 2 searc&es /or a matc&in'
acket
N
p and remo1es it /rom t&e bu//er ?i/ /ound@) Note t&at acket
admittin'$droin' is t&e /unctionality o/ class !e!e* not o/ class
Packet!e!e) 6e will s&ow an eAamle o/ acket admittin'$droin' o/ class
DropTail in Sect) 2)3):)
2)3 +u//er %ana'ement 181
Program 5=5 .eclaration and /unction (andle o/ class !e!eHandler* and
t&e constructor o/ class !e!e
MMUnsM+!e!eM+!e!eI(
2 class !e!eHandler 9 p!blic Handler 7
1 p!blic9
3 inline !e!eHandler&!e!eF +' 9 +!e!e5&+' 78
= void (andle&Event
N
';
> private9
A !e!eF +!e!e5;
B 8;
MMUnsM+!e!eM+!e!eIcc
/ void !e!eHandler99(andle&Event
N
'
G 7
20 +!e!e5Ires!me&';
22 8
21 !e!e99!e!e&' 9 Connector&') blocked5&0')
!nblock5on5res!me5&2') +(5&
N
t(is')p+5&0'
23 7 III 8
4.".2 >!e!e 7andler
.eri1ed /rom class Handler ?see !ine 1 in Pro'ram 2)2@* class
!e!eHandler is closely related to t&e ?e1ent@ Sc&eduler) 4'ain* a
!e!eHandler obBect de/ines its de/ault actions in its /unction (andle&e')
T&ese de/ault actions will be taken w&en an associated e1ent is disatc&ed) 4s
s&own in !ines "H11 o/ Pro'ram 2)2* t&e de/ault action o/ a !e!eHandler
obBect is to eAecute /unction res!me&' o/ t&e associated !e!e obBect
F+!e!e5)G 6e will discuss t&e details o/ /unction res!me&' in Sect) 2)3)3) In
t&e rest o/ t&is section* we will demonstrate &ow a connection between
!e!eHandler and !e!e obBects is created)
To associate a !e!e obBect wit& a !e!eHandler obBect* classes !e!e
and !e!eHandler declare t&eir member 1ariables F+(5G ?!ine 1# in Pro'ram
2)3@ and F+!e!e5G ?!ine 8 in Pro'ram 2)2@* as a !e!eHandler ointer
and a !e!e re/erence* resecti1ely) T&ese two 1ariables are initialiJed w&en a
!e!e obBect is instantiated ?!ine 12 in Pro'ram 2)2@) T&e constructor o/ class
!e!e in1okes t&e constructor o/ class !e!eHandler* /eedin' itsel/ as
an inut ar'ument ?i)e)* +(5&
N
t(is'@) T&e constructor o/ F+(5G t&en sets its
member 1ariable F+!e!e5G to s&are t&e same address as t&e inut !e!e
obBect ?i)e)* +!e!e5&+' in !ine 3 o/ Pro'ram 2)2@) T&ese two constructors
create a two9way connection between t&e !e!e and !e!eHandler obBects)
4/ter t&is oint* t&e !e!e and t&e !e!eHandler obBects re/er to eac& ot&er
by t&e 1ariables +(5 and +!e!e5* resecti1ely)
18, 2 !ink and +u//er %ana'ement
4ig= 5=2 State dia'ram o/ t&e
Dueue blockin' mec&anism
4."." >!e!e 2loc'ing and Call-ac' Mechanis
5=*=*=% ?ueue B#ocking
NS2 uses t&e concet o/ ,ueue 'locking
2
to indicate w&et&er a Dueue is currently
transmittin' a acket) +y de/ault* a Dueue can transmit one acket at a time) It is
not allowed ?i)e)* blocked@ to transmit anot&er acket until t&e on'oin'
transmission is comlete) 4 Dueue is said to be blocked or unblocked ?i)e)*
blocked5 : 2 or blocked5 : 0@* w&en it is transmittin' a acket or is not
transmittin' a acket* resecti1ely)
Ci'ure 2)2 s&ows t&e state dia'ram o/ t&e Dueue blockin' mec&anism) 6&en
in t&e FNot +lockedG state* a Dueue is allowed to transmit a acket by eAecutin'
Ftar$et5JKrecv&p)F+(5'*G a/ter w&ic& it enters t&e F+lockedG state) Here*
a Dueue waits until t&e on'oin' transmission is comlete w&ere t&e /unction
res!me&' is in1oked) 4/ter t&is oint* t&e Dueue enters t&e FNot +lockedG state
and t&e rocess reeats)
5=*=*=2 $a##back Mechanism
4s discussed in C&a) 3* a node in NS2 asses ackets to a downstream node
by eAecutin' /unction recv&p)('* w&ere
N
p denotes a acket and
N
(
denotes a &andler) 4 callback mec&anism re/ers to a rocess w&ere a downstream
obBect in1okes an ustream obBect alon' t&e downstream at& /or a certain
urose) In a Dueue blockin' rocess* a callback mec&anism occurs w&en a
downstream obBect !e!e obBect by in1okin' /unction res!me&' o/ t&e
unblocks an ustream !e!e obBect)
6e now eAlain t&e callback mec&anism rocess /or Dueue unblockin' 1ia
an eAamle network in Ci') 2)3) Here* we assume t&at t&e /ollowin' obBects are
seDuentially connected< an ustream NsObBect* a !e!e obBect* a LinkDelay
obBect* and a downstream NsObBect) 4'ain* an NsObBect asses a acket
N
p by
in1okin' /unction recv&p)(' o/ its downstream obBect* w&ere
N
( is a
&andler) In most cases* t&e inut &andler
N
( is assed alon' wit& t&e acket
N
p
as inut ar'ument o/ /unction recv&p)(') Howe1er* t&is mec&anism is
di//erent /or !e!e obBects)
2
Iueue blockin' &as no relation to acket blockin' w&en t&e bu//er is /ull)
2)3 +u//er %ana'ement 183
4ig= 5=* .ia'ram o/ callback mec&anism /or a Dueue unblockin' rocess
Program 5=7 Cunction recv o/ class !e!e
MMUnsM+!e!eM+!e!eIcc
2 void !e!e99recv&Packet
N
p) Handler
N
'
1 7
3 en+!e&p';
= i" &Cblocked5' 7
> p : de+!e&';
A i" &p C: 0' 7
B blocked5 : 2;
/ tar$et5JKrecv&p) F+(5';
G 8
20 8
22 8
Consider /unction recv&p)(' o/ class !e!e in Pro'ram 2)") Instead o/
immediately assin' t&e incomin' acket
N
p to its downstream obBect* !ine 3
laces t&e acket in t&e bu//er) 4'ain* a !e!e obBect is allowed to transmit a
acket only w&en it is not blocked ?!ine :@) In t&is case* !ine 3 retrie1es a
acket /rom t&e bu//er) I/ t&e acket eAists ?!ine 8@* !ine 2 will set t&e state o/ t&e
!e!e obBect to be Fblocked*G and !ine " will /orward t&e acket to its
downstream obBect ?i)e)*
N
tar$et5@) T&e !e!e obBect asses its
!e!eHandler ointer F+(5G ?instead o/ t&e incomin' &andler ointer@ to its
downstream obBect) T&is !e!eHandler ointer acts as a re/erence oint /or a
Dueue blockin' callback mec&anism)
Crom Ci') 2)3* t&e downstream obBect o/ t&e !e!e obBect is a LinkDelay
obBect) 0on recei1in' a acket* it sc&edules two e1ents< acket dearture and
182 2 !ink and +u//er %ana'ement
Program 5=8 Cunction res!me o/ class
!e!e
MMUnsM+!e!eM+!e!eIcc
2 void !e!e99res!me&'
1 7
3 Packet
N
p : de+!e&';
= i" &p C: 0'
> tar$et5JKrecv&p) F+(5';
A else
B i" &!nblock5on5res!me5'
/ blocked5 : 0;
G else
20 blocked5 : 2;
22 8
arri1al e1ents ?see !ines 1, and " in Pro'ram 2):@) 4 acket arri1al e1ent is
associated wit& t&e downstream obBect ?i)e)*
N
tar$et5@) 4t t&e /irin' time* t&e
/unction (andle&p' o/ t&e downstream obBect will in1oke /unction recv&p'
to recei1e acket
N
p ?see Pro'ram :)2@)
Cunction recv&p' o/ class LinkDelay also sc&edules a acket
dearture e1ent) T&e dearture e1ent is associated wit& t&e !e!eHandler
obBect F+(5)G 4t t&e /irin' time* t&e Sc&eduler in1okes /unction (andle&p' o/
t&e associated !e!eHandler obBect +(5) In Pro'ram 2)2* t&is /unction in turn
in1okes /unction res!me&' to unblock t&e associated !e!e obBect)
Essentially* t&e LinkDelay obBect sc&edules an e1ent w&ic& calls 'ack to
unblock t&e ustream !e!e obBect)
Pro'ram 2)# s&ows t&e details o/ /unction res!me&' in1oked w&en t&e
on'oin' transmission is comlete) Cunction res!me&' /irst retrie1es t&e &ead
o/ t&e line acket /rom t&e bu//er ?!ine 3@) I/ t&e bu//er is nonemty ?!ine :@* !ine
3 will send t&e acket to t&e downstream obBect o/ t&e Dueue) I/ t&e Dueue is idle
?i)e)* t&e bu//er is emty@* 1ariable Fblocked5G will be set to Jero and one in
case t&at t&e /la' F!nblock5on5res!me5G is one and Jero* resecti1ely)
4.".$ Class Dro%Tail9 A Child Class of Class (ueue
Consider class DropTail* a c&ild class o/ class !e!e* w&ic& is bound to
t&e OTcl class !e!eMDropTail in Pro'ram 2)1,) T&e constructor o/ class
DropTail creates a ointer F+5G ?!ine 13@ to a Packet!e!e obBect and
sets Fp+5G deri1ed /rom class !e!e to be t&e same as F+5G ?!ine 3@)
T&rou'&out t&e imlementation* class DropTail re/ers to its bu//er by F+5G
instead o/ Fp+5)G Class DropTail o1errides /unction en+!e&p' ?!ine 11 and
Pro'ram 2)11@ and de+!e&' ?!ine 12@ o/ class !e!e) It also allows acket
droin' at t&e /ront o/ t&e bu//er* i/ t&e /la' Fdrop5"ront5G ?!ine 1:@ is set
to 1) Class DropTail does not o1erride /unction recv&p)(') T&ere/ore* it
recei1es a acket t&rou'& t&e /unction recv&p)(' o/ class !e!e)
18: 2 !ink and +u//er %ana'ement
Program 5=%: .eclaration o/ class DropTail
MMUnsM+!e!eMdropJtailI(
2 class DropTail 9 p!blic !e!e 7
1 p!blic9
3 DropTail&' 7
= +5 : ne, Packet!e!e;
> p+5 : +5;
A bind5bool&Hdrop5"ront5H) Fdrop5"ront5';
B 8;
/ UDropTail&' 7 delete +5; 8;
G protected9
20 int command&int ar$c) const c(ar
N
const
N
ar$v';
22 void en+!e&Packet
N
';
21 Packet
N
de+!e&';
23 Packet!e!e
N
+5;
2= int drop5"ront5;
2> 8;
MMUnsM+!e!eMdropJtailIcc
2A static class DropTailClass 9 p!blic TclClass 7
2B p!blic9
2/ DropTailClass&' 9 TclClass&H!e!eMDropTailH' 78
2G TclObject
N
create&int) const c(ar
N
const
N
' 7
10 ret!rn &ne, DropTail';
12 8
11 8 class5drop5tail;
Program 5=%% Cunction en+!e o/ class DropTail
MMUnsM+!e!eMdropJtailIcc
2 void DropTail99en+!e&Packet
N
p'
1 7
3 i" &&+5JKlen$t(&' 4 2' K: +lim5'
= i" &drop5"ront5' 7
> +5JKen+!e&p';
A Packet
N
pp : +5JKde+!e&';
B drop&pp';
/ 8 else
G drop&p';
20 else
22 +5JKen+!e&p';
21 8
In Pro'ram 2)11* t&e /unction en+!e&p' /irst c&ecks w&et&er t&e incomin'
acket will cause bu//er o1er/low ?!ine 3@) I/ so* it will dro t&e acket eit&er /rom
t&e /ront ?!ines 3H2@ or /rom t&e tail ?!ine #@* w&ere /unction drop&p' ?!ines 2
and #@ belon's to class Connector ?see Pro'ram 3):@) I/ t&e bu//er &as enou'&
sace* !ine 11 will enDueue acket ?p@ to its bu//er ?+5@)
2): 4 Samle Two9Node Network 183
5=/ A Sam&#e Two.Noe Network
6e &a1e introduced two basic NS2 comonents< nodes and links) +ased on t&ese
two comonents* we now create a two9node network wit& a unidirectional link and
s&ow t&e acket /low mec&anism wit&in t&is network in Ci') 2):)
ud6 n1
attach$a4ent
run
Sim6leLin1
sim6lex$lin1
n2
attach$a4ent
null
4ig= 5=/ 4 two9node network wit& a unidirectional link and t&e instrocs o/ class Sim!lator
4.$.1 %et&or' Constr!ction
T&e network in Ci') 2): consists o/ a be'innin' node ?n2@* a termination node
?n1@* a SimpleLink connectin' n2 and n1* a source transort layer a'ent
?!dp@* and a sink transort layer a'ent ?n!ll@) T&is network can be created usin'
t&e /ollowin' Tcl simulation scrit<
set ns ?ne, Sim!lator@
set n2 ?Pns node@
set n1 ?Pns node@
Pns simple*Jlink Pn2 Pn1 <b,K <delayK DropTail
set !dp ?ne, A$entMDDP@
set n!ll ?ne, A$entMN!ll@
Pns attac(Ja$ent Pn2 P!dp
Pns attac(Ja$ent Pn1 Pn!ll
Here* a command FPns nodeG creates a Node obBect) T&e internal
mec&anism o/ t&e node construction rocess was described in Sect) 8)3) T&e
statement FPns simple*Jlink Pn2 Pn1 <b,K <delayK DropTailG
creates a unidirec9 tional SimpleLink obBect* w&ic& connects node Pn2 to
node Pn1) T&e link bandwidt& and delay are <b,K bs and <delayK
seconds* resecti1ely) T&e bu//er in t&e link is o/ class DropTail) Crom Sect)
8)3)3* t&e commands FPns attac(Ja$ent Pn2 P!dpG and FPns
attac(Ja$ent Pn1 Pn!llG set t&e tar'et o/ t&e a'ent F!dpG to be t&e entry
o/ Node Pn2 and installs a'ent Pn!ll in t&e demultileAer o/ Node Pn1)
4.$.2 Pac'et 5lo&
Mechanis
To deli1er a acket F
N
pG /rom a'ent P!dp to
Pn!ll*
188 2 !ink and +u//er %ana'ement
1) 4'ent P!dp sends t&e acket
N
p to t&e entry o/ Node
Pn2)
3
2) Packet
N
p is sent to t&e &ead classi/ier Fclassi"ier5G ?w&ic& is o/ class
DestHas(Classi"ier@ o/ Node Pn2)
3) T&e DestHas(Classi"ier obBect Fclassi"ier5G eAamines t&e &eader
o/ t&e acket
N
p) In t&is case* t&e acket is destined to t&e Node Pn1)
T&ere/ore* it /orwards t&e acket to t&e link &ead o/ t&e connectin'
SimpleLink obBect)
:) T&e link &ead /orwards t&e acket to t&e connectin' !e!e
obBect)
3) T&e !e!e obBect enDueues t&e acket) I/ not blocked* it will /orward t&e
&ead
o/ t&e line acket to t&e connectin' LinkDelay obBect and set its status to
blocked)
8) 0on recei1in' a acket* t&e LinkDelay obBect sc&edules t&e two
/ollowin' e1ents<
a) Packet dearture e1ent* w&ic& indicates t&at acket transmission is com9
lete) T&is e1ent unblocks t&e associated !e!e obBect)
b) Packet arri1al e1ent* w&ic& indicates t&e acket arri1al at t&e connectin'
TTLC(ecker obBect)
2) T&e TTLC(ecker obBect recei1es t&e acket and decrements t&e TT! /ield o/
t&e acket &eader) I/ t&e TT! /ield o/ t&e acket is nonositi1e* t&e
TTLC(ecker obBect will dro t&e acket) Ot&erwise* it will /orward t&e
acket to t&e entry o/ Node Pn1 ?see /ile Tns$common$ttl)cc@)
") Node Pn1 /orwards t&e acket to t&e &ead classi/ier ?classi"ier5@) Since
t&e acket is destined to itsel/* t&e acket is /orwarded to t&e demultileAer
?dm!*5@)
#) T&e demultileAer /orwards t&e acket to t&e a'ent Pn!ll installed in t&e
demultileAer)
5=0 $ha&ter Summary
T&is c&ater /ocuses on class SimpleLink* a basic link class t&at can be used to
connect two nodes) T&e connection between two nodes Pn2 and Pn1 can be
created by t&e /ollowin' instrocs<
Pns simple*Jlink Pn2 Pn1 <b,K <delayK <+!e!e5typeK
Pns d!ple*Jlink Pn2 Pn1 <b,K <delayK <+!e!e5typeK
w&ere t&e bandwidt& and delay o/ t&e SimpleLink obBect are <b,K bs
and
<delayK seconds* resecti1ely) 4lso t&e tye o/ Dueue imlemented in t&e
SimpleLink obBect is
<+!e!e5typeK)
4 SimpleLink obBect models acket transmission time* link roa'ation
delay* and acket bu//erin') Here* acket transmission time is t&e time reDuired
188 2 !ink and +u//er %ana'ement
3
Note t&at* eac& obBect sends a acket
N
p to its downstream obBect by in1okin' tar$et JK
recv&p)('* w&ere tar$et is a ointer to t&e downstream obBect)
bandwidt&
2)8 EAercises 182
to transmit a acket and is comuted by
ac ket s iJ e
* w&ile t&e link roa'ation time
is t&e time reDuired to deli1er a data bit /rom t&e be'innin' to t&e end o/ t&e
SimpleLink obBect) T&ese two attributes are imlemented in t&e CCC class
!ink.elay) Packet bu//erin' is imlemented in t&e abstract class !e!e) Cinally*
classes LinkDelay and !e!e* to'et&er* &el model acket arri1al and
dearture e1ent)
5=6 "<ercises
1) 6&at are /eatures o/ a simle linkR .raw a dia'ram and eAlain eac& o/ its
obBect comonents) 6&at are t&e uroses* and t&e OTcl and CCC classes o/
t&ose comonentsR
2) .e/ine acket transmission time and roa'ation delay) 6&at are t&eir di//er9
encesR EAlain your answer usin' one eAamle)
3) 6&at are t&e OTcl and CCC classes resonsible to model acket transmission
time and roa'ation delayR .raw a dia'ram and eAlain &ow NS2 imlements
acket latency durin' acket /orwardin')
:) 6&at are t&e uroses o/ t&e 1ariable Fintr5G in class LinkDelayR
3) !ines " and 1, o/ Pro'ram 2): in1oke t&e /unction sc(ed!le&III' o/ t&e
Sc(ed!ler obBect) 6&at do t&ese lines doR
8) 6&at are t&e di//erences$similarities between CCC classes Packet!e!e
and
!e!eR
2) EAlain t&e relations&i amon' class !e!eHandler* !e!e* LinkDelay*
Packet* and Sc(ed!ler) .raw a dia'ram and eAlain t&e callback mec&a9
nism)
") EAlain &ow a DropTail Dueue recei1es and dros ackets /rom its tail
w&en its bu//er is /ull)
#) 6rite an NS2 statement w&ic& creates a SimpleLink obBect w&ose
bandwidt& is 2 %bs* roa'ation delay is 1, ms* and t&e Dueue tye is
.roTail)
$ha&ter 7
Packets3 Packet Heaers3 an Heaer 4ormat
Lenerally* a acket consists o/ acket &eader and data ayload) Packet &eader
stores acket attributes ?e)')* source and destination IP addresses@ necessary /or
acket deli1ery* w&ile data ayload contains user in/ormation) 4lt&ou'& t&is
concet is tyical in ractice* NS2 models ackets di//erently)
In most cases* NS2 eAtracts in/ormation /rom data ayload and stores t&e
in/ormation into acket &eader) T&is idea remo1es t&e need to rocess data
ayload at runtime) Cor eAamle* instead o/ countin' t&e number o/ bits in a
acket* NS2 stores acket siJe in t&e 1ariable (dr5cmn99si6e5 ?see Sect)
")3)3@* and accesses t&is 1ariable at runtime)
1
T&is c&ater discusses &ow NS2 models ackets) Section ")1 'i1es an o1er1iew
on NS2 acket modelin') Section ")2 discusses t&e acket allocation and deallo9
cation rocesses) Sections ")3 and "): s&ow t&e details o/ acket &eader and data
ayload* resecti1ely) 6e 'i1e a 'uideline o/ &ow to customiJe ackets ?i)e)* to
de/ine a new ayload tye and acti1ate$deacti1ate new and eAistin' rotocols@ in
Sect) ")3) Cinally* t&e c&ater summary is 'i1en in Sect) ")8)
7=% An ,verview of Packet Moe#ing Princi&#e
?.1.1 Pac'et
Architect!re
Ci'ure ")1 s&ows t&e arc&itecture o/ an NS2 acket model) Crom Ci') ")1* a acket
model consists o/ /our main arts< actual acket* class Packet* rotocol9seci/ic
&eaders* and acket &eader mana'er)
Actua# Packet2 4n actual acket re/ers to t&e ortion o/ memory w&ic&
stores acket &eader and data ayload) NS2 does not directly access eit&er t&e
1
Cor eAamle* class LinkDelay determines acket siJe /rom a 1ariable (dr cmn99
si6e w&en comutin' acket transmission time ?see !ine 11 o/ Pro'ram 2)3@)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 "* = Srin'er Science>+usiness %edia* !!C 2,12
18#
12, " Packets* Packet Headers* and Header Cormat
Packet
bitsC dataC
hdrlenC
Pac1et Header
Actual Packet AppData
Data Payload
ty6eC
PROTOCOL SPECIFIC HEADERS
classCcmnhdr
CommonHeaerClass
(ma66in4 class)
offsetC
si<eof()
(088 0lass)
offsetC
!r"ip
(088 0lass)
classCi6hdr
IPHeaerClass
(ma66in4 class)
:::
hdrlenC
classnameC
PacketHeaer#Common
(*'cl 0lass)
hdrlenC
PacketHeaer$ana%er
PacketHeaer#IP
(*'cl 0lass)
:::
C&&
OTcl
hdrlenC
a b
Arro' le%en
LaM 6oints to LbM -ind LaM to LbM Store LaM in LbM
a b a b
4ig= 7=% Packet modelin' in NS2
acket &eader or t&e data ayload) (at&er* it uses member 1ariables Fbits5G
and Fdata5G o/ class Packet to access acket &eader and data ayload*
resecti1ely) T&e details o/ acket &eader and data ayload will be 'i1en in
Sects) ")3 and "):* resecti1ely)
$#ass Packet2 .eclared in Pro'ram ")1* class Packet is t&e CCC main
class w&ic& reresents ackets) It contains t&e /ollowin' 1ariables and
/unctions<
H $CC >ariab#es of $#ass Packet
bits5 4 strin' w&ic& contains acket &eader
data5 4 ointer to an AppData obBect w&ic& contains data
ayload
""la$5 Set to tr!e i/ t&e acket is currently re/erred to by
ot&er obBects and "alse ot&erwise
"ree5 4 ointer to t&e &ead o/ t&e acket /ree list
re"5co!nt5 T&e number o/ obBects w&ic& currently re/er to t&e acket
ne*t5 4 ointer to t&e neAt acket in t&e link list o/ ackets
(dr5len5 !en't& o/ acket &eader
Program 7=% .eclaration o/ class Packet
MMUMnsMcommonMpacketI(
2 class Packet 9 p!blic Event 7
1 private9
3 !nsi$ned c(ar
N
bits5;
= AppData
N
data5;
> static void init&Packet
N
' 7b6ero&pJKbits5) (drlen5';8
A bool ""la$5;
B protected9
/ static Packet
N
"ree5;
G int re"5co!nt5;
20 p!blic9
22 Packet
N
ne*t5;
21 static int (drlen5;
MMPacket Allocation and Deallocation
23 Packet&' 9 bits5&0') data5&0') re"5co!nt5&0') ne*t5&0' 7 8
2= inline !nsi$ned c(ar
N
const bits&' 7 ret!rn &bits5'; 8
2> inline Packet
N
copy&' const;
2A inline Packet
N
re"copy&' 7 44re"5co!nt5; ret!rn t(is; 8
2B inline intF re"5co!nt&' 7 ret!rn &re"5co!nt5'; 8
2/ static inline Packet
N
alloc&';
2G static inline Packet
N
alloc&int';
10 inline void allocdata&int';
12 static inline void "ree&Packet
N
';
MMPacket Access
11 inline !nsi$ned c(ar
N
access&int o""'7ret!rn Fbits5?o""@';8;
13 8
H $CC 4unctions of $#ass Packet
init&p' Clear t&e acket &eader
N
bits5 o/ t&e inut
acket
N
p)
copy&' (eturn a ointer to a dulicated acket)
re"copy&' Increase t&e number o/ obBects* w&ic& re/er to t&e
acket* by one)
alloc&' Create a new acket and return t&e ointer to t&e
created acket)
alloc&n' Create a new acket wit& FnG bytes o/ data ayload
and return a ointer to t&e created acket)
allocdata&n' 4llocate FnG bytes o/ data ayload to t&e 1ariable
data5)
"ree&p' .eallocate t&e acket Fp)G
access&o""' (etrie1e a re/erence to a certain oint ?seci/ied by t&e
o//set Fo""G@ o/ t&e 1ariable Fbits5G ?i)e)* acket
&eader@)
122 " Packets* Packet Headers* and Header Cormat
Protoco# S&ecific Heaer2 Crom Ci') ")1* acket &eader consists o/ se1eral
rotocol9seci/ic &eaders) Eac& rotocol9seci/ic &eader uses a conti'uous
ortion o/ acket &eader to store its acket attributes) In common wit& most
TclObBects* t&ere are t&ree classes related to eac& rotocol9seci/ic &eader<
H 4 CCC class ?e)')* (dr5cmn or (dr5ip@ ro1ides a structure to store
acket attributes)
H 4n OTcl class ?e)')* PacketHeaderMCommon or PacketHeaderMIP@
acts as an inter/ace to t&e OTcl domain) NS2 uses t&is class to con/i'ure
acket &eader /rom t&e OTcl domain)
H 4 main' class ?e)')* CommonHeaderClass or IPHeaderClass@
binds a CCC class to an OTcl class)
6e will discuss t&e details o/ rotocol9seci/ic &eader later in Sect) ")3)3)
Packet Heaer Manager2 4 acket &eader mana'er maintains a list o/ acti1e
rotocols and con/i'ures all acti1e rotocol9seci/ic &eaders to setu acket
&eader) It &as an inst1ar F(drlen5G w&ic& indicates t&e len't& o/ acket
&eader consistin' o/ rotocol9seci/ic &eaders) T&e inst1ar F(drlen5G is
bound to a 1ariable F(drlen5G o/ class Packet) 4ny c&an'e in one o/ t&ese
two 1ariables will result in an automatic c&an'e in anot&er)
-ata Pay#oa2 Crom !ine : in Pro'ram ")1* t&e ointer Fdata5G oints to
data ayload* w&ic& is o/ class AppData) 6e will discuss t&e details o/ data
ayload in Sect) "):)
?.1.2 A Pac'et as an *#ent9 A )elayed Pac'et Reception
*#ent
.eri1ed /rom class Event ?!ine 1 in Pro'ram ")1@* class Packet can be
laced on t&e simulation time line ?see t&e details in C&a) :@) In Sect) :)2* we
mentioned two main classes deri1ed /rom class Event< class AtEvent and
class Packet) 6e also mentioned t&at an AtEvent obBect is an e1ent created
by a user /rom a Tcl simulation scrit) T&is section discusses details o/ anot&er
deri1ed class o/ class Event< class Packet)
4s discussed in Sect) 3)2)2* NS2 imlements delayed packet forwarding by
lacin' a acket recetion e1ent on t&e simulation timeline at a certain delayed
time) .eri1ed /rom class Event* class Packet can be laced on t&e simulation
timeline to si'ni/y a delayed acket recetion) Cor eAamle* t&e /ollowin'
statement ?see !ine " in Pro'ram 2):@ sc&edules a acket recetion e1ent* w&ere
t&e NsObBect
N
tar$et5 recei1es a acket
N
p at t*t4delay5 seconds in
/uture<
sIsc(ed!le&tar$et5) p) t*t 4 delay5'
Note t&at a Packet ointer is cast to be an Event ointer be/ore bein' /ed as
t&e second inut ar'ument o/ t&e /unction sc(ed!le&III')
")1 4n O1er1iew o/ Packet %odelin' Princile 123
4ig= 7=2 4 link list o/ ackets and a /ree acket list
4t t&e /irin' time* t&e Sc&eduler disatc&es t&e sc&eduled e1ent ?i)e)*
N
p@
and in1okes tar$etJK(andle&p'* w&ic& eAecutes Ftar$et5JKrecv&p'G to
/orward acket
N
p to t&e NsObBect ointer
N
tar$et5)
?.1." A Lin' List of Pac'ets
4art /rom t&e abo1e /our main acket comonents* a Packet obBect contains
a ointer Fne*t5G ?!ine 11 in Pro'ram ")1@* w&ic& &els /ormulatin' a link
list o/ Packet obBects ?e)')* Packet !ist in Ci') ")2@) Pro'ram ")2 s&ows t&e
imlementation o/ /unctions en+!e&p' and de+!e&' o/ class
Packet!e!e) Cunction en+!e&p' ?!ines 3H13@ uts a Packet obBect
N
p
to t&e end o/ t&e Dueue) I/ t&e Packet!e!e is emty* NS2 sets F(drlen5*G
Ftail5*G and FpG
to oint to t&e same lace
2
?!ine 3@) Ot&erwise* !ines 2 and " set
N
p as t&e last
acket in t&e Packet!e!e* and s&i/t 1ariable Ftail5G to t&e last acket
ointer Fp)G Since t&e ointer Ftail5G is t&e last ointer o/ Packet!e!e*
!ine 1, sets t&e ointer tail5JKne*t5 to , ?i)e* oints to NDLL@)
Cunction de+!e&' ?!ines 1:H21@ retrie1es a ointer to t&e acket at t&e &ead
o/ t&e bu//er) I/ t&ere is no acket in t&e bu//er* t&e /unction de+!e&' will
return a NDLL ointer ?!ine 13@) I/ t&e bu//er is not emty* !ine 12 will s&i/t t&e
ointer F(ead5G to t&e neAt acket* !ine 1# will decrease t&e len't& o/
Packet!e!e obBect by one* and !ine 2, will return t&e packet ointer FpG
w&ic& was set to t&e ointer F(ead5G in !ine 18)
2
Note t&at* (ead and tail are ointers to t&e /irst and t&e last Packet obBects*
resecti1ely* in a Packet!e!e obBect)
12: " Packets* Packet Headers* and Header Cormat
Program 7=2 Cunctions en+!e and de+!e o/ class Packet!e!e
MMUMnsMcommonM+!e!eI(
2 class Packet!e!e 9 p!blic TclObject 7
1 III
3 virt!al Packet
N
en+!e&Packet
N
p' 7
= Packet
N
pt : tail5;
> i" &Ctail5' (ead5: tail5: p;
A else 7
B tail5JKne*t5: p;
/ tail5: p;
G 8
20 tail5JKne*t5: 0;
22 44len5;
21 ret!rn pt;
23 8
2= virt!al Packet
N
de+!e&' 7
2> i" &C(ead5' ret!rn 0;
2A Packet
N
p : (ead5;
2B (ead5: pJKne*t5; MM 0 i" p :: tail5
2/ i" &p :: tail5' (ead5: tail5: 0;
2G JJlen5;
10 ret!rn p;
12 8
11 III
13 8;
?.1.$ 5ree Pac'et
List
0nlike most NS2 obBects* a Packet obBect* once created* will not be destroyed
until t&e simulation terminates) NS2 kees Packet obBects w&ic& are no lon'er
in use in a free packet list ?see Ci') ")2@) 6&en NS2 needs a new acket* it /irst
c&ecks w&et&er t&e /ree acket list is emty) I/ not* it will take a Packet obBect
/rom t&e list) Ot&erwise* it will create anot&er Packet obBect) 6e will discuss
t&e details o/ &ow to allocate and deallocate a Packet obBect later in Sect) ")2)
T&ere are two 1ariables w&ic& are closely related to t&e acket allocation$
deallocation rocess< F""la$5G and F"ree5)G Eac& Packet obBect uses a 1ari9
able F""la$5G ?!ine 8 in Pro'ram ")1@ to indicate w&et&er it is in use) T&e
1ariable F""la$5G is set to tr!e* w&en t&e Packet obBect is in use* and set to
"alse ot&erwise) S&ared by all t&e Packet obBects* a static ointer F"ree5G
?!ine " in Pro'ram ")1@ is a ointer to t&e /irst acket on t&e /ree acket list) Eac&
acket on t&e /ree acket list uses its 1ariable Fne*t5G to /orm a link list o/ /ree
Packet obBects) T&is link list o/ /ree ackets is re/erred to as a free packet list)
4lt&ou'& NS2 does not return memory allocated to a Packet obBect to t&e
system* it does return t&e memory used by acket &eader ?i)e)* Fbits5G@ and data
ayload ?i)e)* Fdata5G@ to t&e system ?see Sect) ")2)2@* w&en t&e acket is
deallocated) Since most
")2 Packet 4llocation and .eallocation 123
memory reDuired to store a Packet obBect is consumed by acket &eader and
data ayload* maintainin' a /ree acket list does not result in a si'ni/icant waste o/
memory)
7=2 Packet A##ocation an -ea##ocation
0nlike most o/ t&e NS2 obBects*
3
a Packet obBect is allocated and deallocated
usin' static /unctions alloc&' and "ree&p' o/ class Packet*
resecti1ely) I/ ossible* /unction alloc&' takes a Packet obBect /rom t&e
/ree acket list) Only w&en t&e /ree acket list is emty* does t&e /unction
alloc&' creates a new Packet obBect usin' Fne,G) Cunction "ree&p'
deallocates a Packet obBect* by returnin' t&e memory allocated /or acket
&eader and data ayload to t&e system and storin' t&e not9in9use Packet
ointer FpG in t&e /ree acket list /or /uture reuse) T&e details o/ acket
allocation and deallocation will be discussed below)
?.2.1 Pac'et Allocation
Pro'ram ")3 s&ows details o/ t&e /unction alloc&' o/ class Packet* t&e
acket allocation /unction) T&e /unction alloc&' returns a ointer to an
allocated Packet obBect to t&e caller) T&is /unction consists o/ two arts< acket
allocation in !ines 3H13 and acket initialiJation in !ines 18H22)
Consider t&e acket allocation in !ines 3H13) !ine 3 declares FpG as a ointer to
a Packet obBect and sets t&e ointer FpG to oint to t&e /irst acket on t&e /ree
acket list)
:
I/ t&e /ree acket list is emty ?i)e)* p : 0@* NS2 will create a new
Packet obBect ?in !ine 11@ and allocate memory sace wit& siJe F(drlen5G
bytes /or t&e acket &eader in !ine 12) T&e 1ariable F(drlen5G is not
con/i'ured durin' t&e construction o/ a Packet obBect) (at&er* it is set u in t&e
Network Con/i'uration P&ase ?see Sect) ")3)"@ and is used by t&e /unction
alloc&' to create acket &eader)
Cunction alloc&' does not allocate memory sace /or data ayload) 6&en
necessary* NS2 creates data ayload usin' t&e /unction allocdata&n' ?see
!ines
"H1: in Pro'ram "):@* w&ic& will be discussed in detail later in t&is
section)
I/ t&e /ree acket list is nonemty* t&e /unction alloc&' will eAecute !ines
3H# in Pro'ram ")3 ?see also t&e dia'ram in Ci') ")3@) In t&is case* t&e /unction
alloc&' /irst makes sure t&at nobody is usin' t&e Packet obBect F
N
p*G by
assertin' t&at
3
Lenerally* NS2 creates and destroys most obBects usin' rocedures ne,/III' and
delete/III'* resecti1ely)
12: " Packets* Packet Headers* and Header Cormat
:
4'ain* F"ree G is t&e ointer to t&e /irst acket on t&e /ree acket list)
")2 Packet 4llocation and .eallocation 122
Program 7=* Cunction alloc o/ class
Packet
MMUMnsMcommonMpacketI(
2 inline Packet
N
Packet99alloc&'
1 7
MMPacket Allocation
3 Packet
N
p : "ree5;
= i" &p C: 0' 7
> assert&pJK""la$5 :: QALSE';
A "ree5 : pJKne*t5;
B assert&pJKdata5 :: 0';
/ pJK!id5 : 0;
G pJKtime5 : 0;
20 8 else 7
22 p : ne, Packet;
21 pJKbits5 : ne, !nsi$ned c(ar?(drlen5@;
23 i" &p :: 0 XX pJKbits5 :: 0'
2= abort&';
2> 8
MMPacket Initiali6ation
2A init&p'; MM Initiali6e bits5?@
2B &HD#5C%N&p''JKne*t5(op5 : J1; MM J2 reserved "or
IP5.#OADCAST
2/ &HD#5C%N&p''JKlast5(op5 : J1; MM J2 reserved "or
IP5.#OADCAST
2G pJK""la$5 : T#DE;
10 &HD#5C%N&p''JKdirection&' : (dr5cmn99DOWN;
12 pJKne*t5 : 0;
11 ret!rn &p';
13 8
freeC
Pac1et
nextC
Pac1et
nextC
G
6
)?LL
4ig= 7=* .ia'ram o/ acket allocation w&en t&e /ree acket list is nonemty) T&e dotted lines
s&ow t&e actions caused by t&e /unction alloc o/ class Packet
Program 7=/ Cunctions alloc* allocdata* and copy o/ class Packet
MMUMnsMcommonMpacketI(
2 inline Packet
N
Packet99alloc&int n'
1 7
3 Packet
N
p : alloc&';
= i" &n K 0'
> pJKallocdata&n';
A ret!rn &p';
B 8
/ inline void Packet99allocdata&int n'
G 7
20 assert&data5 :: 0';
22 data5 : ne, PacketData&n';
21 i" &data5 :: 0'
23 abort&';
2= 8
2> inline Packet
N
Packet99copy&' const
2A 7
2B Packet
N
p : alloc&';
2/ memcpy&pJKbits&') bits5) (drlen5';
2G i" &data5'
10 pJKdata5 : data5JKcopy&';
12 ret!rn &p';
11 8
F""la$5G is "alse ?!ine 3@)
3
T&en* !ine 8 s&i/ts t&e ointer F"ree5G by one
osition) !ines "H# initialiJe two 1ariables ?F!id5G and Ftime5G@ o/ class
Event ?i)e)* t&e mot&er class o/ class Packet@ to be Jero) !ine 21 remo1es t&e
acket /rom t&e /ree list by settin' pJKne*t5 to Jero)
4/ter t&e acket allocation rocess is comlete* !ines 18H22 initialiJe t&e
allocated Packet obBect) !ine 18 in1okes /unction init&p'* w&ic& initialiJes
t&e &eader o/ acket
N
p) Crom !ine 3 in Pro'ram ")1* in1ocation o/ /unction
init&p' eAecutes Fb6ero&pJK bits5)(drlen5'*G w&ic& clears
Fbits5G
to Jero)
8
!ine 1# sets ""la$5 to be tr!e* indicatin' t&at t&e acket
N
p is
now in use) !ine 21 sets t&e ointer pJKne*t5 to be Jero) !ines 12* 1"*
and 2, initialiJe t&e common &eader) 6e will discuss acket &eader in 'reater
detail in
Sect) ")3)2)
3
T&e CCC /unction assert&cond' can be used /or an inte'rity c&eck) It does not&in' i/ t&e
inut ar'ument FcondG is tr!e) Ot&erwise* it will initiate an error &andlin' rocess ?e)')*
s&owin' an error on t&e screen@)
8
Cunction b6ero&III' takes two ar'uments H t&e /irst is a ointer to t&e bu//er and t&e
second is t&e siJe o/ t&e bu//er H and sets all 1alues in a bu//er to Jero)
")2 Packet 4llocation and .eallocation 12#
4art /rom t&e /unction alloc&'* ot&er rele1ant /unctions include
alloc&n'* allocdata&n'* and copy&' ?see Pro'ram "):@) T&e /unction
allocdata&n' data allocates a acket ?!ine 3@* and in1okes
allocdata&n' ?!ine 3@) T&e /unction allocdata&n' creates data ayload
wit& siJe FnG bytes ?by in1okin' ne, Packet Data&n' in !ine 11@) 6e will
discuss t&e details o/ data ayload later in Sect) "):)
Cunction copy&' returns a relica o/ t&e current Packet obBect) T&e
only di//erence between t&e current and t&e relicated Packet obBects is t&e
uniDue I. ?!id5@ /ield) T&is /unction is Duite use/ul* since we o/ten need to
create a acket w&ic& is t&e same as or sli'&tly di//erent /rom an ori'inal acket)
T&is /unction /irst allocates a acket in !ine 12) T&en* it coies acket &eader and
data ayload to t&e created acket
N
p in !ines 1" and 2,* resecti1ely)
.esite its name* /unction re"copy&' ?!ine 18 in Pro'ram ")1@ does not
create
a coy o/ a Packet obBect) (at&er* it returns t&e ointer to t&e current Packet
obBect and increment t&e 1ariable re"5co!nt5 b' 1) T&e 1ariable
re"5co!nt5
kees track o/ t&e number o/ obBects w&ic& s&are t&e same Packet obBect) It is
initialiJed to , in t&e constructor o/ class Packet ?!ine 13 in Pro'ram ")1@* and
is incremented by one w&en t&e /unction re"5copy&' ?!ine 18 in Pro'ram ")1@
is in1oked* indicatin' t&at a new obBect starts usin' t&e current Packet
obBect)
Similarly* it is decremented by one w&en t&e /unction "ree&p' ?see Sect)
")2)2@
is in1oked* indicatin' t&at an obBect &as stoed usin' t&e current Packet
obBect)
?.2.2 Pac'et )eallocation
6&en a acket
N
p is no lon'er in use* NS2 deallocates t&e acket usin' a
/unction "ree&p') +y deallocation* NS2 returns t&e memory used to store
acket &eader and data ayload to t&e system* sets t&e ointer Fdata5G to Jero*
and stores t&e Packet obBect in t&e /ree acket list) Note t&at alt&ou'& t&e 1alue
o/ Fbits5G is not set to Jero* t&e memory location stored in Fbits5G is no
lon'er accessible) It is 1ery imortant not to use Fbits5G a/ter acket
deallocation) Ot&erwise* NS2 will encounter a ?memory s&are 1iolation@ runtime
error)
.etails o/ t&e /unction "ree&Packet
N
' are s&own in Pro'ram ")3) +e/ore
returnin' a Packet obBect to t&e /ree acket list* we need to make sure t&at
1) T&e acket is in use ?i)e)* pJK""la$5 : 2 in !ine 3@* since t&ere is no oint
in deallocatin' a acket w&ic& &as already been deallocated)
2) No obBect is usin' t&e acket) In ot&er words* t&e 1ariable re"5co!nt5 is
Jero ?!ine :@* w&ere re"5co!nt5 stores t&e number o/ obBects w&ic& are
currently usin' t&is acket)
3) T&e acket is no lon'er on t&e simulation time line ?i)e)* pJK!id5<:0 in
!ine 3@) .eallocatin' a acket w&ile it is still on t&e simulation timeline will
12" " Packets* Packet Headers* and Header Cormat
Program 7=0 Cunction "ree o/ class
Packet
MMUMnsMcommonMpacketI(
2 inline void Packet99"ree&Packet
N
p'
1 7
3 i" &pJK""la$5' 7
= i" &pJKre"5co!nt5 :: 0' 7
> assert&pJK!id5 <: 0';
A i" &pJKdata5 C: 0' 7
B delete pJKdata5;
/ pJKdata5 : 0;
G 8
20 init&p';
22 pJKne*t5 : "ree5;
21 "ree5 : p;
23 pJK""la$5 : QALSE;
2= 8 else 7
2> JJpJKre"5co!nt5;
2A 8
2B 8
2/ 8
cause e1ent mis9seDuencin' and runtime error) !ine 3 asserts t&at t&e e1ent
uniDue I. corresondin' to t&e Packet obBect FpG ?i)e)* pJK!id5@ is non9
ositi1e* and t&ere/ore is no lon'er on t&e simulation timeline)
2
NS2 allows more t&an one simulation obBect to s&are t&e same Packet obBect)
To deallocate a acket* NS2 must ensure t&at t&e acket is no lon'er used by any
simulation obBect) 4'ain* NS2 kees t&e number o/ obBects s&arin' a acket in t&e
1ariable re"5co!nt5) I/ re"5co!nt5K0* meanin' an obBect is in1okin' t&e
/unction "ree&p' w&ile ot&er obBects are still usin' t&e acket
N
p* t&e /unction
"ree&p' will simly reduce re"5co!nt5 by one* indicatin' t&at one obBect
stos usin' t&e acket ?!ine 13@)
"
On t&e ot&er &and* i/ re"5co!nt5 is Jero*
meanin' t&at no ot&er obBect is usin' t&e acket* !ines 3H13 will t&en clear acket
&eader and data ayload and store t&e Packet obBect in t&e /ree acket list)
I/ all t&e abo1e t&ree conditions are satis/ied* /unction "ree&p' will eAecute
!ines 8H13 in Pro'ram ")3) T&e sc&ematic dia'ram /or t&is art is s&own in Ci')
"):) !ine 2 returns t&e memory used by data ayload to t&e system) !ine " sets t&e
ointer Fdata5G to Jero) !ine 1, returns t&e memory used by &eader o/ t&e
acket
N
p to t&e system by in1okin' t&e /unction init&p' ?see !ine 3 o/
Pro'ram ")1@) !ines
11 and 12 lace t&e acket as t&e /irst acket on t&e /ree acket list) Cinally* !ine
13 sets F""la$5G to "alse* indicatin' t&at t&e acket is no lon'er in use)
2
Crom Ci') :)2* an e1ent wit& ositi1e uniDue I. ?e)'* F!id G is 2 or 8@ was sc&eduled but &as
not been disatc&ed)
"
I/ t&e Packet obBect is deallocated w&en re" co!nt K 0* simulation obBects may later try
to access t&e deallocated Packet obBect and cause a runtime error)
")3 Packet Header 1"1
4ig= 7=/ T&e rocess o/ returnin' a acket to t&e acket /ree list) T&e dotted lines s&ow t&e
action caused by t&e /unction "ree o/ class Packet
7=* Packet Heaer
4s a art o/ a acket* acket &eader contains acket attributes suc& as acket
uniDue I. and IP address) 4'ain* acket &eader is stored in t&e 1ariable Fbits5G
o/ class Packet ?see !ine 3 o/ Pro'ram ")1@) T&e 1ariable Fbits5G is declared
as a strin' ?i)e)* a Bag of Bits ?+O+@@ and &as no structure to store acket
attributes) Howe1er* NS2 imoses a two9le1el structure on 1ariable Fbits5*G as
s&own in Ci') ")3)
T&e /irst le1el di1ides t&e entire acket &eader into rotocol9seci/ic &eaders)
T&e
location allocated to eac& rotocol seci/ic &eader on Fbits5G is identi/ied by its
1ariable o""set5) T&e second le1el imoses a acket attribute9storin' structure
on eac& rotocol9seci/ic &eader) On t&is le1el* acket attributes are stored as
members o/ a CCC str!ct data tye)
In ractice* a acket contains only rele1ant rotocol9seci/ic &eaders) 4n NS2
acket* on t&e ot&er &and* includes all rotocol9seci/ic &eaders into a acket
&eader* re'ardless o/ acket tye) E1ery acket uses t&e same amount o/ memory
to store t&e acket &eader) T&e amount o/ memory is stored in t&e 1ariable
F(drlen5G o/ class Packet in !ine 12 o/ Pro'ram ")1* and is declared as a
static 1ariable) T&e 1ariable F(drlen5G &as no relations&i to simulation acket
siJe) Cor eAamle* TCP and 0P. ackets may &a1e di//erent siJes) T&e 1alues
stored in t&e corresondin' 1ariable (dr5cmn99si6e5 may be di//erentO
&owe1er* t&e 1alues stored in t&e 1ariable Packet99(drlen5 /or bot& TCP
and 0.P ackets are t&e same)
In t&e /ollowin'* we /irst discuss t&e /irst le1el acket &eader comosition in
Sect) ")3)1) Sections ")3)2 and ")3)3 s&ow eAamles o/ rotocol9seci/ic &ead9
ers< common acket &eader and IP acket &eader) Section ")3): discusses one
o/ t&e main acket attributes< ayload tye) Section ")3)3 eAlains t&e details
o/ rotocol9seci/ic &eader ?i)e)* t&e second le1el acket &eader comosition@)
Section ")3)8 demonstrates &ow acket attributes stored in acket &eader are
1", " Packets* Packet Headers* and Header Cormat
4ig= 7=0 4rc&itecture o/ acket &eader< .urin' t&e construction o/ t&e Simulator* t&e acket
&eader siJe is determined and stored in t&e inst1ar PacketHeader%ana$er99(drlen
w&ic& is bound to t&e 1ariable PacketHeader%ana$er99(drlen ) See t&e details in
Ste 2 in Sect) ")3)"
accessed) Section ")3)2 discusses one o/ t&e main acket &eader comonent* a
acket &eader mana'er* w&ic& maintains t&e acti1e rotocol list and sets u t&e
o//set 1alue /or eac& rotocol) Cinally* Sect) ")3)" resents t&e acket &eader
construction rocess)
?.".1 An O#er#ie& of 5irst Le#el Pac'et Coposition9
Offseting
Protocol(Specific 7eader on the Pac'et 7eader
On t&e /irst le1el* NS2 uts to'et&er all rele1ant rotocol9seci/ic &eaders ?e)')*
com9 mon &eader* IP &eader* TCP &eader@ and comoses a acket &eader ?see
Ci') ")3@) Concetually* NS2 allocates a conti'uous art on t&e acket &eader /or a
rotocol9 seci/ic &eader) Eac& rotocol9seci/ic &eader is o//set /rom t&e
be'innin' o/ acket &eader) T&e distance between t&e be'innin' o/ acket &eader
and t&at o/ a rotocol9 seci/ic &eader is stored in t&e member 1ariable o""set5
o/ t&e rotocol9seci/ic &eader) Cor eAamle* (dr5cmn* (dr5ip* and
(dr5tcp H w&ic& reresent common &eader* IP &eader* and TCP &eader H
store t&eir o//set 1alues in 1ari9 ables (dr5cmn99o""set5*
(dr5ip99o""set5* and (dr5tcp99o""set5* resecti1ely)
")3 Packet Header 1"3
Program 7=6 .eclaration o/ C>> (dr cmn str!ct data
tye
MMUMnsMcommonMpacketI(
2 str!ct (dr5cmn 7
1 en!m dir5t 7 DOWN: J2) NONE: 0) DP: 2 8;
3 packet5t ptype5; MM payload type
= int si6e5; MM sim!lated packet si6e
> int !id5; MM !ni+!e id
A dir5t direction5; MM direction9 0:none) 2:!p) J2:do,n
B static int o""set5; MM o""set "or t(is (eader
/ inline static (dr5cmn
N
access&const Packet
N
p' 7
G ret!rn &(dr5cmn
N
' pJKaccess&o""set5';
20 8
22 inline static intF o""set&' 7 ret!rn o""set5; 8
21 inline packet5tF ptype&' 7 ret!rn &ptype5'; 8
23 inline intF si6e&' 7 ret!rn &si6e5'; 8
2= inline intF !id&' 7 ret!rn &!id5'; 8
2> inline dir5tF direction&' 7 ret!rn &direction5'; 8
2A 8;
?.".2 Coon Pac'et 7eader
Common acket &eader contains acket attributes w&ic& are common to all
ackets) It uses CCC str!ct data tye (dr5cmn to indicate &ow t&e acket
attributes are stored) Pro'ram ")8 s&ows a art o/ (dr5cmn declaration) T&e
main member 1ariables o/ (dr5cmn are as /ollows<
ptype5 T&e ayload tye ?see Sect) ")3):@)
si6e5 T&e acket siJe in bytes) 0nlike actual acket transmission* t&e
number o/ bits reDuires to &old a acket &as no relations&i to
simulation acket siJe) .urin' simulation* NS2 uses t&e 1ariable
(dr5cmn99si6e5 as t&e acket siJe)
!id5 T&e I. w&ic& is uniDue to e1ery acket)
dir5t T&e direction to w&ic& t&e acket is mo1in') It is used mainly in
wireless networks< 4 acket can mo1e FDPG ?i)e)* dir5t : 2@ to9
ward &i'&er layers or mo1e FDOWNG toward lower layer
comonents ?i)e)* dir5t : J2@) It can also set to 0* w&en not in
use* by de/ault* Fdir5tG is set to FDOWNG ?see !ine 2, in Pro'ram
")3@)
o""set5 T&e memory location relati1e to t&e be'innin' o/ acket &eader
/rom w&ic& t&e common &eader is stored ?see Sect) ")3)1 and Ci')
")3@)
Crom Ci') ")8* most /unctions o/ class (dr5cmn act as an inter/ace to access
its 1ariables) Per&as* t&e most imortant /unction o/ class (dr5cmn is t&e
/unction access&p' in !ines "H1,) T&is /unction returns a ointer to t&e
common rotocol9 seci/ic &eader o/ t&e inut Packet obBect
N
p) 6e will
discuss t&e acket &eader access mec&anism in 'reater detail in Sect) ")3)8)
1"2 " Packets* Packet Headers* and Header Cormat
Program 7=5 .eclaration o/ C>> (dr ip str!ct data
tye
MMUMnsMcommonMipI(
2 str!ct (dr5ip 7
1 ns5addr5t src5;
3 ns5addr5t dst5;
= int ttl5;
> int "id5;
A int prio5;
B static int o""set5;
/ inline static intF o""set&' 7 ret!rn o""set5; 8
G inline static (dr5ip
N
access&const Packet
N
p' 7
20 ret!rn &(dr5ip
N
' pJKaccess&o""set5';
22 8
21 ns5addr5tF src&' 7 ret!rn &src5'; 8
23 nsaddr5tF saddr&' 7 ret!rn &src5Iaddr5'; 8
2= int315tF sport&' 7 ret!rn src5Iport5;8
2> ns5addr5tF dst&' 7 ret!rn &dst5'; 8
2A nsaddr5tF daddr&' 7 ret!rn &dst5Iaddr5'; 8
2B int315tF dport&' 7 ret!rn dst5Iport5;8
2/ intF ttl&' 7 ret!rn &ttl5'; 8
2G intF "lo,id&' 7 ret!rn &"id5'; 8
10 intF prio&' 7 ret!rn &prio5'; 8
12 8;
?."." IP Pac'et 7eader
(eresented by a CCC struct data tye (dr5ip* IP acket &eader contains
in/ormation about source and destination o/ a acket) Pro'ram ")2 s&ows a art
o/ (dr5ip declaration) IP acket &eader contains t&e /ollowin' /i1e main
1ariables w&ic& contain IP9related acket in/ormation ?see !ines 2H8 in Pro'ram
")2@<
src5 Source node5s address indicated in t&e acket
dst5 .estination node5s address indicated in t&e acket
ttl5 Time to li1e /or t&e acket
"id5 Clow I. o/ t&e acket
prio5 Priority le1el o/ t&e acket
NS2 uses data tye ns5addr5t de/ined in t&e /ile Tns$con/i')& to store node
address) Crom Pro'ram ")"* ns5addr5t is a struct data tye* w&ic& contains
two members< addr5 and port5) +ot& members are o/ tye int315t* w&ic&
is simly an alias /or int data tye ?see !ine 3 and /ile Tns$autocon/9win32)&@)
6&ile addr5 seci/ies t&e node address* port5 identi/ies t&e attac&ed ort ?i/
any@)
T&e 1ariables src5 and dst5 o/ IP &eader are o/ class ns5addr5t)
Hence* Fsrc5Iaddr5G and Fsrc5Iport5G store t&e node address and t&e ort
o/ t&e sendin' a'ent* resecti1ely) Similarly* t&e acket will be sent to a recei1in'
a'ent attac&ed to ort Fdst5Iport5G o/ a node wit& address Fdst5Iaddr5)G
")3 Packet Header 1"3
P r ogram 7=7 .eclaration o / C CC ns addr t s truct da ta tye* a nd int31 t
MMUMnsMcon"i$I(
2 str!ct ns5addr5t 7
1 int315t addr5;
3 int315t port5;
= 8;
MMUMnsMa!tocon"J,in31I(
> typede" int int315t;
!ines 2H11 in Pro'ram ")2 declare t&e 1ariable o""set5* /unction o""set
&o""' and /unction access&p'* w&ic& are essential to access IP &eader o/ a
acket) !ines 12H2, in Pro'ram ")2 are /unctions t&at return t&e 1alues o/ t&e
1ariables)
?.".$ Payload Type
4lt&ou'& stored in common &eader* ayload tye is attributed to t&e entire acket*
not to a rotocol9seci/ic &eader) Eac& acket corresonds to only one ayload
tye but may contain se1eral rotocol9seci/ic &eaders) Cor eAamle* a acket
can be encasulated by bot& TCP and IP rotocols) Howe1er* its tye can be
eit&er audio or TCP acket* 'ut not 'oth)
NS2 stores a ayload tye in a member 1ariable ptype5 o/ a common
acket &eader) T&e tye o/ t&e 1ariable ptype5 is en!m packet5t
de/ined in Pro'ram ")#) 4'ain* members o/ en!m are inte'ers w&ic& are
maed to strin's) Crom Pro'ram ")#* PT5TCP ?!ine 2@ and PT5DDP ?!ine 3@
are maed to , and 1* resecti1ely) Since packet5t declares PT5NT[PE
?reresentin' unde/ined ayload tye@ as t&e last member* t&e 1alue o/
PT5NT[PE is N

1* w&ere N

is t&e number o/ packet5t members) NS2
ro1ides 8, built9in ayload tyes* meanin' t&e de/ault 1alue o/ PT5NT[PE is
3#)
Crom !ines 11H3, in Pro'ram ")#* class p5in"o mas eac& member o/
packet5t to a descrition strin') It &as a static associati1e array 1ariable*
name5 ?!ine 2"@) T&e indeA and 1alue o/ name5 are t&e ayload tye and t&e
corresond9 in' descrition strin'* resecti1ely) Class p5in"o also &as one
imortant /unction name&p' ?!ines 23H28@* w&ic& translates a packet5t
1ariable to a descrition strin')
4t t&e declaration* NS2 declares a 'lobal 1ariable packet5in"o ?usin'
e*tern@* w&ic& is o/ class p5in"o ?!ine 3,@) 4ccessible at t&e 'lobal scoe*
t&e 1ariable packet5in"o ro1ides an access to t&e /unction name&p' o/
class p5in"o) To obtain a descrition strin' o/ a packet5t obBect Fp*G one
may in1oke
packet5in"oIname&ptype'
1": " Packets* Packet Headers* and Header Cormat
Program 7=8 .eclaration o/ en!m packet t tye and class p in"o
MMUMnsMcommonMpacketI(
2 en!m packet5t 7
1 PT5TCP)
3 PT5DDP)
= PT5C.#)
> PT5ADDIO)
A PT5SIDEO)
B PT5ACV)
/ III
G PT5NT[PE MM T(is %DST be t(e LAST one
20 8
22 class p5in"o 7
21 p!blic9
23 p5in"o&' 7
2= name5?PT5TCP@: HtcpH;
2> name5?PT5DDP@: H!dpH;
2A name5?PT5C.#@: HcbrH;
2B name5?PT5ADDIO@: Ha!dioH;
2/ name5?PT5SIDEO@: HvideoH;
2G name5?PT5ACV@: HackH;
10 III
12 name5?PT5NT[PE@: H!nde"inedH;
11 8
13 const c(ar
N
name&packet5t p' const 7
1= i" & p <: PT5NT[PE ' ret!rn name5?p@;
1> ret!rn 0;
1A 8
1B private9
1/ static c(ar
N
name5?PT5NT[PE42@;
1G 8;
30 e*tern p5in"o packet5in"o; M
N
map PT5
N
to strin$ name
N
M
E%ample :** Class A$ent is resonsible /or creatin' and destroyin' network
layer ackets ?see C&a) #@) It is t&e base class o/ TCP and 0.P transort layer
rotocol modules) Class A$ent ro1ides a /unction allocpkt&'* w&ic& is
resonsible /or allocatin' ?i)e)* creatin'@ a acket)
To rint out t&e tye o/ e1ery allocated acket on t&e screen* we modi/y /unction
allocpkt&' o/ class A$ent in /ile Tns$common$a'ent)cc as
/ollows<
MMUMnsMcommonMa$entI(
2 Packet
N
A$ent99allocpkt&' const
1 7
3 Packet
N
p : Packet99alloc&';
= initpkt&p';
> M
N
JJJJJ .e$in Additional Codes JJJJJ
N
M
A (dr5cmn
N
c( : (dr5cmn99access&p';
B packet5t pt : c(JKptype&';
")3 Packet Header 1"2
/ print"&HE*ample Test9 Class A$ent allocates a
packet ,it( type EsTnH) packet5
in"oIname&pt'';
G $etc(ar&';
20 M
N
JJJJJ End Additional Codes JJJJJ
N
M
22 ret!rn &p';
21 8
w&ere !ines 3H1, are added to t&e ori'inal codes) !ine 8 retrie1es t&e re/erence
Fc(G to t&e common acket &eader ?see Sect) ")3)8@) !ine 2 obtains t&e ayload
tye stored in t&e common &eader usin' t&e /unction ptype&'* and assi'ns t&e
ayload tye to 1ariable Fpt)G Note t&at* t&e 1ariable packet5in"o is a 'lobal
1ariable o/ class p5in"o) 6&en t&e 1ariable FptG is /ed as an inut ar'ument*
t&e statement packet5in"oIname&pt' returns t&e descrition strin'
corresondin' to t&e packet5t obBect FptG ?!ine "@)
4/ter recomilin' t&e code* t&e simulation s&ould s&ow t&e tye o/ e1ery
allocated acket on t&e screen) Cor eAamle* w&en runnin' t&e Tcl simulation
scrit in Pro'rams 2)1H2)2* t&e /ollowin' result s&ould aear on t&e screen<
KK ns my"irst5nsItcl
E*ample Test9 Class A$ent allocates a packet ,it( type cbr
E*ample Test9 Class A$ent allocates a packet ,it( type cbr
E*ample Test9 Class A$ent allocates a packet ,it( type cbr
III
?.".+ Protocol(Specific 7eaders
4 rotocol9seci/ic &eader stores acket attributes rele1ant to t&e underlyin' roto9
col only) Cor eAamle* common acket &eader &olds basic acket attributes suc& as
acket uniDue I.* acket siJe* ayload tye* and so on) IP acket &eader contains
IP acket attributes suc& as source and destination IP addresses and ort numbers)
T&ere are :" classi/ications o/ acket &eaders) T&e comlete list o/ rotocol9
seci/ic &eaders wit& t&eir descritions is 'i1en in M12N)
Eac& rotocol9seci/ic &eader in1ol1es t&ree classes< 4 CCC class* and OTcl
class* and a main' class)
7=*=0=% Protoco#.S&ecific Heaer $CC $#asses
In CCC* NS2 uses a str!ct data tye to reresent a rotocol9seci/ic &eader)
It stores acket attributes and its o//set 1alue in members o/ t&e str!ct data
tye) It also ro1ides a /unction access&p' w&ic& returns t&e re/erence to t&e
rotocol9seci/ic &eader o/ a acket
N
p) (eresentin' a rotocol seci/ic &eader*
1"8 " Packets* Packet Headers* and Header Cormat
eac& str!ct data tye is named usin' t&e /ormat (dr5<LLLK* w&ere <LLLK
is an arbitrary strin' reresentin' t&e tye o/ a rotocol9seci/ic &eader) Cor
eAamle* t&e CCC class name /or common acket &eader is (dr5cmn)
In t&e CCC domain* rotocol seci/ic &eaders are declared but not instantiated)
T&ere/ore* NS2 uses a str!ct data tye ?rat&er t&an a class@ to reresent
rotocol9 seci/ic &eaders) No constructor is reDuired /or a rotocol9seci/ic
&eader) Herea/ter* we will re/er to str!ct and class interc&an'eably)
7=*=0=2 A Protoco#.S&ecific Heaer ,Tc# $#ass
NS2 de/ines a s&adow OTcl class /or eac& CCC rotocol seci/ic &eader class)
4n OTcl class acts as an inter/ace to t&e OTcl domain) It is named wit& t&e
/ormat PacketHeaderM<LLLK* w&ere <LLLK is an arbitrary strin'
reresentin' a rotocol9seci/ic &eader) Cor eAamle* t&e OTcl class name /or
common acket &eader is PacketHeaderMCommon)
7=*=0=* A Protoco#.S&ecific Heaer Ma&&ing $#ass
4 main' class is resonsible /or bindin' OTcl and CCC class names to'et&er)
4ll t&e acket &eader main' classes deri1e /rom class PacketHeaderClass
w&ic& is a c&ild class o/ class TclClass) 4 main' class is named wit&
/ormat <LLLKHeaderClass* w&ere <LLLK is an arbitrary strin' reresentin' a
rotocol9seci/ic &eader) Cor eAamle* t&e main' class name /or common acket
&eader is CommonHeaderClass)
Pro'ram ")1, s&ows t&e declaration o/ class PacketHeaderClass* w&ic&
&as two key 1ariables< (rdlen5 in !ine " and o""set5 in !ine #) T&e
1ariable F(drlen5G reresents t&e len't& o/ t&e rotocol9seci/ic &eader)
#
It is
t&e system memory needed to store a rotocol9seci/ic &eader CCC class)
T&e 1ariable
o""set5 indicates t&e location on acket &eader w&ere t&e rotocol9seci/ic
&eader is used)
T&e constructor o/ class PacketHeaderClass in !ines 3 and : takes
two inut ar'uments) T&e /irst inut ar'ument classname is t&e name o/ t&e
corresondin' OTcl class name ?e)')* PacketHeaderMCommon@) T&e second
one* (drlen* is t&e len't& o/ t&e rotocol9seci/ic &eader CCC class) In !ines 3
and :* t&e constructor /eeds classname to t&e constructor o/ class TclClass*
stores (drlen in t&e member 1ariable (drlen5* and resets o""set5 to Jero)
Cunction met(od&ar$c)ar$v' in !ine 3 is an aroac& to take a CCC
action /rom t&e OTcl domain) Cunctions bind5o""set&o""' in !ine 8 and
o""set&o""' in !ine 2 are used to con/i'ure and retrie1e* resecti1ely*
1alue
#
6&ile t&e 1ariable (drlen in class PacketHeaderClass reresents t&e len't& o/ a
rotocol seci/ic &eader* t&e 1ariable (drlen in class Packet reresents total len't& o/
acket &eader)
")3 Packet Header 1"#
Program 7=%: .eclaration o/ class PacketHeaderClass
MMUMnsMcommonMpacketI(
2 class PacketHeaderClass 9 p!blic TclClass 7
1 protected9
3 PacketHeaderClass&const c(ar
N
classname) int (drlen' 9
= TclClass&classname') (drlen5&(drlen')
o""set5&0';78;
> virt!al int met(od&int ar$c) const c(ar
N
const
N
ar$v';
A inline void bind5o""set&int
N
o""' 7 o""set5 : o""; 8;
B inline void o""set&int
N
o""' 7o""set5: o"";8;
/ int (drlen5; MM O o" bytes "or t(is (eader
G int
N
o""set5; MM o""set "or t(is (eader
20 p!blic9
22 TclObject
N
create&int ar$c)const c(ar
N
const
N
ar$v'
7ret!rn 0;8;
21 virt!al void bind&'7
23 TclClass99bind&';
2= TclF tcl : Tcl99instance&';
2> tclIeval"&HEs set (drlen5 EdH) classname5) (drlen5';
2A add5met(od&Ho""setH';
2B 8;
2/ 8;
o/ t&e 1ariable Fo""set5G) Cunction create&ar$c)ar$v' in !ine 11 does
not&in'* since no rotocol9seci/ic &eader CCC obBect is created) It will be o1er9
ridden by t&e deri1ed classes o/ class PacketHeaderClass) Cunction bind&'
in !ines 12H12 'lues t&e CCC class to t&e OTcl class) !ine 13 /irst in1okes t&e
/unction bind&' o/ class TclClass* w&ic& er/orms t&e basic bindin' actions)
!ine 13 eAorts 1ariable F(drlen5G to t&e OTcl domain) !ine 18 re'isters t&e
(Tcl method o""set usin' /unction add5met(od?Fo""setG@)
4art /rom t&e OTcl commands discussed in Sect) 3):* an (Tcl method is
anot&er way to in1oke CCC /unctions /rom t&e OTcl domain) It is imlemented
in CCC 1ia t&e /ollowin' two stes) T&e /irst ste is to de/ine a /unction
met(od&ac)av') 4s can be seen /rom Pro'ram ")11* t&e structure o/
/unction met(od is 1ery similar to t&at o/ t&e /unction command) 4 method
Fo""setG stores t&e inut ar'ument in t&e 1ariable
N
o""set5 ?!ine 2 in
Pro'ram ")11@) T&e second ste in met&od imlementation is to re'ister t&e name
o/ t&e method usin' a /unction Fadd5met(od&str'*G w&ic& takes t&e
met&od name as an inut ar'ument) Cor class PacketHeaderClass* t&e
method o""set is re'istered /rom wit&in /unction bind&III' ?!ine 18 o/
Pro'ram ")1,@)
4 rotocol9seci/ic &eader is imlemented usin' a str!ct data tye* and
&ence does not deri1e /unction command&III' /rom class TclObject)
1,
It
resorts to OTcl methods de/ined in t&e main' class to take CCC actions /rom
t&e OTcl
1,
Since NS2 does not instantiate a rotocol seci/ic &eader obBect* it models a rotocol seci/ic
&eader usin' str!ct data tye)
1"" " Packets* Packet Headers* and Header Cormat
Program 7=%% Cunction met(od o/ class PacketHeaderClass
MMUMnsMcommonMpacketIcc
2 int PacketHeaderClass99met(od&int ac) const c(ar
N
const
N
av'
1 7
3 TclF tcl : Tcl99instance&';
= III
> i" &strcmp&ar$v?2@) Ho""setH' :: 0' 7
A i" &o""set5' 7
B
N
o""set5 : atoi&ar$v?1@';
/ ret!rn TCL5OV;
G 8
20 tclIres!lt"&HWarnin$9 cannot set
o""set5 "or EsH)classname5';
22 ret!rn TCL5OV;
21 8
23 III
2= ret!rn TclClass99met(od&ac) av';
2> 8
Tab#e 7=% Classes and
obBects related to common
acket &eader
Class$obBect Name
C>> class (dr5cmn
OTcl class PacketHeaderMCommon
%ain' class CommonHeaderClass
%ain' 1ariable class5cmn(dr
domain) 6e will s&ow an eAamle use o/ t&e met&od o""set later in Sect)
")3)"* w&en we discuss acket construction mec&anism)
Consider* /or eAamle* a common acket &eader) Its CCC* OTcl* and main'
classes are (dr5cmn* PacketHeaderMCommon* and CommonPacketHeader
Class* resecti1ely ?see Table ")1@) Pro'ram ")12 s&ows t&e declaration o/
class CommonPacketHeaderClass) 4s a c&ild class o/ TclClass* a class
main' 1ariable class5cmn(dr is instantiated at t&e declaration) !ine 3 o/ t&e
constructor in1okes t&e constructor o/ its arent class PacketHeaderClass*
w&ic& takes t&e OTcl class name ?i)e)* PacketHeaderMCommon@ and t&e amount
o/ memory needed to &old t&e CCC class ?i)e)* (dr5cmn@ as inut ar'uments)
Here* Fsi6eo" &(dr5cmn'G comutes t&e reDuired amount o/ memory* /or
(dr5cmn) T&e result o/ t&is statement is /ed as t&e second inut ar'ument) In
!ine
8 o/ Pro'ram ")1,* t&e statement bind5o""set&F(dr5cmn99o""set5' sets
t&e 1ariable o""set5 to s&are t&e address wit& t&e inut ar'ument) T&ere/ore* a
c&an'e in (dr5cmn99o""set5 will result in an automatic c&an'e in t&e
1ariable
N
o""set5 o/ class CommonHeaderClass* and 1ice
1ersa)
")3 Packet Header 1#1
Program 7=%2 .eclaration o/ class CommonHeaderClass
MMUMnsMcommonMpacketIcc
2 class CommonHeaderClass 9 p!blic PacketHeaderClass 7
1 p!blic9
3 CommonHeaderClass&' 9 PacketHeaderClass&HPacketHeaderM
CommonH) si6eo"&(dr5cmn'' 7
= bind5o""set&F(dr5cmn99o""set5';
> 8
A 8 class5cmn(dr;
?."./ Pac'et 7eader Access
Mechanis
T&is section demonstrates &ow acket attributes stored in acket &eader can be
retrie1ed and modi/ied) NS2 uses a two9le1el acket &eader structure to store
acket attributes) On t&e /irst le1el* rotocol9seci/ic &eaders are stored wit&in a
acket &eader) On t&e second le1el* eac& rotocol9seci/ic &eader uses a CCC
str!ct data tye to store acket attributes)
+e/ore roceedin' /urt&er* let us &a1e a look at &ow acket &eader can be
modi/ied)
E%ample :*2* Li1en a ointer to a Packet obBect
N
p* t&e /ollowin' statements
set t&e acket siJe to be 1,,, bytes)
(dr5cmn
N
c( : (dr5cmn99access&p';
c(JKsi6e5 : 2000;
T&e uer line retrie1es t&e re/erence to t&e common &eader and stores t&e
re/erence in t&e ointer Fc(*G w&ile t&e lower line modi/ies t&e acket siJe
t&rou'& t&e /ield si6e5 o/ t&e common acket &eader ?t&rou'&
N
c(@)
T&e &eader access mec&anism consists o/ two maBor stes< ?1@ (etrie1e a
re/erence to a rotocol9seci/ic &eader* and ?2@ Collow t&e structure o/ t&e
rotocol9 seci/ic &eader to retrie1e or modi/y acket attributes) In t&is section* we
will eAlain t&e access mec&anism t&rou'& common acket &eader ?see t&e
corresondin' class names in Table ")1@)
7=*=6=% Retrieving a Reference to Protoco#.S&ecific Heaer
NS2 obtains a re/erence to a rotocol9seci/ic &eader o/ a acket
N
p usin' a
/unction
access&p' o/ t&e CCC class
(dr5cmn)
E%ample :*$* Consider /unction allocpkt&' o/ class A$ent s&own in
Pro'ram ")13* w&ic& s&ows t&e details o/ /unctions allocpkt&' and
1#, " Packets* Packet Headers* and Header Cormat
Program 7=%* Cunctions allocpkt and initpkt o/ class A$ent
MMUMnsMcommonMa$entIcc
2 Packet
N
A$ent99allocpkt&' const
1 7
3 Packet
N
p : Packet99alloc&';
= initpkt&p';
> ret!rn &p';
A 8
B Packet
N
A$ent99initpkt&Packet
N
p' const
/ 7
G (dr5cmn
N
c( : (dr5cmn99access&p';
20 c(JK!id&' : !idcnt544;
22 c(JKptype&' : type5;
21 c(JKsi6e&' : si6e5;
23 III
2= (dr5ip
N
ip( : (dr5ip99access&p';
2> ip(JKsaddr&' : (ere5Iaddr5;
2A ip(JKsport&' : (ere5Iport5;
2B ip(JKdaddr&' : dst5Iaddr5;
2/ ip(JKdport&' : dst5Iport5;
2G III
10 8
initpkt&p') Cunction allocpkt&' in !ines 1H8 creates a Packet obBect
and returns a ointer to t&e created obBect) It /irst in1okes /unction alloc&' o/
class Packet in !ine 3 ?see t&e details in Sect) ")2)1@) T&en* !ine : initialiJes
t&e allocated acket by in1okin' t&e /unction initpkt&p') Cinally* !ine 3
returns t&e ointer FpG w&ic& oints to t&e initialiJed Packet obBect)
Cunction initpkt&p' /ollows t&e structure de/ined in t&e rotocol9seci/ic
&eader CCC classes to set acket attributes to t&e de/ault 1alues) !ines # and 1: in
Pro'ram ")13 eAecute t&e /irst ste in t&e access mec&anism< retrie1e re/erences to
common acket &eader Fc(G and IP &eader Fip(*G resecti1ely)
4/ter obtainin' t&e ointers Fc(G and Fip(*G !ines 1,H12 and !ines 13H1"
carry
out t&e second ste in t&e access mec&anism< access acket attributes t&rou'& t&e
structure de/ined in t&e rotocol9seci/ic &eaders) In t&is ste* t&e rele1ant acket
attributes suc& as uniDue acket I.* ayload tye* acket siJe* source IP address
and ort* and destination IP address and ort* are con/i'ured t&rou'& t&e ointers
Fc(G and Fip()G Note t&at !idcnt ?i)e)* uid count@ is a static member 1ariable
o/ class A$ent w&ic& reresents t&e total number o/ 'enerated ackets) 6e will
discuss t&e details o/ class A$ent later in C&a) #)
Ci'ure ")8 s&ows an internal mec&anism o/ t&e /unction (dr5cmn99
access&p' w&ere FpG is a Packet ointer) 6&en
(dr5cmn99access&p' is eAecuted !ine # in Pro'ram ")8 eAecutes pJ
Kaccess&o""set5'* w&ere o""set5 is t&e member 1ariable o/ class
(dr5cmn* seci/yin' t&e location on
")3 Packet Header 1#3
4ig= 7=6 T&e internal mec&anism o/ t&e /unction access&p' o/ t&e (dr cmn str!ct
data tye* w&ere FpG is a ointer to a Packet obBect
t&e acket &eader allocated to t&e common &eader ?see also Ci') ")3@) On t&e ri'&t9
&and side o/ Ci') ")8* t&e /unction access&o""' simly returns
Fbits5?o""@* w&ere Fbits5G is t&e member 1ariable o/ class Packet
storin' t&e entire acket &eader) Since t&e inut ar'ument o""set5 belon's
to (dr5cmn* t&e state9 ment access&o""set5' essentially returns
Fbits5?(dr5cmn99o""set5@* w&ic& is t&e re/erence to t&e common &eader
stored in t&e Packet obBect
N
p) T&is re/erence is returned as an !nsi$ned
c(ar
N
1ariable) T&en* class (dr5cmn casts t&e returned re/erence to
(dr5cmn
N
data tye and returns it to t&e caller)
Note t&at NS2 simli/ies t&e retri1al o/ rotocal seci/ic &eader re/erence* by
de/inin' re9rocessin' statements<
MMUnsMcommonMpacketI(
Ode"ine HD#5C%N&p' c(dr5cmn99access&p''
Ode"ine HD#5A#P&p' c(dr5arp99access&p''
III
7=*=6=2 Accessing Packet Attributes in a Protoco#.S&ecific Heaer
4/ter obtainin' a re/erence to a rotocol9seci/ic &eader* t&e second ste is to
access t&e acket attributes accordin' to t&e structure seci/ied in t&e rotocol9
seci/ic
1#2 " Packets* Packet Headers* and Header Cormat
Program 7=%/ .eclarations o/ C>> class PacketHeader%ana$er and
main' class PacketHeader%ana$erClass
MMUMnsMcommonMpacketIcc
2 class PacketHeader%ana$er 9 p!blic TclObject 7
1 p!blic9
3 PacketHeader%ana$er&' 7bind&H(drlen5H)
FPacket99(drlen5';8
= 8;
> static class PacketHeader%ana$erClass 9 p!blic TclClass 7
A p!blic9
B PacketHeader%ana$erClass&' 9
TclClass&HPacketHeader%ana$erH' 78
/ TclObject
N
create&int) const c(ar
N
const
N
' 7
G ret!rn &ne, PacketHeader%ana$er';
20 8
22 8 class5packet(dr5m$r;
&eader CCC class) Since NS2 declares a rotocol9seci/ic &eader as a str!ct
data tye* it is /airly strai'&t/orward to access acket attributes once t&e re/erence
to t&e rotocol9seci/ic &eader is obtained ?see EAamle ")3@)
?.".4 Pac'et 7eader Manager
4 acket &eader mana'er is resonsible /or keein' t&e list o/ acti1e rotocols
and settin' t&e o//set 1alues o/ all t&e acti1e rotocols) It is imlemented usin'
a CCC class PacketHeader%ana$er w&ic& is bound to an OTcl class wit&
t&e same name) Pro'ram ")1: and Ci') ")2 s&ow t&e declaration o/ t&e CCC class
PacketHeader%ana$er as well as t&e corresondin' bindin' class* and t&e
dia'ram o/ t&e OTcl class PacketHeader%ana$er* resecti1ely)
T&e CCC class PacketHeader%ana$er &as one constructor ?!ine 3@ and
&as neit&er 1ariables nor /unctions) T&e constructor binds t&e inst1ar
F(drlen5G o/ t&e OTcl class PacketHeader%ana$er to t&e 1ariable
F(drlen5G o/ class Packet ?see also Ci') ")1@) T&e OTcl class
PacketHeader %ana$er &as two main inst1ars< F(drlen5G and
Ftab5)G T&e inst1ar F(drlen5G stores t&e len't& o/ acket &eader) It is
initialiJed to Jero in !ine 1 o/ Pro'ram ")13* and is incremented as rotocol9
seci/ic &eaders are added to t&e acket &eader) (eresentin' t&e acti1e rotocol
list* t&e inst1ar Ftab5G ?!ine 2 in Pro'ram ")18@ is an associati1e array w&ose
indeAes are rotocol9seci/ic &eader OTcl class names and 1alues are 1 i/ t&e
rotocol9seci/ic &eader is acti1e ?see !ine
12 in Pro'ram ")3@) I/ t&e rotocol9seci/ic &eader is inacti1e* t&e corresondin'
1alue o/ Ftab5G will not be a1ailable ?i)e)* NS2 !nsets all entries corresondin'
to inacti1e rotocol9seci/ic &eadersO see !ine 2 in Pro'ram ")2,@)
")3 Packet Header 1#3
*
f
f
s
e
t

a
s
s
i
4
n
m
e
n
t
Packet Heaer $ana%er
Packet
tabC hdrlenC
bind
hdrlenC
:::
'0P
Header
/P
Header
0ommon
Header
:::
4ig= 7=5 4rc&itecture o/ an OTcl PacketHeader%ana$er obBect
Program 7=%0 InitialiJation o/ a PacketHeader%ana$er obBect
MMUMnsMtclMlibMnsJpacketItcl
2 PacketHeader%ana$er set (drlen5 0
1 "oreac( prot 7
3 Common
= Qla$s
> IP
A III
B 8 7
/ addJpacketJ(eader Pprot
G 8
20 proc addJpacketJ(eader ar$s 7
22 "oreac( cl Par$s 7
21 PacketHeader%ana$er set tab5&PacketHeaderMPcl' 2
23 8
2= 8
?.".? Protocol(Specific 7eader Coposition and Pac'et 7eader
Constr!ction
Packet &eader is constructed t&rou'& t&e /ollowin' t&ree9ste rocess<
Program 7=%6 Cunction create packet"ormat o/ class Sim!lator
and /unction alloc(dr o/ class PacketHeader%ana$er
MMUMnsMtclMlibMnsJpacketItcl
2 Sim!lator instproc create5packet"ormat 7 8 7
1 PacketHeader%ana$er instvar tab5
3 set pm ?ne, PacketHeader%ana$er@
= "oreac( cl ?PacketHeader in"o s!bclass@ 7
> i" ?in"o e*ists tab5&Pcl'@ 7
A set o"" ?Ppm alloc(dr Pcl@
B Pcl o""set Po""
/ 8
G 8
20 Psel" set packet%ana$er5 Ppm
22 8
21 PacketHeader%ana$er instproc alloc(dr cl 7
23 set si6e ?Pcl set (drlen5@
2= Psel" instvar (drlen5
2> set NS5ALI-N /
2A set incr ?e*pr &Psi6e 4 &PNS5ALI-NJ2'' F U&PNS5ALI-NJ2'@
2B set base P(drlen5
2/ incr (drlen5 Pincr
2G ret!rn Pbase
10 8
Ste& %2 At the $om&i#ation Time
.urin' t&e comilation* NS2 translates all CCC codes into an eAecutable /ile) It
sets u all necessary 1ariables ?includin' t&e len't& o/ all rotocol9seci/ic
&eaders@ /or all built9in rotocol9seci/ic &eaders* and includes all built9in
rotocol9seci/ic &eaders into t&e acti1e rotocol list) T&ere are t&ree main tasks in
t&is ste)
Task > Construct +ll 5apping ?aria'les= Configure the ?aria'le (drlen
= #egister the (Tcl Class Name= and Binds the (ffset ?alue
Since all main' 1ariables are instantiated at t&e declaration* t&ey are constructed
durin' t&e comilation usin' t&eir constructors) 4s an eAamle* consider t&e
common acket &eader
11
w&ose construction rocess s&own in Pro'ram ")1,*
Pro'ram ")12* and Ci') ")" roceeds as /ollows<
1) Store t&e corresondin' OTcl class name ?e)')* PacketHeaderMCommon@ in
t&e 1ariable classname5 o/ class TclClass)
2) .etermine t&e siJe ?usin' /unction si6eo" &III'@ o/ t&e rotocol9seci/ic
&eader* and store it in t&e 1ariable F(drlen5G o/ class
PacketHeaderClass)
3) +ind t&e 1ariable o""set5 o/ t&e PacketHeader to t&at o/ class
(dr5cmn)
11
NS2 reeats t&e /ollowin' rocess /or all rotocol seci/ic &eaders) Cor bre1ity* we s&ow t&e
construction rocess t&rou'& common acket &eader only)
")3 Packet Header 1#2
0ommonHeader0lass classCcmnhdrE
PacketHeaerClass
;;Pac1etHeader0lass
(classnameDhdrlen)
'cl0lass(classname)
hdrlenC(hdrlen)
offsetC(!)
CommonHeaerClass
;;0ommonHeader0lass()
Pac1etHeader0lass(
LPac1etHeaderN0ommonMD
si<eof(hdrCcmn) )
PacketHeaer#Common (OTcl Class)
!r"cmn (C&& Class)
offsetC
PacketHeaerClass;;bindCoffset(off)
offsetC @ offE
bindCoffset(JhdrCcmn;;offsetC)
return
4ig= 7=7 Construction o/ t&e static main' 1ariable class
cmn(dr
Task 2> Invocation of &unction bind&' of Class TclClass 6hich E%ports
the
?aria'le (drlen
T&e main NS2 /unction ?i)e)* main&ar$c)ar$v'@ in1okes t&e /unction
init&III' o/ class Tcl* w&ic& in turn in1okes t&e /unction bind&' o/
class TclClass o/ all main' 1ariables) T&e /unction bind&' re'isters and
binds an OTcl class name to t&e CCC domain ?see /ile Ttclcl$Tcl)cc@) T&is
/unction is o1erridden by class PacketHeaderClass)
4s s&own in !ines 12H12 o/ Pro'ram ")1,* class PacketHeaderClass
o1errides /unction bind&' o/ class TclClass) !ine 13 /irst in1okes t&e
/unction bind&' o/ class TclClass) !ine 13 eAorts t&e 1ariable F(drlen5G
to t&e OTcl domain) Cinally* !ine 18 re'isters t&e OTcl met&od o""set)
In case o/ class CommonHeaderClass* classname5 is PacketHeaderM
Common and F(drlen5G is 1,: bytes) T&ere/ore* !ine 13 o/ Pro'ram ")1,
eAecutes t&e /ollowin' OTcl statement<
PacketHeaderMCommon set (drlen5 20=
w&ic& sets inst1ar F(drlen5G o/ class PacketHeaderMCommon to be 1,:)
Note t&at t&is inst1ar F(drlen5G is not bound to t&e CCC domain)
4/ter Task 1 and Task 2 are comleted* t&e related rotocol9seci/ic classes*
namely (dr5cmn* PacketHeaderMCommon* and CommonHeaderClass*
would be as s&own in Ci') ")#) T&e main' obBect class5cmn(dr is o/ class
CommonHeaderClass* w&ic& deri1es /rom classes PacketHeaderClass
and TclClass* resecti1ely) It in&erits 1ariables classname5* (drlen5* and
o""set5 /rom its arent class) 4/ter obBect construction is comlete* 1ari9
able classname5 will store t&e name o/ t&e OTcl common acket &eader
4ig= 7=8 4 sc&ematic dia'ram o/ a static main' obBect class cmn(dr* class (dr cmn*
class
PacketHeaderMCommon* and class Packet
class ?i)e)* PacketHeaderMCommon@* (dr5len5 will store t&e amount o/
memory in bytes needed to store common &eader* and o""set5 will oint to
(dr5cmn99 o""set5) Howe1er* at t&is moment* t&e o//set 1alue is set to Jero)
T&e das&ed arrow in Ci') ")# indicates t&at t&e 1alue o/ 1ariable (dr5cmn99
o""set5 will be later set to store an o//set /rom t&e be'innin' o/ a acket
&eader to t&e oint w&ere t&e common acket &eader is stored) 4lso* a/ter t&e
/unction Tcl99init&' in1okes t&e /unction bind&' o/ class
PacketHeaderClass* t&e inst1ar F(drlen5G o/ class
PacketHeaderMCommon will store t&e 1alue o/ t&e 1ariable F(drlen5G o/
class CommonHeaderClass) Note t&at tasks 1 and
2 only set u CCC OTcl class* and main' class) Howe1er* t&e acket &eader
mana'er is not con/i'ured at t&is &ase)
Task $> Sourcing the &ile @ nsAtclAli'Ans)packet*tcl to Setup an +ctive Protocol
.ist
4s discussed in Sect) 3)2* NS2 sources all scritin' Tcl /iles durin' t&e com9
ilation rocess) In re'ards to acket &eader* Pro'ram ")13 s&ows a art o/
t&e /ile Tns$tcl$lib$ns9acket) Here* !ine " in1okes rocedure addJpacketJ
")3 Packet Header 1##
(eader/prot' /or all built9in rotocol9seci/ic &eaders indicated in !ines 3H8)
!ine 12 sets t&e 1alue o/ t&e associati1e array Ftab5G w&ose indeA is t&e inut
rotocol9seci/ic &eader name to be 1)
Ste& 22 -uring the Network $onfiguration Phase
In re'ards to acket &eader construction* t&e main task in t&e Network
Con/i'uration P&ase is to setu 1ariables o""set5 o/ all acti1e rotocol9
seci/ic &eaders and /ormulate a acket &eader /ormat) SubseDuent acket creation
will /ollow t&e acket /ormat created in t&is ste)
T&e o//set con/i'uration rocess takes lace durin' t&e simulator construction)
Crom !ine 2 o/ Pro'ram :)11* t&e constructor o/ t&e Simulator in1okes t&e
instroc create5packet"ormat/' o/ class Sim!lator)
4s s&own in Pro'ram ")18* t&e instroc create5packet"ormat/' creates a
PacketHeader%ana$er obBect FpmG ?!ine 3@) Here* t&e constructor o/ CCC
class PacketHeader%ana$er is in1oked) Crom Pro'ram ")1:* t&e
constructor
binds its OTcl inst1ar F(drlen5G to t&e 1ariable F(drlen5G o/ t&e CCC class
Packet)
4/ter creatin' a PacketHeader%ana$er obBect Fpm*G t&e instroc
create5
packet"ormat/' comutes t&e o//set 1alue o/ all acti1e rotocol9seci/ic &ead9
ers usin' t&e instroc alloc(dr/cl' ?!ine 8@* and con/i'ures t&e o//set 1al9
ues o/ all rotocol seci/ic &eaders ?!ine 2@) T&e "oreac( loo in !ine :
runs /or all built9in rotocol9seci/ic &eaders w&ic& are c&ild classes o/ class
PacketHeader) !ine 3 /ilters out t&ose w&ic& are not in t&e acti1e rotocol
list ?see Sect) ")3)2@) !ines 8 and 2 are eAecuted /or all acti1e rotocol9seci/ic
&eaders seci/ied in t&e 1ariable Ftab5G ?w&ic& was con/i'ured in Ste 1 H Task
3@ o/ t&e PacketHeader%ana$er obBect Fpm)G !ine 2 con/i'ures o//set
1alues
usin' t&e OTcl method o""set ?see Pro'ram ")11@ o/ rotocol seci/ic &eader
main' classes) T&e OTcl method o""set stores t&e inut ar'ument in t&e
1ariable
N
o""set5 o/ t&e rotocol9seci/ic &eader main' class ?e)')*
Common
HeaderClass@)
!ines 12H1# in Pro'ram ")18 and Ci') ")1, s&ow t&e OTcl source codes
and t&e dia'ram* resecti1ely* o/ t&e instroc alloc(dr/cl' o/ an OTcl class
PacketHeader%ana$er) T&e instroc alloc(dr/cl' takes one inut ar'u9
ment FclG ?in !ine 12@ w&ic& is t&e name o/ a rotocol9seci/ic &eader* comutes
t&e memory reDuirement* and returns t&e o//set 1alue corresondin' to t&e inut
ar'ument Fcl)G !ine 13 stores &eader len't& o/ a rotocol9seci/ic &eader FclG
?e)')* t&e 1ariable F(drlen5G o/ class PacketHeaderMCommon@ in a local
1ariable Fsi6e)G
12
+ased on Fsi6e*G !ines 13 and 18 comute t&e amount o/
12
T&e 1ariable (drlen o/ a rotocol seci/ic &eader OTcl class was con/i'ured in Ste 1 H Task
2)
1#" " Packets* Packet Headers* and Header Cormat
4ig= 7=%: 4 dia'ram reresentin' t&e instroc alloc(dr o/ class
PacketHeader%ana$er) !ine numbers s&own on t&e left corresond to t&e lines in Pro'ram
")18) T&e action corresondin' to eac& line is s&own on t&e right
memory ?incr@ needed to store t&e &eader)
13
!ine 12 stores t&e current acket
&eader len't& ?eAcludin' t&e inut rotocol9seci/ic &eader@ in a local 1ariable
Fbase)G Since FbaseG is an o//set distance /rom t&e be'innin' o/ acket &eader
to t&e inut rotocol9seci/ic &eader* it is returned to t&e caller as t&e o//set 1alue
in !ine 1#) 4/ter !ine 1" increases t&e &eader len't& ?i)e)* t&e inst1ar F(drlen5G
o/ class PacketHeader%ana$er@ by Fincr)G
.urin' t&e Sim!lator construction* t&e acket &eader mana'er also u9
dates its 1ariable F(drlen5G ?!ine 1# in Pro'ram ")18@) Note t&at t&e inst1ar
F(drlen5G o/ class PacketHeader%ana$er was set to Jero at t&e
comilation
?!ine 1 in Pro'ram ")13@) 4s !ines 8 and 2 in Pro'ram ")18 reeat /or e1ery
rotocol9seci/ic &eader* t&e o//set 1alue is added to t&e inst1ar F(drlen5G o/ an
OTcl class PacketHeader%ana$er) 4t t&e end* t&e inst1ar F(drlen5G will
reresent t&e total &eader len't&* w&ic& embraces all rotocol9seci/ic &eaders)
Ste& *2 -uring the Simu#ation Phase
.urin' t&e Simulation P&ase* NS2 creates ackets based on t&e /ormat de/ined
in t&e /ormer two stes) Cor eAamle* an A$ent obBect creates and initialiJes a
acket usin' its /unction allocpkt&') Here* a acket is created usin' t&e
/unction
13
T&e 1ariable FincrG could be 'reater t&an Fsi6e*G deendin' on t&e underlyin' &ardware)
"): .ata Payload 2,1
bandwidt&
alloc&' o/ class Packet and initialiJed usin' t&e /unction initpkt&p'
o/ class A$ent) 4'ain* t&e /unction alloc&' takes a acket /rom t&e /ree
acket list* i/ it is nonemty) Ot&erwise* it will create a new acket usin' Fne,G)
4/ter retrie19 in' a acket* it clears t&e 1alues stored in t&e acket &eader and data
ayload) T&e /unction initpkt&p' assi'ns de/ault 1alues to acket attributes
suc& as acket uniDue I.* ayload tye* and acket siJe ?see Pro'ram ")13@) T&e
initialiJation is er/ormed by retrie1in' a re/erence ?e)')* Fc(G@ to t&e rele1ant
rotocol9seci/ic &eader and accessin' acket attributes usin' t&e rede/ined
structure)
7=/ -ata Pay#oa
Imlementation o/ data ayload in NS2 di//ers /rom actual data ayload) In
ractice* user in/ormation is trans/ormed into bits and are stored in data ayload)
Suc& t&e trans/ormation is not necessary in simulation* since NS2 stores t&e user
in/ormation in t&e acket &eader) NS2 rarely needs to maintain data ayload) In
!ine 11 o/ Pro'ram 2)3* acket transmission time* i)e)* t&e time reDuired to send
out a acket*
is comuted as
ac ket s iJ e
) Class LinkDelay determines t&e siJe o/ a acket
by
(dr5cmn99si6e5 ?not by countin' t&e number o/ bits stored in acket &eader
and data ayload@ to comute acket transmission time) In most cases* users do
not
need to eAlicity deal wit& data ayload)
NS2 also ro1ides a suort to &old data ayload) In !ine : o/ Pro'ram ")1*
class Packet ro1ides a ointer Fdata5G to an AppData obBect)
1:
Pro'ram
")12 s&ows t&e declaration o/ an abstract class AppData) Class AppData &as
only one member 1ariable type5 in !ine 11) 4mon' its /unctions* and one is a
ure 1irtual /unction copy&' s&own in !ine 1") Indicatin' t&e tye o/
alication* t&e 1ariable type5 is o/ tye en!m AppDataType de/ined in
!ines 1H") T&e /unction copy&' dulicates an AppData obBect to a new
AppData obBect) It is a ure 1irtual /unction* and must be o1erridden by c&ild
instantiable classes o/ class AppData) Cunction si6e&' in !ine 12 returns t&e
amount o/ memory reDuired to store an AppData obBect)
Class AppData ro1ides two constructors) One is in !ine 13* w&ere t&e caller
/eeds an AppData tye as an inut ar'ument) 4not&er is in !ine 1:* w&ere a
re/erence to a AppData obBect is /ed as an inut ar'ument) In bot& t&e cases*
t&e constructor simly sets t&e 1ariable type5 to a 1alue as seci/ied in t&e
inut
ar'ument)
Pro'ram ")1" s&ows t&e declaration o/ class PacketData* a c&ild class o/
class AppData) T&is class &as two new member 1ariables< Fdata5G ?a strin'
1ariable w&ic& stores data ayload@ in !ine 3 and datalen5 ?t&e len't& o/
Fdata5G@ in !ine :) !ine 23 de/ines a /unction data&' w&ic& simly returns
Fdata5)G !ines
28 and 22 o1erride t&e 1irtual /unctions si6e&' and copy&'* resecti1ely* o/
2,, " Packets* Packet Headers* and Header Cormat
1:
Howe1er* no memory is allocated to t&e AppData obBect unless it is needed)
"): .ata Payload 2,1
Program 7=%5 .eclaration o/ en!m AppDataType and class AppData
MMUMnsMcommonMnsJprocessI(
2 en!m AppDataType 7
1 III
3 PACVET5DATA)
= HTTP5DATA)
> III
A ADD5LAST
B
/ 8;
G class AppData 7
20 private9
22 AppDataType type5; MM ADD type
21 p!blic9
23 AppData&AppDataType type' 7 type5 : type; 8
2= AppData&AppDataF d' 7 type5 : dItype5; 8
2> virt!al UAppData&' 78
2A AppDataType type&' const 7 ret!rn type5; 8
2B virt!al int si6e&' const 7 ret!rn si6eo"&AppData'; 8
2/ virt!al AppData
N
copy&' : 0;
2G 8;
class AppData) Cunction si6e&' simly returns datalen5) Cunction
copy&' creates a new PacketData obBect w&ic& &as t&e same content as
t&e current PacketData obBect* and returns t&e ointer to t&e created obBect to
t&e caller)
Class PacketData &as two constructors) One is to construct a new obBect
wit& siJe Fs6*G usin' t&e constructor in !ines 8H12) T&is constructor simly
sets t&e de/ault alication data tye to be PACVET5DATA ?!ine 8@* stores
Fs6G in Fdatalen5G ?!ine 2@* and allocates memory o/ siJe Fdatalen5G
to Fdata5G ?!ine #@) 4not&er construction met&od
13
is to create a coy o/ an
inut PacketData obBect ?!ines 13H2,@) In t&is case* t&e constructor /eeds an
inut PacketData obBect FdG to t&e arent class ?!ine 13@* coies t&e 1ariable
datalen5 ?!ine 1:@* and dulicates its data ayload ?!ine 12@)
18
NS2 creates a PacketData obBect t&rou'& two /unctions o/ class Packet<
alloc&n' and allocdata&n') In Pro'ram "):* t&e /unction alloc&n'
allo9 cates a acket in !ine 3 and creates data ayload usin' t&e /unction
allocdata&n' in !ine 3) T&e /unction allocdata&n' creates a
PacketData obBect o/ siJe Fn*G by eAecutin' Fne, PacketData&n'G in
!ine 11)
Pro'ram ")1# s&ows /our /unctions w&ic& can be used to maniulate data
ayload) Cunctions accessdata&' ?!ines :H#@ and !serdata&' ?!ine 1,@
are bot& data ayload access /unctions) T&e di//erence is t&at t&e /unction
13
Cunction copy&' in !ine 22 uses t&is constructor to create a coy o/ a PacketData obBect)
18
Cunction memcpy&dst)src)n!m' coies Fn!mG data bytes /rom t&e location ointed by
FsrcG to t&e memory block ointed by Fdst)G
2,2 " Packets* Packet Headers* and Header Cormat
Program 7=%7 .eclaration o/ class PacketData
MMUMnsMcommonMpacketI(
2 class PacketData 9 p!blic AppData 7
1 private9
3 !nsi$ned c(ar
N
data5;
= int datalen5;
> p!blic9
A PacketData&int s6' 9 AppData&PACVET5DATA' 7
B datalen5 : s6;
/ i" &datalen5 K 0'
G data5 : ne, !nsi$ned c(ar?datalen5@;
20 else
22 data5 : NDLL;
21 8
23 PacketData&PacketDataF d' 9 AppData&d' 7
2= datalen5 : dIdatalen5;
2> i" &datalen5 K 0' 7
2A data5 : ne, !nsi$ned c(ar?datalen5@;
2B memcpy&data5) dIdata5) datalen5';
2/ 8 else
2G data5 : NDLL;
10 8
12 virt!al UPacketData&' 7
11 i" &data5 C: NDLL'
13 delete ?@data5;
1= 8
1> !nsi$ned c(ar
N
data&' 7 ret!rn data5; 8
1A virt!al int si6e&' const 7 ret!rn datalen5; 8
1B virt!al AppData
N
copy&' 7 ret!rn ne, PacketData&
N
t(is';8
1/ 8;
accessdata&' returns a direct ointer to a string Fdata5G w&ic& contains
data ayload w&ile t&e /unction !serdata&' returns a ointer to an AppData
o'3ect w&ic& contains data ayload) Cunction setdata&d' ?!ines 11H13@ sets
t&e ointer Fdata5G to oint to t&e inut ar'ument Fd)G Cinally* /unction
datalen&' in !ine
18 returns t&e siJe o/ data ayload)
7=0 $ustomiCing Packets
?.+.1 Creating 6o!r O&n
Pac'et
6&en desi'nin' a new rotocol* ro'rammers may need to c&an'e t&e acket
/ormat) T&is section 'i1es a 'uideline o/ &ow acket &eader* data ayload* or bot&
can be modi/ied) Note t&at* it is recommended not to use data ayload in
simulation) I/ ossible* include in/ormation related to t&e new rotocol in a
rotocol9seci/ic &eader)
")3 CustomiJin' Packets 2,3
Program 7=%8 Cunctions accessdata* !serdata* setdata and datalen
o/ cla s s Packet
MMUMnsMcommonMpacketI(
2 class Packet 9 p!blic Event 7
1 III
3 p!blic9
= inline !nsi$ned c(ar
N
accessdata&' const 7
> i" &data5 :: 0'
A ret!rn 0;
B assert&data5JKtype&' :: PACVET5DATA';
/ ret!rn &&&PacketData
N
'data5'JKdata&'';
G 8
20 inline AppData
N
!serdata&' const 7ret!rn data5;8
22 inline void setdata&AppData
N
d' 7
21 i" &data5 C: NDLL'
23 delete data5;
2= data5 : d;
2> 8
2A inline int datalen&' const 7 ret!rn data5 Y data5
JKsi6e&' 9 0; 8
2B III
2/ 8;
7=0=%=% -efining a New Packet Heaer
Suose we would like to include a new rotocol9seci/ic &eader* namely F%y
Header*G into t&e acket &eader) 6e need to de/ine a CCC class ?e)')*
(dr5my(dr@* an OTcl class ?e)')* PacketHeaderM%yHeader@* and a
main' class ?e)')* %yHeaderClass@* and include t&e OTcl class into t&e
acti1e rotocol list) In articular* we need to er/orm t&e /ollowin' /our stes<
Ste& %2 .e/ine a CCC rotocol9seci/ic &eader structure ?e)')* see Pro'ram
")8@)
H Pick a name /or t&e CCC str!ct data tye* say str!ct (dr5my(dr)
H .eclare a 1ariable o""set5 to identi/y w&ere t&e rotocol9seci/ic &eader
reside in t&e entire &eader)
H .e/ine a /unction access&p' w&ic& returns t&e re/erence to t&e rotocol9
seci/ic &eader ?see !ines "H1, in Pro'ram ")8@)
H Include all member 1ariables reDuired to &old new acket attributes)
H QOtional Include a new ayload tye into en!m packet5t and class
p5in"o ?e)')* see Pro'ram ")#@) 4'ain* a new ayload tye does not need
to be added /or e1ery new rotocol9seci/ic &eader)
Ste& 22 Pick an OTcl name /or t&e rotocol seci/ic &eader* e)')* Packet
HeaderM%yHeader)
2,: " Packets* Packet Headers* and Header Cormat
Ste& *2 +ind t&e OTcl name wit& t&e CCC rotocol9seci/ic &eader structure)
.eri1e a main' class %yHeaderClass /rom class PacketHeaderClass
?e)')* see class CommonHeaderClass in Pro'ram ")12@)
H 4t t&e construction* /eed t&e OTcl name ?i)e)*
PacketHeaderM%yHeader@ and t&e siJe needed to &old t&e rotocol9
seci/ic &eader ?i)e)* si6eo"&(dr5 my(dr'@ to t&e constructor o/
class PacketHeaderClass ?e)')* see !ine 3 in Pro'ram ")12@)
H Crom wit&in t&e constructor o/ t&e main' class* in1oke /unction bind5
o""set&III' /eedin' t&e address o/ t&e 1ariable o""set5 o/ t&e
CCC str!ct data tye as an inut ar'ument ?i)e)* in1oke
bind5o""set &F(dr5my(dr99o""set5'@)
H Instantiate a main' 1ariable class5my(dr at t&e declaration)
Ste& /2 4cti1ate t&e rotocol9seci/ic &eader /rom t&e OTcl domain) 4dd t&e
OTcl name to t&e list de/ined wit&in t&e acket &eader mana'e) In articular*
modi/y !ines 2H# o/ Pro'ram ")13 as /ollows<
"oreac( prot 7
Common
Qla$s
III
%yHeader
8 7
addJpacketJ(eader Pprot
8
w&ere only t&e su//iA o/ t&e new rotocol9seci/ic &eader ?i)e)* %yHeader@ is
added to t&e "oreac( loo)
7=0=%=2 -efining a New -ata Pay#oa
.ata ayload can be created in /our le1els<
1) None< NS2 rarely uses data ayload in simulation) To a1oid any comlication it
is su''ested not to use data ayload in simulation)
2) 0se class PacketData< T&e simlest /orm o/ storin' data ayload is to use
class PacketData ?see Pro'ram ")1"@) Class Packet &as a 1ariable
Fdata5G w&ose class is PacketData* and ro1ides /unctions ?in Pro'ram
")1#@ to maniulate t&e 1ariable Fdata5)G
3) .eri1e a class ?e)')* class %yPacketData@ /rom class PacketData< T&is
otion is suitable w&en new /unctionalities ?i)e)* /unctions and 1ariables@ in
addition to t&ose ro1ided by class PacketData are needed) 4/ter deri1in'
a new PacketData class* ro'rammers may also deri1e a new class ?e)')*
class %yPacket@ /rom class Packet* and o1erride t&e 1ariable Fdata5G o/
class Packet to be a ointer to a %yPacketData obBect)
")3 CustomiJin' Packets 2,3
:) .e/ine a new data ayload class< 4 user can also de/ine a new ayload tye
i/ needed) T&is otion s&ould be used w&en t&e new ayload &as not&in' in
common wit& class PacketData) T&e /ollowin' are t&e main tasks needed
to de/ine and use a new ayload tye %[5DATA)
Include t&e new ayload tye ?e)')* %[5DATA@ into en!m AppDataType
data tye ?see Pro'ram ")12@)
.eri1e a new ayload class %yData /rom class AppData)
H Ceed t&e ayload tye %[5DATA to t&e constructor o/ class AppData)
H Include any ot&er necessary /unctions and 1ariables)
H O1erride /unctions si6e&' and copy&')
.eri1e a new class %yPacket /rom class Packet
H .eclare a 1ariable o/ class %yData to store data ayload)
H Include /unctions to maniulate t&e abo1e %yData 1ariable)
?.+.2 Acti#ate/)eacti#ate a Protocol(Specific 7eader
+y de/ault* NS2 includes all built9in rotocol9seci/ic &eaders into acket &eader
?see Pro'ram ")13@) T&is inclusion can lead to unnecessary wasta'e o/ memory
esecially in a packet)intensive simulation* w&ere numerous ackets are created)
Cor eAamle* common* IP* and TCP &eaders to'et&er use only ,)1 k+* w&ile t&e
de/ault acket &eader consumes as muc& as 1)# k+ M12N) 4'ain* NS2 does not
return t&e memory allocated to a Packet obBect until t&e simulation terminates)
Selecti1ely includin' rotocol9seci/ic &eader can lead to &u'e memory sa1in')
T&e acket /ormat is de/ined w&en t&e Simulator is created) T&ere/ore* a
rotocol9seci/ic &eaders must be acti1ated$deacti1ated be/ore t&e creation o/ t&e
Simulator) NS2 ro1ides t&e /ollowin' OTcl rocedures to acti1ate$ deacti1ate
rotocol9seci/ic &eaders<
To add a rotocol9seci/ic &eader PacketHeaderM%H2* eAecute
addJpacketJ(eader %H2
In !ines 1,H1: o/ Pro'ram ")13* t&e abo1e statement includes PacketHeJ
aderM%H2 to t&e 1ariable Ftab5G o/ class PacketHeader%ana$er)
To remo1e a rotocol9seci/ic &eader PacketHeaderM%H2 /rom t&e acti1e
list* eAecute
removeJpacketJ(eader %H2
T&e details o/ rocedure removeJpacketJ(eader/ar$s' are s&own in
!ines 1H# o/ Pro'ram ")2,) !ine 2 remo1es t&e entries wit& t&e indeA Packet
HeaderM%H2 /rom t&e 1ariable Ftab5G o/ class PacketHeader%ana$er)
2,8 " Packets* Packet Headers* and Header Cormat
Program 7=2: Procedures removeJpacketJ(eader* and removeJallJ
packetJ(eader
MMUnsMtclMnsJpacketItcl
2 proc removeJpacketJ(eader ar$s 7
1 "oreac( cl Par$s 7
3 i" 7 Pcl :: HCommonH 8 7
= ,arn HCannot e*cl!de common packet (eaderIH
> contin!e
A 8
B PacketHeader%ana$er !nset tab5&PacketHeaderMPcl'
/ 8
G 8
20 proc removeJallJpacketJ(eaders 78 7
22 PacketHeader%ana$er instvar tab5
21 "oreac( cl ?PacketHeader in"o s!bclass@ 7
23 i" 7 Pcl C: HPacketHeaderMCommonH 8 7
2= i" ?in"o e*ists tab5&Pcl'@ 7
2> PacketHeader%ana$er !nset tab5&Pcl'
2A 8
2B 8
2/ 8
2G 8
To remo1e all rotocol9seci/ic &eaders* eAecute
removeJallJpacketJ(eader
In !ines 1,H1# o/ Pro'ram ")2,* t&e rocedure removeJallJpacketJ
(eader/' uses "oreac( to remo1e all rotocol9seci/ic &eaders ?eAcet /or
common &eader@ /rom t&e acti1e rotocol list)
7=6 $ha&ter Summary
Consistin' o/ acket &eader and data ayload* a acket is reresented by a CCC
class Packet) Class Packet consists o/ ointers Fbits5G to its acket &eader
and Fdata5G to its data ayload) It uses a ointer Fne*t5G to /orm a link list o/
ackets) It also &as a ointer F"ree5G w&ic& oints to t&e /irst Packet obBect
on t&e /ree acket list) 6&en a Packet obBect is no lon'er in use* NS2 stores t&e
Packet obBect in t&e /ree acket list /or /uture reuse) 4'ain* Packet obBects
are not destroyed until t&e simulation terminates) 6&en allocatin' a acket* NS2
/irst tries to take a Packet obBect /rom t&e /ree acket list) Only w&en t&e /ree
acket list is emty* will NS2 create a new Packet obBect)
.urin' simulation* NS2 usually stores rele1ant user in/ormation ?e)')* acket
siJe@ in acket &eader* and rarely uses data ayload) It is recommended not to
use data ayload i/ ossible* since storin' all in/ormation in acket &eader 'reatly
simli/ies t&e simulation yet yields t&e same simulation results)
")2 EAercises 2,2
Packet &eader consists o/ se1eral rotocol9seci/ic &eaders) Eac& rotocol9
seci/ic &eader occuies a conti'uous art in acket &eader and identi/ies t&e
occuied location usin' its 1ariable o""set5) NS2 uses a acket &eader mana'er
?reresented by an OTcl class PacketHeader%ana$er@ to maintain a list o/
acti1e rotocols* and de/ine acket &eader /ormat usin' t&e list w&en t&e Simulator
is created) T&e acket &eader construction rocess roceeds in t&e t&ree /ollowin'
stes<
1) +t the Compilation< NS2 de/ines t&e /ollowin' t&ree classes /or eac& o/
rotocol9 seci/ic &eaders<
+ CCC class< NS2 uses CCC str!ct data tye to de/ine &ow acket
attributes are stored in a rotocol seci/ic &eader) One o/ t&e imortant
member 1ariables is o""set5* w&ic& indicates t&e location o/ t&e rotocol9
seci/ic &eader on t&e acket &eader)
+n (Tcl class< .urin' t&e Network Con/i'uration P&ase* t&e acket &eader
mana'er con/i'ures acket &eader /rom t&e OTcl domain)
+ mapping class< 4 main' class binds t&e OTcl and CCC class to'et&er)
It declares a method o""set* w&ic& is in1oked by a acket &eader mana'er
/rom t&e OTcl domain to con/i'ure t&e 1alue o/ t&e 1ariable o""set5 o/
t&e CCC class PacketHeaderClass)
2) +t the Network Configuration Phase< 4 user may add$remo1e rotocol seci/ic
&eaders to$/rom t&e acti1e rotocol list) 6&en t&e Simulator is created* t&e
acket &eader mana'er comutes and assi'ns aroriate o//set 1alues to all
rotocol9 seci/ic &eaders seci/ied in t&e acti1e list)
3) +t the Simulation Phase< NS2 /ollows t&e abo1e acket &eader de/initions w&en
allocatin' a acket)
7=5 "<ercises
1) 6&at are actual ackets* class Packet* data ayload* acket &eader*
rotocol9 seci/ic &eaderR EAlain t&eir similarities$di//erences$relations&is)
.raw a dia'ram to suort your answer)
2) Consider standard IP acket &eader as seci/ied in M21N) How does NS2 store
t&is acket &eader in/ormationR
3) 6&at is t&e /ree acket listR How does it relate to t&e 1ariable F"ree5G o/
class
PacketR .raw a dia'ram to suort your answer)
:) 6&at is t&e urose o/ t&e 1ariable F""la$5G o/ class PacketR 6&en is it
usedR How is it usedR
3) EAlain t&e acket destruction rocess) .raw a dia'ram to suort your
answer)
2," " Packets* Packet Headers* and Header Cormat
8) 6&at is t&e urose o/ t&e 1ariable Fo""set5G de/ined /or eac& rotocol9
seci/ic &eaderR EAlain your answer 1ia /ew eAamles o/ rotocol seci/ic
&eader)
2) 6&ere and &ow does NS2 de/ine acti1e rotocol listR 6rite /ew statements to
acti1ate$deacti1ate rotocol9seci/ic &eaders)
") .esi'n a new acket &eader w&ic& can record a collection o/ time 1alues)
Pass t&e acket wit& new &eader t&rou'& a network) 6&en t&e acket enters
a LinkDelay obBect* add t&e current simulation time into t&e time 1alue
collection and rint out all t&e 1alues in t&e collection)
#) .esi'n a new data ayload tye) Cor simlicity* set e1ery bit in t&e ayload to
F1G) (un a ro'ram to test your answer)
1,) 6rite CCC statements to er/orm t&e /ollowin' tasks<
a) S&ow t&e /ollowin' in/ormation /or a acket
N
p on t&e screen< SiJe*
source and destination IP addresses and orts* ayload tye* and /low I.)
b) Create a new acket)
c) .estroy t&e acket
N
p)
$ha&ter 8
Trans&ort $ontro# Protoco#s Part %2
An ,verview an 9ser -atagram Protoco#
'm&#ementation
4 tyical communication system consists o/ alications* transort layer a'ents*
and a low9le1el network) 4n alication models user demand to transmit data)
Takin' user demand as an inut* a sendin' transort layer a'ent creates ackets
and /orwards t&em to t&e associated recei1in' transort layer a'ent t&rou'& a low9
le1el network ser1ices) Ha1in' discussed t&e details o/ low9le1el network
/unctionalities in C&as) 3H2* t&e details o/ transort layer a'ents are resented
&ere in C&as) # and 1,) 4lso* t&e details o/ alications will be resented in
C&a) 11)
T&is c&ater ro1ides an o1er1iew o/ transort layer a'ents and s&ows NS2
imlementation o/ 0ser .ata'ram Protocol ?0.P@ a'ents) In articular* Sect) #)1
introduces two most widely used transort control rotocols< Transmission
Control Protocol ?TCP@ and 0.P) Section #)2 eAlains NS2 imlementation o/
basic a'ents) Section #)3 s&ows t&e imlementation o/ 0.P a'ents and Null
a'ents) Cinally* t&e c&ater summary is 'i1en in Sect) #):)
8=% 9-P an T$P Basics
@.1.1 0)P 2asics
.e/ined in M22N* 0.P is a connectionless transort9layer rotocol* w&ere no
connection setu is needed be/ore data trans/er) 0.P o//ers minimal transort
layer /unctionalities H non9'uaranteed data deli1ery H and 'i1es alications a
direct access to t&e network layer) 4side /rom t&e multileAin'$demultileAin'
/unctions and some li'&t error c&eckin'* it adds not&in' to IP ackets) In /act* i/
t&e alication de1eloer uses 0.P as a transort layer rotocol* t&en t&e
alication is communicatin' almost directly wit& t&e network layer)
0.P takes messa'es /rom an alication rocess* attac&es source and
destination orts /or t&e multileAin'$demultileAin' ser1ice* adds two ot&er
/ields o/ error
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* .OI
1,)1,,2$#2"919:81:91:,893 #* = Srin'er Science>+usiness %edia* !!C 2,12
2,#
#)1 0.P and TCP +asics 211
G
4ig= 8=% %ain &ases o/ TCP
oeration< Connection setu*
data trans/er* and connection
termination
SO)
,0P
SO)$,0P
0*))+0'/*)
S+'?P
PH,S+
D,', '=,)S.+=
PH,S+
./)
0*))+0'/*)
'+=M/),'/*)
PH,S+
,0P
./)
,0P
c&eckin' and len't& in/ormation* and asses t&e resultin' acket to t&e network
layer M22N) T&e network layer encasulates t&e 0.P acket into a network layer
acket and t&en deli1ers t&e encasulated acket at t&e recei1in' &ost) 6&en a
0.P acket arri1es at t&e recei1in' &ost* it is deli1ered to t&e recei1in' 0.P
a'ent identi/ied by t&e destination ort /ield in t&e acket &eader)
@.1.2 TCP 2asics
4s s&own in Ci') #)1* TCP M2,H22N is a connection9oriented reliable transort
rotocol consistin' o/ t&ree &ases o/ oerations< connection setu* data trans/er*
and connection termination) In t&e connection setup &ase* a TCP sender initiates
a t&ree9way &ands&ake ?i)e)* sendin' S[N* S[NJACV* and ACV messa'es@) 4/ter
a connection is establis&ed* TCP enters t&e data transfer &ase w&ere a TCP
sender trans/ers data to a TCP recei1er) Cinally* a/ter t&e data trans/er is comlete*
TCP tears down t&e connection in t&e connection termination &ase usin' a /our9
way &ands&ake ?i)e)* sendin' two airs o/ QINJACV messa'es)@
T&e main oeration o/ TCP lies in t&e data trans/er &ase* w&ic& imlements
t&e /ollowin' two mec&anisms< ?1@ error control usin' basic acknowled'ment and
timeout* and ?2@ con'estion control usin' a window9based mec&anism)
(TO* resecti1ely* w&en t&e kt& (TT samle is determined) T&en*
t )k C 1$ . X t )k$ C )1 X$ t )k C 1$O ?#)1@

t
)k C 1$ . Y
t
)k$ C )1 Y$ Bt )k C 1$ t )k$BO ?#)2@
(TO)k C 1$ . min/ubO maA/l bO Qt)k C 1$ C :
t
)k C 1$ ''O ?#)3@
'0P Sender
='*
1 2 3 4 % & 3
'0P =ecei(er
,1
,2 ,2 ,2 ,2
4ig= 8=2 4n eAamle o/ TCP error control usin' acknowled'ment< 4 TCP sender realiJes t&e
loss o/ TCP acket number 3 a/ter transmittin' t&e acket number 3 /or a eriod o/ (TO ?i)e)*
timeout@
8=%=2=% "rror $ontro# 9sing Basic Acknow#egment an Timeout
4s a reliable transort layer rotocol* TCP ro1ides connection reliability by
means o/ acknowled'ment ?4CK@) Cor e1ery recei1ed acket* a TCP recei1er
returns an 4CK acket to t&e sender) I/ an 4CK acket is not recei1ed wit&in a
'i1en timeout 1alue* t&e TCP sender will assume t&at t&e acket is lost* and
will retransmit t&e lost acket) Note t&at in t&e literature* a timeout eriod is
also re/erred to as (etransmission TimeOut ?(TO@) Herea/ter* we will re/er to
t&ese two terms interc&an'eably)
TCP uses a cumulative acknowled'ment mec&anism) 6it& t&is mec&anism* a
TCP recei1er always acknowled'es to t&e sender wit& t&e &i'&est seDuence
number u to w&ic& all ackets &a1e been success/ully recei1ed) Cor eAamle* in
Ci') #)2* acket 3 is lost) T&ere/ore* t&e TCP recei1er returns 4CK /or acket 2
?42@ e1en w&en ackets :* 3* and 8 &a1e been recei1ed) T&ese 4CK ackets ?e)')*
42@* w&ic& acknowled'e t&e same TCP acket ?e)')* acket 2@* are re/erred to as
t&e duplicated acknowledgment packets) Crom Ci') #)2* t&e TCP sender does not
recei1e an 4CK acket w&ic& acknowled'es acket 3) 4/ter a eriod o/ (TO* t&e
sender will assume t&at acket 3 is lost and will retransmit acket 3)
T&e (TO 1alue is otimiJed accordin' to t&e /ollowin' tradeo//< a small (TO
1alue leads to unnecessary acket retransmission* w&ile a lar'e (TO 1alue results
in &i'& latency o/ acket loss detection) In 'eneral* an (TO 1alue s&ould be a
/unction o/ network (ound9Tri Time ?(TT@* w&ic& is t&e time reDuired /or a data
bit to tra1el /rom a source node to a destination node and tra1el back to t&e
source node) .ue to network dynamics* (TT o/ one acket could be di//erent
/rom t&at o/ anot&er) In TCP* smoot&ed ?i)e)* a1era'e@ (TT ?t @ and (TT 1ariation
?
t
@ are comuted based on t&e collected (TT samles* and are used to comute
t&e (TO 1alue)
4ccordin' to M23N* instantaneous smoot&ed (TT* (TT 1ariation* and instanta9
neous (TO are comuted as /ollows) !et t )k$ be t&e kt& (TT samle collected
uon 4CK recetion) 4lso* let t )k$*
t
)k$* and (TO)k$ be t&e 1alues o/ t *
t
*
and
#)1 0.P and TCP +asics 213
w)t $
w&ere ub and l b are /iAed uer and lower bounds on t&e (TO 1alue)
1
T&e
constants
X 2 ),O 1$ and Y 2 ),O 1$ are usually set to 2$" and 3$:* resecti1ely) T&e 1ariable
is a 'inary e%ponential 'ackoff ?+E+@ /actor) It is initialiJed to 1 and doubled
/or e1ery timeout e1ent* and is reset to 1 w&en a new 4CK acket arri1es)
8=%=2=2 Winow.Base $ongestion $ontro#
4 transort layer rotocol is also resonsible /or network con'estion) It limits t&e
transmission rate o/ a data /low to &el control network con'estion) 4s a window9
based con'estion control rotocol* TCP limits t&e transmission rate by adBustin'
t&e congestion window ?i)e)* transmission window@ w&ic& basically re/ers to t&e
amount o/ data t&at a sender can transmit wit&out waitin' /or acknowled'ment)
Cor eAamle* t&e con'estion window siJe o/ t&e TCP connection in Ci') #)2 is
initialiJed to :) T&ere/ore* t&e TCP sender auses a/ter sendin' ackets 1H:) 4/ter
recei1in' 4CK corresondin' to acket 1 ?i)e)* 41@* t&e number o/
unacknowled'ed ackets becomes 3 and TCP is able to send out acket 3)
Con'estion window o/ transmission window re/ers to a ran'e o/ seDuence
numbers o/ TCP ackets w&ic& can be transmitted at a moment) Cor eAamle* t&e
con'estion window at t&e be'innin' o/ Ci') #)2 is /1O 2O 3O :' and t&e con'estion
window siJe is :) 6&en 41 is recei1ed* t&e con'estion window becomes /2O 3O :O
3') In t&is case* we say t&at t&e con'estion window slides to t&e ri'&t) Suose
t&at t&e con'estion window c&an'es to /2O 3O :O 3O 8' ?t&e siJe is 3@) In t&is
case* we say t&at t&e con'estion window is opened by one unit) On t&e contrary*
i/ t&e window becomes /2O 3O :'* we say t&e con'estion window is closed by
one unit) 4'ain* a lar'er window siJe allows t&e sender to transmit more data in a
'i1en inter1al imlyin' a &i'&er transmission rate at t&e transort layer) TCP
increases and decreases its transmission rate by oenin' and closin' its con'estion
window)
6indow Increasin' %ec&anism
One o/ t&e key /eatures o/ TCP is network9based rate adatability) TCP slowly
oens its con'estion window to /ill u t&e underlyin' network* w&en t&e network
is underutiliJed) 6&en t&e network is o1erutiliJed* TCP raidly closes t&e
con'estion window to &el relie1e t&e con'estion) TCP window oenin'
mec&anism consists o/ two &ases* eac& o/ w&ic& is identi/ied by t&e current
con'estion window siJe ?w@ and a slow)start t&res&old ?w
t&
@<
1) Slow)start phase> I/ w Z w
t&
* TCP increases w by one /or e1ery recei1ed 4CK
acket)
2) Congestion avoidance phase> I/ w w
t&
* TCP increases w by
1
/or e1ery
recei1ed 4CK acket)
1
(CC 2#"" recommends ub to be at least 8, s* and l b to be 1 s M23N)
212 # Transort Control Protocols Part 1< 4n O1er1iew < < <
Note t&at* TCP recei1er may ad1ertise its maAimum window siJe ?w
maA
@ w&ic&
does not /ill its bu//er too raidly) T&is w
maA
acts as an uer9bound /or t&e abo1e
window increasin' mec&anism) In NS2* con'estion window ?w@ e1ol1es accordin'
to t&e abo1e two &ases* re'ardless o/ w
maA
) Howe1er* TCP uses t&e minimum o/
W and w
maA
to determine t&e amount o/ data it can transmit)
Packet !oss .etection %ec&anism
In t&e literature* 1arious TCP 1ariants use di//erent combinations o/ t&e /ollowin'
acket loss detection mec&anisms<
Timeout< 4s discussed earlier* TCP starts its retransmission timer /or e1ery
transmitted acket* and assumes a acket loss uon timer eAiration)
&ast #etransmit< +y de/ault* an (TO &as 'ranularity o/ ,)3 s* w&ic& could lead
to lar'e latency in acket loss detection) Cast retransmit eAedites t&e acket
loss detection by means o/ dulicated acknowled'ment detection) 0on
detection o/ t&e kt& ?w&ic& is eDual to 3 by de/ault@ dulicated
acknowled'ment ?eAcludin' t&e /irst one w&ic& is a new acknowled'ment@*
t&e TCP sender stos waitin' /or t&e timeout* assumes a acket loss* and
retransmits t&e lost acket) Crom Ci') #)2* i/ t&e /ast retransmit mec&anism is
used* t&e TCP sender will assume t&at acket 3 is lost and it retransmits
acket 3 uon recei1in' t&e :t& 42 acket ?i)e)* t&e t&ird dulicated
acknowled'ment@) Note t&at based on t&e cumulati1e acknowled'ment
rincile* uon recei1in' t&e retransmitted acket
3* TCP recei1er sends 48 back to t&e sender* since ackets :* 3* and 8 &a1e
been success/ully recei1ed earlier)
6indow .ecreasin' %ec&anism
Ori'inally concei1ed to combat con'estion in a wired network* TCP assumes t&at
all acket losses occur due to con'estion ?i)e)* bu//er o1er/low at t&e routers in t&e
network@) It reacts to e1ery acket loss by reducin' its transmission rate ?or
window siJe@ to lessen t&e con'estion) T&e /ollowin' aroac&es are amon' t&e
most oular window decreasin' mec&anisms /or a TCP 1ariant used in t&e
literature)
#eset to < Con1entionally* TCP reacts to acket loss by resettin' t&e window
siJe to 1* and settin' t&e slow9start t&res&old to &al/ o/ t&e current con'estion
window siJe) Howe1er* t&is otion is usually deemed too radical and could lead
to TCP t&rou'&ut de'radation in t&e resence o/ random acket loss)
&ast #ecovery< 0on detection o/ a acket loss* t&e /ast reco1ery mec&anism
sets bot& current window siJe and slow9start t&res&old to &al/ o/ t&e current
con'estion window siJe) T&en* it increases t&e window siJe by one /or eac&
dulicated acknowled'ment recei1ed durin' t&e /ast retransmit &ase) 4t t&is
moment* t&e sender may transmit a new acket i/ t&e con'estion window
allows)
#)2 +asic 4'ents 213
Tab#e 8=% .i//erences
amon' basic TCP 1ariants<
di//erent window closin'
mec&anisms uon detection
o/ a acket loss
TCP 1ariant !oss detection
T i m eout C ast re t rans m i t
Old9Ta&oe (eset w to 1 N$4
Ta&oe (eset w to 1 (eset w to 1
(eno (eset w to 1 Cast reco1ery ?sin'le acket@
New (eno (eset w to 1 Cast reco1ery ?all ackets@
0on recei1in' a new acknowled'ment* t&e sender eAits Cast (eco1ery and sets
t&e window siJe to t&e slow9start t&res&old 1alue* a/ter w&ic& TCP oerates
normally in a con'estion a1oidance &ase)
8=%=2=* T$P >ariants
T&ere are numerous TCP 1ariants in t&e literature) T&is section discusses only de
/acto TCP 1ariants namely Old Ta&oe* Ta&oe* (eno* and new (eno) T&ese TCP
1ariants use t&e same window increasin' mec&anism ?i)e)* slow start and
con'estion a1oidance@) Howe1er* t&ey di//er in &ow t&ey detect a acket loss
and decrease t&e window siJe) Table #)1 s&ows t&e di//erences in window siJe
adBustment mec&anism* w&en acket loss is detected t&rou'& timeout and Cast
(etransmit ?i)e)* dulicated 4CKs@)
T&e 1ery /irst TCP 1ariant* Old9Ta&oe* detects acket loss t&rou'& timeout
only) 6&en acket loss is detected* it always resets con'estion window siJe to 1)
.e1eloed /rom Old9Ta&oe* TCP Ta&oe uses t&e Cast (etransmit mec&anism to
eAedite acket loss detection rat&er t&an waitin' /or t&e timeout) It always sets
t&e window siJe to 1 uon detection o/ a acket loss) +ot& TCP (eno and New9
(eno reset t&e window siJe to 1* w&en a acket loss is detected t&rou'& timeout)
Howe1er* t&ey will use Cast (eco1ery i/ acket loss is detected t&rou'& Cast
(etransmit) T&e di//erence between TCP (eno and TCP New9(eno is t&at TCP
(eno eAits t&e /ast reco1ery rocess as soon as t&e lost acket w&ic& tri''ered
Cast (etransmit is acknowled'ed) I/ t&ere are multile acket losses wit&in a
con'estion window* Cast (eco1ery could be in1oked /or se1eral times* and t&e
window siJe will decrease si'ni/icantly) To a1oid t&e multile window closures*
TCP New(eno stays in t&e Cast (eco1ery &ase until all ackets in t&e loss
window are acknowled'ed or until timeout occurs)
8=2 Basic Agents
4n a'ent is an NsObBect w&ic& is resonsible /or creatin' and destroyin' ackets)
T&ere are two main tyes o/ NS2 a'ents< routin' a'ents and transort9layer
a'ents) 4 routin' a'ent creates* transmits* and recei1es routin' control ackets*
and commands routin' rotocols to act accordin'ly) Connectin' an alication to a
low9
P r ogram 8=% Cl a s s A$entClass w&ic& binds O Tcl and C CC cla s s A$ent
MMUMnsMcommonMa$entIcc
2 static class A$entClass 9 p!blic TclClass 7
1 p!blic9
3 A$entClass&' 9 TclClass&HA$entH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, A$ent&PT5NT[PE'';
A 8
B 8 class5a$ent;
le1el network* a transort9layer a'ent controls t&e con'estion and reliability o/ a
data /low based on an underlyin' transort layer rotocol ?e)')* 0.P or TCP@)
T&is book /ocuses on transort layer a'ents only)
NS2 imlements a'ents in a CCC class A$ent* w&ic& is bound to an OTcl
class wit& t&e same name ?see Pro'ram #)1@) In t&e /ollowin'* we /irst discuss
t&e relations&i amon' a transort9layer a'ent* an alication* and a low9le1el
network in Sect) #)2)1) 4'ent con/i'uration and internal mec&anisms are discussed
in Sects) #)2)2 and #)2)3* resecti1ely) Cinally* Sect) #)2): ro1ides 'uidelines to
de/ine a new transort9layer a'ent)
@.2.1 ApplicationsA AgentsA and a Lo&(Le#el %et&or'
4n a'ent acts as a brid'e w&ic& connects an alication and a low9le1el network)
+ased on t&e user demand ro1ided by an alication* a sendin' a'ent constructs
ackets and transmits t&em to a recei1in' a'ent t&rou'& a low9le1el network)
Ci'ure #)3 s&ows an eAamle o/ suc& a connection)
Consider Ci') #)3) On t&e to le1el* a constant bit rate C+( alication* w&ic&
models a user demand to eriodically transmit data* is used as an alication) T&e
demand is assed to a 0.P sendin' a'ent* w&ic& in turn creates 0.P ackets)
Here* t&e 0.P a'ent stores source and destination IP addresses and transort layer
orts in t&e acket &eader* and /orwards t&e acket to t&e attac&ed node ?e)')*
Node 1 in Ci') #)3@) 0sin' t&e recalculated routin' table* t&e low9le1el network
deli1ers t&e acket to t&e destination node ?e)')* Node 3 in Ci') #)3@ seci/ied in
t&e acket &eader) T&e destination node uses its demultileAer to /orward t&e
acket to t&e a'ent attac&ed to t&e ort seci/ied in t&e acket &eader) Cinally* a
Null recei1in' a'ent simly destroys t&e recei1ed acket)
Crom t&e abo1e discussion* an a'ent can be used as a sendin' a'ent ?e)')*
a 0.P a'ent@ or a recei1in' a'ent ?e)')* a Null a'ent@) 4 sendin' a'ent &as
connections to bot& an alication and a low9le1el network* w&ile a recei1in'
a'ent may not &a1e a connection to an alication ?because it does not need
any@) 4n alication ?e)')* C+(@ uses its 1ariable Fa$ent5G as a re/erence to an
a'ent ?e)')* 0.P and Null a'ents@* w&ile an a'ent uses its 1ariable Fapp5G as a
re/erence to an alication) It is mandatory to con/i'ure t&e 1ariables Fa$ent5G
and
#)2 +asic 4'ents 212
,

)
e
t
>
o
r
1

o
f

)
s
*
b
7
e
c
t
s
0-=
a4entC
attach$a4ent
Application*
?ser demand indication
?DP ,4ent
(Sendin4)
a66C
tar4etC
connect
)ull ,4ent
(=ecei(in4)
! a66C
tar4etC
A%ents* Pac1et
construction and
destruction
attach$a4ent
)ode 1
attach$a4ent
)ode 3
Lo'+Le,el Net'ork*
Pac1et for>ardin4
dmuxC
classifierC
dmuxC
classifierC
Lin1 2
Lin1 1
Lo'+Le,el
Net'ork
Lin1 3
)ode 2
4ig= 8=* 4 C+( alication o1er 0.P con/i'uration
Fapp5G ?i)e)* create t&e connection@ /or a sendin' a'ent* w&ile it is otional /or a
recei1in' a'ent) T&is is mainly because t&e alication needs to in/orm t&e a'ent
o/ user demand ?i)e)* by in1okin' /unction sendms$&III'@* and t&e sendin'
a'ent needs to in/orm t&e alication o/ t&e comletion o/ data transmission ?i)e)*
by in1okin' /unction res!me&'@) Since a recei1in' a'ent simly destroys t&e
recei1ed acket* it does not need a connection to an alication)
+ot& sendin' and recei1in' a'ents connect to a low9le1el network in t&e same
manner) T&ey use a ointer Ftar$et5*G to oint to t&e attac&ed node) T&e
Node* on t&e ot&er &and* installs t&e a'ent in t&e slot number FportG o/ its
demultileAer Fdm!*5G ?w&ic& is o/ class PortClassi"ier@* w&ere FportG
is t&e corresondin' ort number o/ t&e a'ent ?see Sect) 8)3)3@)
Table #)2 s&ows t&e key di//erences between a sendin' a'ent and a recei1in'
a'ent) T&e ustream obBect o/ a sendin' a'ent is an alication* w&ic& in/orms
a sendin' a'ent o/ incomin' user demand t&rou'& /unction sendms$&III'
o/ t&e sendin' a'ent) T&e ustream obBect o/ a recei1in' a'ent* on t&e ot&er
&and* is a Node obBect* w&ic& /orwards ackets to t&e recei1in' a'ent 1ia
/unction recv&p)(') T&e downstream obBect o/ a sendin' a'ent is a Node
obBect) T&e sendin' a'ent asses a acket
N
p to a Node obBect by
eAecutin' tar$et5JKrecv&p)(') 4 recei1in' a'ent usually &as no
downstream obBect* since it simly destroys t&e recei1ed ackets)
Tab#e 8=2 Key
di//erences between a
sendin' and a recei1in'
a'ent
0stream
Sendin' a'ent (ecei1in' a'ent
H ObBect Application Node
H Packet /orwardin' /unction sendms$ recv
.ownstream obBect
H ObBect Node N$4
H Packet /orwardin' /unction recv N$4
@.2.2 Agent Config!ration
Crom Ci') #)3 and Pro'ram #)2* a'ent con/i'uration consists o/ /our main
stes<
1) Create a sendin' a'ent* a recei1in' a'ent* and an alication usin'
Fne,/III'G ?!ines "H1,@)
2) 4ttac& a'ents to t&e alication usin' OTcl Command attac(Ja$ent9
/a$ent' o/ class Application ?!ine 11@)
3) 4ttac& a'ents to t&e a low9le1el network usin' instroc attac(Ja$ent9
/node a$ent' o/ class Sim!lator ?!ines 12 and 13@)
:) 4ssociate t&e sendin' a'ent wit& t&e recei1in' a'ent usin' instroc connect
/src dst' o/ class Sim!lator ?!ine 1:@)
T&e details o/ t&ese /our stes will be discussed in 'reater detail in Sect) 11)1)
E%ample ;* -+ Network Construction E%ample0* T&e eAamle network in
Ci') #)3 uses C+(* a 0.P a'ent* and a Null a'ent as an alication* a sendin'
a'ent* and a recei1in' a'ent* resecti1ely) To setu t&e eAamle network* we may
use t&e Tcl simulation scrit in Pro'ram #)2)
Program 8=2 4 simulation scrit w&ic& creates t&e network in Ci') #)3
2 set ns ?ne, Sim!lator@
1 set n2 ?Pns node@
3 set n1 ?Pns node@
= set n3 ?Pns node@
> Pns d!ple*Jlink Pn2 Pn1 >%b 1ms DropTail
A Pns d!ple*Jlink Pn1 Pn3 >%b 1ms DropTail
B Pns d!ple*Jlink Pn2 Pn3 >%b 1ms DropTail
O::: DDPJN!ll peerin$ starts (ere :::
/ set !dp ?ne, A$entMDDP@
G set n!ll ?ne, A$entMN!ll@
20 set cbr ?ne, ApplicationMTra""icMC.#@
22 Pcbr attac(Ja$ent P!dp
21 Pns attac(Ja$ent Pn2 P!dp
23 Pns attac(Ja$ent Pn3 Pn!ll
2= Pns connect P!dp Pn!ll
#)2 +asic 4'ents 21#
6&ile !ines 1H2 create a low9le1el network ?see t&e details in C&as) 8 and 2@*
!ines "H1: set u a C+( alication* a 0.P a'ent* and a Null a'ent on to o/ t&e
low9le1el network)
@.2." Internal Mechanis for Agents
T&e internal mec&anisms /or a'ents are de/ined in t&e CCC domain as
/ollows<
+ sending agent< (ecei1e user demand by &a1in' t&e associated alication
in1oke its /unction sendms$&III') Crom wit&in sendms$&III'* create
ackets usin' /unction allocpkt&' and /orward t&e created ackets to t&e
low9le1el network by eAecutin' tar$et5JKrecv&p)(')
+ receiving agent< (ecei1e ackets by &a1in' a low9le1el network
demultileAer in1oke its /unction recv&p)(') .estroy recei1ed ackets by
in1okin' /unction "ree&p' o/ class Packet)
In t&is section* we will discuss t&e detail o/ 1ariables and /unctions reDuired to
er/orm t&e abo1e mec&anisms)
8=2=*=% Re#ate $CC an ,Tc# >ariab#es
T&e main 1ariables o/ CCC class A$ent and t&eir bound OTcl inst1ars are
s&own in Table #)3) O/ tye ns5addr5t ?see Sect) ")3)3@* 1ariables F(ere5G
and Fdst5G contain addresses and orts o/ t&e Node attac&ed to t&e sendin' a'ent
and t&e recei1in' a'ent* resecti1ely) 4n IP18 riority le1el is stored in t&e
1ariable Fprio5)G 7ariable Fapp5G acts as a re/erence to an Application
obBect) Since class A$ent is resonsible /or acket 'eneration* it must assi'n a
uniDue I. to e1ery acket) T&ere/ore* it maintains a static 1ariable F!idcnt5*G
w&ic& counts t&e total number o/ 'enerated ackets) 6&en a acket is created* an
A$ent obBect sets t&e uniDue I. o/ t&e acket to be F!idcnt5*G and increases
F!idcnt5G by one ?see /unction initpkt&p' in !ine 1, o/ Pro'ram #)3@)
8=2=*=2 Dey $CC 4unctions
4 list o/ key CCC /unctions wit& t&eir descritions is 'i1en below ?see t&e
declaration o/ class A$ent in /ile Tns$common$a'ent)cc*&@) Since class A$ent
is a temlate /or transort layer a'ents* it ro1ides no imlementation /or some o/
its
int
int
"id5
prio5
"id5
prio5
Clow I.
IP18 riority /ield?e)')* , .
unseci/ied* 1 . back9
'round tra//ic@
int "la$s5 "la$s5 Cla's
int de"ttl5 ttl5 .e/ault time to li1e 1alue
int si6e5 N$4 Packet siJe
packet5t type5 N$4 Payload tye
int se+no5 N$4 Current seDuence number
Application
N
app5 N$4 4 ointer to an alication
int !idcnt5 N$4 Total number o/ ackets 'en9
erated by all a'ents
21" # Transort Control Protocols Part 1< 4n O1er1iew < < <
Ta b # e 8 = * T & e li s t o / C CC and O Tcl 1 ar i ab l es o/ c l ass A$ent
C CC t ye C CC 1 ar i ab le O T c l i ns t 1 a r . escr i ti o n
ns5addr5t (ere5
(ere5Iaddr5 a$ent5addr5 4ddress o/ t&e attac&ed node
(ere5Iport5 a$ent5port5 Port w&ere t&e sendin' a'ent
is attac&ed
ns5addr5t dst5
dst5Iaddr5 dst5addr5 4ddress o/ t&e attac&ed node
attac&in' to a eerin'
a'ent
dst5Iport5 dst5port5 Port w&ere t&e recei1in'
a'ent is attac&ed
/unctions) T&e c&ild classes o/ class A$ent are resonsible /or imlementin'
t&ese /unctions)
recv&p)(' (ecei1e a acket
N
p
send&p)(' Send a acket
N
p
send&nbytes' Send a messa'e wit& nbytes bytes
sendms$&nbytes' Send a messa'e wit& nbytes bytes
timeo!t&tno' 4ction to be er/ormed at timeout
connect&dst' Connect to a dynamic destination dst
close&' Close a connection9oriented session
listen&' 6ait /or a connection9oriented session
attac(App&app' Store app in t&e 1ariable app5
allocpkt&' Create a acket
initpkt&p' InitialiJe t&e inut acket
N
p
recv.ytes&bytes' Send data o/ bytes bytes to t&e attac&ed alication
idle&' Tell t&e alication t&at t&e a'ent &as not&in' to
transmit
#)2 +asic 4'ents 221
Program 8=* Constructor* /unction allocpkt* and /unction initpkt o/ class
A$ent
MMUMnsMcommonMa$entIcc
2 A$ent99A$ent&packet5t pkttype'9si6e5&0')type5&pkttype')
app5&0'78
1 Packet
N
A$ent99allocpkt&' const
3 7
= Packet
N
p : Packet99alloc&';
> initpkt&p';
A ret!rn &p';
8
B void A$ent99initpkt&Packet
N
p'
7
/ (dr5cmn
N
c( : (dr5cmn99access&p';
G c(JK!id&' : !idcnt544;
20 c(JKptype&' : type5;
22 III
21 (dr5ip
N
ip( : (dr5ip99access&p';
23 ip(JKsaddr&' : (ere5Iaddr5;
2= ip(JKsport&' : (ere5Iport5;
2> ip(JKdaddr&' : dst5Iaddr5;
2A ip(JKdport&' : dst5Iport5;
2B III
2/ 8
The $onstructor
Class A$ent &as no de/ault constructor) Its only constructor takes a packet5t
?see Sect) ")3): and Pro'ram ")#@ obBect as an inut ar'ument ?see !ine 1 o/
Pro'ram #)3@) T&e constructor sets t&e 1ariable Ftype5G to be as seci/ied in t&e
inut ar'ument and resets ot&er 1ariables to Jero) T&is ayload tye settin'
imlies t&at one a'ent is able to transmit ackets o/ one tye only) 6e need
se1eral a'ents to transmit ackets o/ se1eral tyes)
4unctions alloc%kt)* an
init%kt)%*
S&own in Pro'ram #)3* /unction allocpkt&' is t&e main acket construction
/unction) It creates a acket by in1okin' /unction alloc&' o/ class Packet
in !ine :* and initialiJes t&e acket by in1okin' /unction initpkt&p' in !ine
3) 4/ter initialiJation* /unction allocpkt&' returns a ointer to t&e
constructed acket FpG to t&e caller)
T&e details o/ /unction initpkt&p' are s&own in !ines "H1" o/ Pro'ram
#)3) Cunction initpkt&p' sets t&e initial 1alues in t&e acket &eader o/ t&e
inut acket F
N
pG to t&e de/ault 1alues) T&e uniDueness o/ t&e uniDue I. /ield
F!id5G in t&e common &eader is assured by settin' F!id5G to be t&e total
number o/ ackets
22, # Transort Control Protocols Part 1< 4n O1er1iew < < <
Program 8=/ Cunctions attac(App and recv o/ class A$ent
MMUMnsMcommonMa$entIcc
2 void A$ent99attac(App&Application
N
app'
1 7
3 app5 : app;
= 8
> void A$ent99recv&Packet
N
p) Handler
N
'
A 7
B i" &app5'
/ app5JKrecv&(dr5cmn99access&p'JKsi6e&'';
G Packet99"ree&p';
20 8
allocated so /ar) Class A$ent stores t&e total number o/ allocated ackets in its
static 1ariable F!idcnt5)G Since t&e 1ariable F!idcnt5G is distinct and uniDue
to all a'ents* assi'nin' t&is 1ariable to t&e /ield F!id5G o/ t&e common &eader
?!ine #@ assures t&e uniDueness o/ acket uniDue I.)
Ot&er initialiJation includes settin' u t&e ayload tye in t&e common &eader
to be as seci/ied in t&e 1ariable Ftype5G ?!ine 1,@) 4lso* !ines 12H18 con/i'ure
source and destination IP addresses and ort numbers in t&e 1ariables F(ere5G
and Fdst5)G
4unction attachA%%)a%%*
!ines 1H: in Pro'ram #): s&ow t&e details o/ /unction attac(App&app') To
bind an alication to an a'ent* /unction attac(App&app' stores t&e inut
ointer FappG in its ointer to a Application obBect* Fapp5)G 4/ter t&is
oint* t&e a'ent may in1oke p!blic /unctions o/ t&e attac&ed alication
t&rou'& t&e ointer Fapp5)G
4unctions recv)%+h*3 send)%+h*3 an sendmsg)nb$tes*
T&ese /unctions are used by sendin' and recei1in' a'ents in t&e acket /orwardin'
rocess) On t&e sender side* an alication in/orms a sendin' a'ent o/ user demand
by in1okin' /unctions send&nbytes'* and sendms$&III' o/ class A$ent)
4s an NsObBect* t&e sendin' a'ent /orwards an incomin' acket
N
p to a
downstream NsObBect by eAecutin' tar$et5JKrecv&p)(') Cunctions
send&nbytes' and sendms$&III' &a1e no imlementation in t&e scoe
o/ class A$ent* and must be imlemented by t&e c&ild classes o/ class A$ent)
On t&e recei1er side* an NsObBect /orwards ackets to a recei1in' a'ent by
in1okin' its /unction recv&p)(') S&own in !ines 3H1, o/ Pro'ram #):* /unction
recv&p)(' deallocates t&e recei1ed acket ?!ine #@ and may in/orm t&e
attac&ed
#)3 0.P and Null 4'ents 223
alication ?i/ it eAists@ o/ acket recetion by in1okin' /unction recv&si6e'
o/ t&e attac&ed Application obBect ?!ines 2 and "@* w&ere si6e is t&e siJe
o/ acket
N
p)
@.2.$ ,!idelines to )efine a %e& Transport Layer
Agent
Class A$ent ro1ides t&e basic /unctionalities necessary /or most a'ents) 4
new a'ent can be created based on t&ese /unctionalities* /ollowin' t&e 'uidelines
below<
1) .e/ine an in&eritance structure< Select a base class and deri1e a new a'ent class
/rom t&e selected base class) +ind t&e CCC and OTcl a'ent class names
to'et&er)
2) .e/ine necessary CCC 1ariables and OTcl
inst1ars)
3) Imlement t&e constructors o/ bot& CCC and OTcl classes) +ind t&e 1ariables
and t&e inst1ars i/ necessary) Ceed ayload tye ?i)e)* packet5t@ as an inut
ar'ument o/ t&e CCC constructor)
:) Imlement t&e necessary /unctions includin' /unctions send&nbyte'*
sendms$&III'* recv&p)('* and timeo!t&tno') 4lso de/ine OTcl inst9
rocs i/ necessary)
3) .e/ine necessary OTcl commands as inter/aces to t&e CCC domain /rom t&e
OTcl domain)
8) MOtionalN .e/ine a timer ?see Sect)
13)1@)
8=* 9-P an Nu## Agents
0.P is a connectionless transort layer rotocol* w&ic& ro1ides neit&er
con'estion control nor error control) In NS2* a 0.P a'ent is used as a
sendin' a'ent) It is usually eered wit& a Null ?recei1in'@ a'ent* w&ic& is
resonsible /or acket destruction) Ci'ure #)3 s&ows a network con/i'uration
eAamle w&ere a Constant +it (ate ?C+(@ tra//ic source uses a 0.P a'ent and a
Null a'ent as its transort later a'ents) Here* t&e C+( asks t&e 0.P a'ent to
transmit a burst o/ ackets /or e1ery /iAed inter1al) T&e 0.P a'ent creates and
/orwards ackets to t&e low9le1el network* irresecti1e o/ t&e network condition)
On t&e recei1in' end* t&e Null a'ent simly destroys t&e ackets recei1ed /rom t&e
low9le1el network) In t&e /ollowin'* we will discuss t&e details o/ 0.P and Null
a'ents)
@.".1 %!ll BRecei#ingC Agents
4 Null a'ent is t&e simlest but one o/ t&e most widely used recei1in' a'ents)
222 # Transort Control Protocols Part 1< 4n O1er1iew < < <
T&e main resonsibility o/ a Null a'ent is to deallocate ackets t&rou'& /unction
#)3 0.P and Null 4'ents 223
Program 8=0 %ain' class DdpA$entClass w&ic& binds a CCC class
DdpA$ent to an OTcl class A$entMDDP
MMUMnsMappsM!dpIcc
2 static class DdpA$entClass 9 p!blic TclClass 7
1 p!blic9
3 DdpA$entClass&' 9 TclClass&HA$entMDDPH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, DdpA$ent&'';
A 8
B 8 class5!dp5a$ent;
"ree&p' o/ class Packet ?see !ine # in Pro'ram #):@) 4 Null a'ent is
reresented by an OTcl class A$entMN!ll w&ic& is deri1ed directly /rom an
OTcl class A$ent ?see /ile Tns$tcl$lib$ns9a'ent)tcl@) .ue to its simlicity* Null
a'ents &a1e no imlementation in t&e CCC domain)
@.".2 0)P BSendingC Agent
4 0.P a'ent is er&as t&e simlest /orm o/ sendin' a'ents) It recei1es user
demand to transmit data by &a1in' t&e attac&ed alication in1oke its /unction
?e)')* sendms$&III'@* creates ackets based on t&e demand* and /orwards t&e
created acket to a low9le1el network) 4n alication may use t&e t&ree /ollowin'
ways to tell a 0.P a'ent to send out ackets< 1ia a CCC /unction
sendms$&III' o/ class DdpA$ent* 1ia an OTcl command send/III' o/
OTcl class A$entMDDP* or 1ia an OTcl command sendms$/III' o/ OTcl class
A$entMDDP)
4'ain* NS2 de/ines a 0.P sendin' a'ent based on t&e 'uideline in Sect) #)2):)
Since a 0.P a'ent imlements no acknowled'ment mec&anism and needs no
timer* we can ski t&e last ste in t&e 'uideline)
Ste& %2 -efine 'nheritance Structure
4 0.P a'ent is reresented by a CCC class DdpA$ent and an OTcl class
A$entMDDP) T&ese two classes deri1e /rom class A$ent in t&eir domains* and
are bound usin' a main' class DdpA$entClass ?see Pro'ram #)3@)
Ste& 22 -efine $CC >ariab#es an ,Tc#
'nstvars
T&e key 1ariable o/ class DdpA$ent is Fse+no5G ?!ine 12 in Pro'ram #)8@*
w&ic& counts t&e number o/ ackets 'enerated by a DdpA$ent obBect) Note
t&at e1ery
22: # Transort Control Protocols Part 1< 4n O1er1iew < < <
Program 8=6 .eclaration and t&e constructors o/ class DdpA$ent as well as t&e
de/ault 1alue o/ t&e inst1ar packetSi6e o/ class A$entMDDP
MMUMnsMappsM!dpI(
2 class DdpA$ent 9 p!blic A$ent 7
1 p!blic9
3 DdpA$ent&';
= DdpA$ent&packet5t';
> virt!al void sendms$&int nbytes) const c(ar
N
"la$s : 0'7
A sendms$&nbytes) NDLL) "la$s';
B 8
/ virt!al void sendms$&int nbytes) AppData
N
data) III
const c(ar
N
"la$s : 0';
G virt!al void recv&Packet
N
pkt) Handler
N
';
20 virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
22 protected9
21 int se+no5;
23 8;
MMUMnsMappsM!dpIcc
2= DdpA$ent99DdpA$ent&' 9 A$ent&PT5DDP') se+no5&J2'7
2> bind&HpacketSi6e5H) Fsi6e5';
2A 8
2B DdpA$ent99DdpA$ent&packet5t type' 9 A$ent&type'7
2/ bind&HpacketSi6e5H) Fsi6e5';
2G 8
MMUMnsMtclMlibMnsJde"a!ltItcl
10 A$entMDDP set packetSi6e5 2000
acket &as a uniDue I. F!id5)G 4lso* e1ery acket 'enerated by t&e same agent
&as a uniDue seDuence number Fse+no5)G Howe1er* two ackets 'enerated by
di//erent a'ents may &a1e t&e same seDuence number Fse+no5G but t&ey must
&a1e di//erent uniDue I. F!id5)G
Ste& *2 'm&#ement the $onstructors in the $CC an ,Tc# -omains
NS2 imlements constructor /or 0.P a'ents in t&e CCC domain only) Crom
Pro'ram #)8* t&e de/ault constructor in !ines 1:H18 /eeds 0.P ayload tye ?i)e)*
PT5DDP@ to t&e constructor o/ class A$ent* essentially storin' PT5DDP in t&e
1ariable type ) It also sets t&e seDuence number ?i)e)* se+no @ to be 1) +y
seci9 /yin' t&e ayload tye* t&e constructor in !ines 12H1# sets t&e ayload tye
to be as seci/ied in t&e inut ar'ument) T&e constructor in t&is case does not set
t&e 1alue o/ Fse+no5G since t&e ackets o/ seci/ied tye may not &a1e
seDuence number) Cor bot& constructors* t&e CCC 1ariable Fsi6e5*G w&ic&
seci/ies t&e acket siJe*
#)3 0.P and Null 4'ents 223
Program 8=5 Cunction sendms$ o/ class DdpA$ent and /unction idle o/
class
A$ent
MMUMnsMappsM!dpIcc
2 void DdpA$ent99sendms$&int nbytes)AppData
N
data)const c(ar
N
"la$s'
1 7
3 Packet
N
p;
= int n : nbytes M si6e5;
> ,(ile &nJJ K 0' 7
A p : allocpkt&';
B M
N
packet (eader con"i$!ration
N
M
/ (dr5cmn99access&p'JKsi6e&' : si6e5;
G III
20 M
N
JJJJJJJJJJJJJJJJJJJJJJJJJJJ
N
M
22 tar$et5JKrecv&p';
21 8
23 n : nbytes E si6e5;
2= i" &n K 0' 7
2> p : allocpkt&';
2A M
N
packet (eader con"i$!ration
N
M
2B (dr5cmn99access&p'JKsi6e&' : n;
2/ III
2G M
N
JJJJJJJJJJJJJJJJJJJJJJJJJJJ
N
M
10 tar$et5JKrecv&p';
12 8
11 idle&';
13 8
MMUMnsMcommonMa$entIcc
1= void A$ent99idle&' 7 i" &app5' app5JKres!me&'; 8
1> 8
is bound to inst1ar packetSi6e5 in t&e OTcl domain ?!ines 13 and 1#@) +y
de/ault* t&e acket siJe is set to 1*,,, bytes in t&e /ile Tns$tcl$lib$ns9de/ault)tcl
?!ine 2,@)
Ste& /2 -efine the Necessary $CC 4unctions
4s a sendin' a'ent* a 0.P a'ent needs to de/ine a /unction sendms$&III'
to recei1e a user demand /rom t&e alication) Pro'ram #)2 s&ows t&e details
o/ /unction sendms$&nbytes)data)"la$s'* w&ic& takes t&ree inut ar'u9
ments< Fnbytes*G Fdata*G and F"la$s)G Cunction sendms$&III' di1ides
data ayload wit& siJe FnbytesG bytes into FnG ?see !ine :@ or Fn42G arts
?deendin' on FnbytesG@* stores eac& art into a 0.P acket ?w&ic& contains a
ayload o/ Fsi6e5G bytes@* and transmits all ?FnG or Fn42G@ ackets to t&e
attac&ed low9le1el network)
228 # Transort Control Protocols Part 1< 4n O1er1iew < < <
Program 8=7 OTcl Commands send and sendms$ o/ class A$entMDDP
MMUMnsMappsM!dpIcc
2 int DdpA$ent99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 i" &ar$c :: =' 7
= i" &strcmp&ar$v?2@) HsendH' :: 0' 7
> PacketData
N
data : ne, PacketData&2 4 strlen
&ar$v?3@'';
A strcpy&&c(ar
N
'dataJKdata&') ar$v?3@';
B sendms$&atoi&ar$v?1@') data';
/ ret!rn &TCL5OV';
G 8
20 8 else i" &ar$c :: >' 7
22 i" &strcmp&ar$v?2@) Hsendms$H' :: 0' 7
21 PacketData
N
data : ne, PacketData&2 4 strlen
&ar$v?3@'';
23 strcpy&&c(ar
N
'dataJKdata&') ar$v?3@';
2= sendms$&atoi&ar$v?1@') data) ar$v?=@';
2> ret!rn &TCL5OV';
2A 8
2B 8
2/ ret!rn &A$ent99command&ar$c) ar$v'';
2G 8
Since NS2 rarely sends actual ayload alon' wit& a acket* !ine " sets t&e
siJe o/ acket to be Fsi6e5)G !ine 11 sends out t&e created acket* by eAecutin'
tar$et5JKrecv&p')
2
!ines 8H11 are reeated FnG times to transmit all FnG
ackets)
4/ter transmittin' t&e /irst FnG ackets* t&e entire alication ayload is le/t
wit& nbytes E si6e5* w&ere E is t&e modulus oerator) I/ t&e remainder is
nonJero* !ines 13H2, will transmit t&e remainin' alication ayload in anot&er
acket) Cinally* !ine 22 in1okes /unction idle&' to in/orm t&e attac&ed
alication t&at t&e 0.P a'ent &as /inis&ed data transmission) Crom !ine 2:*
/unction idle&' does so by in1okin' /unction res!me&' o/ t&e attac&ed
alication ?i/ any@)
T&ere are two imortant notes /or 0.P a'ents) Cirst* since a 0.P a'ent is a
sendin' a'ent its /unction recv&p)(' is 'enerally not to be used) Second* in
Pro'ram #)2* /unction sendms$&III' transmits ackets* irresecti1e o/
network condition)
Ste& 02 -efine ,Tc# $ommans an 'nst&rocs
Class A$entMDDP de/ines t&e two /ollowin' OTcl commands de/ined in
Pro'ram #)"<
2
7ariable tar$et is con/i'ured to oint to a node entry durin' t&e network con/i'uration &ase
?see Sect) #)2)1@)
#): C&ater Summary 222
send/nbytes str'< Send a ayload o/ siJe FnbytesG containin' a messa'e
Fstr)G
sendms$/nbytes str "la$s'< Similar to t&e OTcl command send but
also asses t&e inut /la' F"la$sG w&en sendin' a acket)
!ines 3H" in Pro'ram #)" s&ow t&e details o/ t&e OTcl command send/III')
!ine 3 creates a PacketData obBect) !ine 8 stores t&e inut messa'e FstrG
in t&e created PacketData obBect) !ine 2 sends out t&e alication ayload by
in1okin' /unction sendms$&III') Note t&at t&e siJe o/ alication ayload does
not deend on t&e siJe o/ t&e messa'e in t&e PacketData obBect ?i)e)*
ar$v?3@ or FstrG@) (at&er* t&e siJe is seci/ied in t&e /irst inut ar'ument ?i)e)*
ar$v?1@ or FnbytesG@) T&e imlementation o/ t&e OTcl command
sendms$&III' is similar to t&at o/ t&e OTcl command send/III') Howe1er*
it also /eeds a /la' F"la$sG as an inut ar'ument o/ /unction sendms$&III'
?see !ine 1:@)
@."." Setting 0p a 0)P Connection
4 0.P connection can be created by t&e network con/i'uration met&od ro1ided
in Sect) #)2)2) 4n eAamle connection w&ere a 0.P a'ent* a Null a'ent* and a
C+( tra//ic source are used as a sendin' a'ent* a recei1in' a'ent* and an
alication is s&own in EAamle #)1)
8=/ $ha&ter Summary
4n a'ent is a connector w&ic& brid'es an alication to a low9le1el network) Its
main resonsibilities are to create ackets based on user demand recei1ed /rom
an alication* to /orward ackets to a low9le1el network* and to destroy ackets
recei1ed /rom a low9le1el network) Crom t&is oint o/ 1iew* an a'ent can be used
to model transort layer rotocols and routin' rotocols) T&is c&ater /ocuses on
transort layer ?rotocol@ a'ents only)
Class A$ent is a base class* w&ic& reresents bot& sendin' and recei1in'
a'ents) It connects to an alication and a low9le1el network usin' ointers
Fapp5G and Ftar$et5*G resecti1ely) 4n alication also &as a ointer
Fa$ent5G to t&e a'ent* w&ile a low9le1el network uses a ointer Ftar$et5G as
a re/erence to t&e a'ent) Class A$ent ro1ides basic /unctionalities /or
creatin'* /orwardin'* and destroyin' ackets) Its /unctions send&III' and
sendms$&III' are in1oked by an attac&ed alication to ass on user demand)
4n a'ent creates ackets based on t&e demand* and /orwards t&e created acket to
a low9le1el network by eAecutin' tar$et5JKrecv&p)(') 4 low le1el network
sends a acket to a recei1in' a'ent by in1okin' /unction recv&p)(' o/ t&e
recei1in' a'ent)
0.P and TCP are amon' t&e most widely used transort layer rotocols) 0.P
is a simle transort layer rotocol and it can be /leAibly used by ot&er network
22" # Transort Control Protocols Part 1< 4n O1er1iew < < <
rotocols) In NS2* 0.P is imlemented in t&e CCC class DdpA$ent w&ic& is
bound to an OTcl class A$entMDDP) 4 0.P a'ent is usually eered wit& a Null
a'ent* w&ic& simly destroys recei1ed ackets)
TCP is a reliable transort control rotocol) Its main /eatures are end9to9end
error control and network con'estion control) It imlements timeout and
acknowled'ment to ro1ide end9to9end error control and adots a window9based
rate adBustment to control network con'estion) 6e will discuss t&e details o/ TCP
imlementation in NS2 in t&e C&a) 1,)
8=0 "<ercises
1) 6&at is t&e de/ault TCP 1ersion used in NS2R How does it react to dulicate
acknowled'ments and timeoutR
2) Suose a series o/ ackets measures t&e /ollowin' set o/ round tri time
?(TT@<
#)2* 1,)1* 11)2* 13)2* ")"* 2)2* 12)2* and 13)" s) Suose /urt&er t&at a new
acket wit& round9tri time 13)1 s &as arri1ed) 0se M33N to comute smoot&ed
(TT* (TT 1ariation* and instantaneous retransmission timeout ?(TO@)
3) 6&at is t&e c&aracteristic uniDue to an 4'entR
:) 6&at are t&e NS2 obBects w&ic& are resonsible /or uttin' IP addresses and
orts in acketsR EAlain &ow t&ese obBects write t&e addresses and t&e ort
into t&e acket &eader)
3) 6&at are CCC and OTcl classes w&ic& model senders and recei1ers /or TCP
and 0.P acketsR
8) .esi'n a connection9oriented transort layer rotocol in NS2) T&is rotocol sets
u t&e connection in t&e same way as TCP does* but transmit data ackets in t&e
same way as 0.P does) Incororate t&e rotocol into NS2 and write a ro'ram
to test t&e de1eloed module)
2) 6&ere does NS2 store t&e /ollowin' in/ormation< t&e acket seDuence number*
t&e maAimum window siJe* t&e current con'estion windows* and /low I.R Li1e
you answer /or bot& TCP and 0.P ackets* w&ere1er alicable)
") How does NS2 ensure t&e uniDueness o/ acket uniDue
I.R
$ha&ter %:
Trans&ort $ontro# Protoco#s
Part 22 Transmission $ontro#
Protoco#
4s a transort control rotocol* Transmission Control Protocol ?TCP@ brid'es an
alication to a low9le1el network* controls network con'estion* and ro1ides
relia9 bility to an end9to9end connection) T&is c&ater discusses t&e details o/ TCP
a'ents) Section 1,)1 'i1es an o1er1iew o/ TCP a'ents) Here* we s&ow a TCP
network con/i'uration met&od* a brie/ o1er1iew o/ TCP internal mec&anism*
TCP &eader /ormat* and t&e main stes in de/inin' TCP senders and TCP
recei1ers) Sections 1,)2 and 1,)3 discuss t&e imlementation o/ TCP recei1ers
and senders* resecti1ely) Sections 1,):H1,)2 resent t&e imlementation o/ /our
main /unctionalities o/ a TCP sender) Cinally* t&e c&ater summary is ro1ided in
Sect) 1,)")
%:=% An ,verview of T$P Agents in NS2
+ased on user demand /rom an alication* a TCP sender creates and /orwards
ackets to a low9le1el network) It controls t&e con'estion by limitin' t&e rate
?i)e)* by adBustin' t&e con'estion window@ at w&ic& ackets are /ed to t&e low9
le1el network) It en/orces an acknowled'ment mec&anism to ro1ide connection
reliability) 4 TCP recei1er must acknowled'e e1ery recei1ed TCP acket) +ased
on t&e acknowled'ment attern* a TCP sender determines w&et&er t&e transmitted
acket was lost or not) I/ so* it will retransmit t&e acket) 4 TCP sender is
resonsible /or sendin' ackets as well as controllin' t&e transmission rate* w&ile
t&e role o/ a TCP recei1er is only to return acknowled'ments to t&e associated TCP
sender)
1D.1.1 Setting 0p a TCP Connection
4s a transort layer a'ent* TCP can be incororated into a network usin' t&e
met&od discussed in Sect) #)2)2)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2* .OI
1,)1,,2$#2"919:81:91:,893 1,* = Srin'er Science>+usiness %edia* !!C 2,12
22#
1,)1 4n O1er1iew o/ TCP 4'ents in NS2 231
E%ample 2** Consider Ci') #)3) (elace t&e C+( alication wit& Cile Trans/er
Protocol ?CTP@* t&e 0.P a'ent wit& a TCP sender* and t&e Null a'ent wit& a TCP
recei1er) T&e modi/ied network can be created usin' t&e /ollowin' Tcl simulation
scrit)
2 set ns ?ne, Sim!lator@
1 set n2 ?Pns node@
3 set n1 ?Pns node@
= set n3 ?Pns node@
> Pns d!ple*Jlink Pn2 Pn1 >%b 1ms DropTail
A Pns d!ple*Jlink Pn1 Pn3 >%b 1ms DropTail
B Pns d!ple*Jlink Pn2 Pn3 >%b 1ms DropTail
O::: TCP connection set!p starts (ere :::
/ set tcp ?ne, A$entMTCP@
G set sink ?ne, A$entMTCPSink@
20 set "tp ?ne, ApplicationMQTP@
22 Pns attac(Ja$ent Pn2 Ptcp
21 Pns attac(Ja$ent Pn3 Psink
23 P"tp attac(Ja$ent Ptcp
2= Pns connect Ptcp Psink
2> Pns at 0I0 HP"tp startH
Similar to t&ose in EAamle #)1* !ines "H1: abo1e create a TCP connection on to
o/ a low9le1el network)
1D.1.2 Pac'et Transission and Ac'no&ledgent
Mechanis
TCP ro1ides connection reliability by means o/ acknowled'ment and acket
retransmission) Ci'ure 1,)1 s&ows a dia'ram /or TCP acket transmission and
acknowled'ment mec&anisms) T&e rocess starts w&en an alication ?e)')* QTP@
in/orms a TCP sender ?e)')* TcpA$ent@ o/ user demand by in1okin' /unction
sendms$&nbytes' o/ t&e TcpA$ent obBect t&rou'& its 1ariable
Fa$ent5)G T&e TCP sender creates TCP ackets* and /orwards t&em to its
downstream obBect by eAecutin' tar$et5JKrecv&p)(') T&e low9le1el
network deli1ers t&e ackets to t&e destination node attac&ed to t&e TCP recei1er
?i)e)* TcpSink@) T&e destination node /orwards t&e acket to t&e TCP recei1er
?i)e)* a TcpSink obBect@ by in1okin' /unction recv&p)(' o/ t&e TCP recei1er
installed in its demultileAer ?e)')* Fdm!*5G@) 0on recei1in' a TCP acket* t&e
TCP recei1er creates an 4CK acket and returns it to t&e TCP sender by
eAecutin' tar$et5JKrecv&p)('* w&ere in t&is case p is a ointer to t&e
created 4CK acket) T&e low9le1el network deli1ers t&e 4CK acket to t&e
sendin' node* w&ic& /orwards t&e 4CK acket to t&e TCP sender 1ia its
demultileAer)
23, 1, Transort Control Protocols Part 2< Transmission Control Protocol
4ig= %:=% TCP acket transmission and acknowled'ment mec&anisms
I/ a TCP acket or an 4CK acket is lost ?or delayed /or a lon' eriod o/ time@*
t&e TCP sender will assume t&at t&e acket is lost) In t&is case* t&e TCP sender
will retransmit t&e lost TCP acket based on t&e retransmission rocess eAlained
in Sect) #)1)2)
1D.1." TCP 7eader
TCP acket &eader is de/ined in t&e F(dr5tcpG str!ct data tye s&own in
Pro'ram 1,)1) T&e key 1ariables o/ (dr5tcp include
se+no5 TCP seDuence number
ts5 Timestam< T&e time w&en t&e acket was 'enerated
ts5ec(o5 Timestam ec&o< T&e time w&en t&e eerin' TCP recei1ed
t&e acket
reason5 (eason /or acket transmission ?e)')* , . normal transmission@
In common wit& ot&er acket &eader* (dr5tcp contains /unction
access&p' ?!ines "H1,@* w&ic& can be used to obtain t&e re/erence to a TCP
&eader stored in t&e inut acket
N
p) T&is re/erence can t&en be used to access t&e
attributes o/ a TCP acket &eader)
1D.1.$ )efining TCP Sender and Recei#er
6e /ollow t&e 'uidelines ro1ided in Sect) #)2): to de/ine a TCP sender and a TCP
recei1er)
1,)1 4n O1er1iew o/ TCP 4'ents in NS2 233
Program %:=% .eclaration o/ (dr tcp str!ct data tye
MMUMnsMtcpMtcpI(
2 str!ct (dr5tcp 7
1 do!ble ts5; MMtime packet $enerated &at so!rce'
3 do!ble ts5ec(o5; MMt(e ec(oed timestamp
= int se+no5; MMse+!ence n!mber
> int reason5; MMreason "or a retransmit
A static int o""set5; MM o""set "or t(is (eader
B inline static intF o""set&' 7 ret!rn o""set5; 8
/ inline static (dr5tcp
N
access&Packet
N
p' 7
G ret!rn &(dr5tcp
N
' pJKaccess&o""set5';
20 8
22 intF se+no&' 7 ret!rn &se+no5'; 8
21 III
23 8;
Ste& %2 -efine the 'nheritance Structure
NS2 de/ines TCP sender in a CCC class TcpA$ent w&ic& is bound to an OTcl
class A$entMTCP t&rou'& a main' class TcpClass* as s&own in !ines 1H2
o/ Pro'ram 1,)2) Similarly* TCP recei1er is de/ined in a CCC class TcpSink
w&ic& is bound to an OTcl class A$entMTCPSink t&rou'& a main' class
TcpSinkClass* as s&own in !ines "H1: o/ Pro'ram 1,)2)
Ste& 22 -efine the Necessary $CC an ,Tc#
>ariab#es
6&ile class TcpSink &as only one CCC key 1ariable Facker5G w&ic& is o/
class Acker*
1
class TcpA$ent &as se1eral 1ariables) 6e classi/y t&e key CCC
1ariables o/ class TcpA$ent into /our cate'ories) Cirst* CCC 1ariables* w&ose
1alues c&an'e dynamically durin' a simulation* are s&own in Table 1,)1) Second*
CCC 1ariables* w&ic& are usually con/i'ured once* are listed in Table 1,)2) T&ird*
Table 1,)3 s&ows t&e 1ariables t&at are related to TCP timer mec&anism) Cinally*
Table 1,): s&ows t&e %iscellaneous 1ariables o/ class TcpA$ent)
%:=%=/=% Ste& *2 'm&#ement the $onstructor
T&e constructors o/ bot& TCP senders and TCP recei1ers set t&eir 1ariables to
t&e de/ault 1alues* and bind CCC 1ariables to OTcl inst1ars as seci/ied in
Tables 1,)1H1,)3) In addition* t&e constructor o/ t&e TCP sender in1okes t&e
1
6e will be discuss t&e details o/ class Acker later in Sect) 1,)2)1)
232 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=2 Class TcpClass w&ic& binds a CCC class TcpA$ent and
an OTcl class A$entMTCP to'et&er* class TcpSinkClass* w&ic& binds a
CCC class TcpSink and an OTcl class A$entMTCPSink to'et&er* and t&e
constructor o/ class TcpSink
MMUMnsMtcpMtcpIcc
2 static class TcpClass 9 p!blic TclClass 7
1 p!blic9
3 TcpClass&' 9 TclClass&HA$entMTCPH' 78
= TclObject
N
create&int ) const c(ar
N
const
N
' 7
> ret!rn &ne, TcpA$ent&'';
A 8
B 8 class5tcp;
MMUMnsMtcpMtcpJsinkIcc
/ static class TcpSinkClass 9 p!blic TclClass 7
G p!blic9
20 TcpSinkClass&' 9 TclClass&HA$entMTCPSinkH' 78
22 TclObject
N
create&int) const c(ar
N
const
N
' 7
21 ret!rn &ne, TcpSink&ne, Acker'';
23 8
2= 8 class5tcpsink;
2> TcpSink99TcpSink&Acker
N
acker' 9 A$ent&PT5ACV')
acker5&acker' 7III8
Program %:=* Comonents o/ TcpA$ent related to TCP retransmission timer
MMUMnsMtcpMtcpI(
2 class TcpA$ent 9 p!blic A$ent 7
1 III
3 protected9
= #t*Timer rt*5timer5;
> III
A 8
MMUMnsMtcpMtcpIcc
B TcpA$ent99TcpA$ent&' 9 III A$ent &PT5TCP') rt*5timer5&t(is')
III
/ 7 III 8
constructor o/ its arent class ?i)e)* A$ent@ wit& an inut ar'ument PT5TCP*
settin' t&e instantiated TcpA$ent obBect to transmit TCP acket only) It also
initialiJes t&e retransmission timer Frt*5timer5G wit& t&e ointer Ft(isG to
itsel/) T&e details o/ TcpA$ent construction and timers are 'i1en in /ile
Tns$tc$tc)cc and Sect) 13)1)
4 TCP recei1er is somew&at di//erent /rom a TCP sender* since it does not
&a1e a de/ault constructor) Crom !ine 13 o/ Pro'ram 1,)2* t&e constructor takes
a ointer to an Acker obBect as an inut ar'ument ?see Sect) 1,)2)1@* and
initialiJes
1,)2 TCP (ecei1er 233
c,nd5 c,nd5 , Con'estion window siJe in ackets
sst(res(5 sst(res(5 , Slow9start t&res&old
d!packs5 d!packs5 , .ulicated 4CK counter
ma*se+5 ma*se+5 , Hi'&est transmitted seDuence number
t5rtt5 rtt5 , (TT samle
t5srtt5 srtt5 , Smoot&ed (TT
t5rttvar5 rttvar5 , (TT de1iation
t5backo""5 backo""5 , Current (TO backo// multilicati1e /actor
rtt5active5 N$4 , Status o/ t&e (TT collection rocess
rtt5ts5 N$4 H1 Time at w&ic& t&e acket is transmitted
rtt5se+5 N$4 , SeDuence number o/ t&e ta''ed acket
t5rt*c!r5 N$4 , Current 1alue o/ unbounded retransmission
Tab#e %:=% Key oeratin' 1ariables o/ class TcpA$ent
.e/ault
C CC 1 ar i ab l e O T cl 1 ar i ab l e 1 a l u e . escr i ti o n
t5se+no5 t5se+no5 , Current TCP seDuence number
c!rse+5 se+no5 , Total number o/ ackets need to be transmitted
seci/ied by t&e alication) 4 TCP sender
transmits ackets as lon' as its seDuence
number is less t&an c!rse+5)
(i$(est5ack5 ack5 , Hi'&est 4CK number ?not /roJen durin' /ast
reco1ery@
lastack5 N$4 , Hi'&est 4CK number ?/roJen durin' /ast
reco1ery@
timeout
ts5peer5 N$4 , !atest timestam ro1ided by t&e eerin' TCP
recei1er
rt*5timer5 N$4 N$4 (etransmission timer obBect
its 1ariable Facker5G wit& t&is inut ointer) It also initialiJes its arent
constructor wit& PT5ACV* an 4CK acket tye) Cinally* it binds /ew CCC
1ariables to OTcl inst1ars ?see t&e detailed construction o/ class TcpSink in
/ile Tns$tc$tc9 sink)cc@)
Ste&s *3 /3 an 02 'm&#ement the Necessary 4unctions3 ,Tc# $ommans3
an
'nst&rocs3 an -efine Timers if Necessary
T&e detailed imlementation o/ CCC /unctions o/ TCP recei1ers are s&own in
t&e neAt section* w&ile t&ose o/ TCP senders are 'i1en in Sects) 1,)3H1,)2) Cor
bre1ity* we will not discuss t&e details o/ imlementation o/ OTcl command
and instroc) T&e readers are encoura'ed to study t&e details o/ TCP senders
and TCP recei1ers in /iles Tns$tc$tc)cc*&* Tns$tc$tc9sink)cc*&* and Tns$tcl$lib$ns9
a'ent)tcl)
,nd5init5 ,indo,Init5 2 Initial 1alue o/ window siJe
si6e5 packetSi6e5 1*,,, TCP acket siJe in bytes
tcpip5base5 tcpip5base5(dr5si6e5 :, TCP basic &eader siJe in bytes
!seHeaders5 !seHeaders5 tr!e I/ tr!e* TCP and IP &eader
siJe will be added to
23: 1, Transort Control Protocols Part 2< Transmission Control Protocol
Tab#e %:=2 Key 1ariables o/ class TcpA$ent
.e/ault
C CC 1 ar i ab l e O T cl 1 ar i ab l e 1 a l u e . escr i ti o n
,nd5 ,indo,5 2, 0er bound on window siJe
n!md!packs5 n!md!packs5 3 Number o/ dulicated 4CKs
w&ic& tri''ers /ast
retransmit
acket siJe
ma*b!rst5 ma*b!rst5 , %aAimum number o/ bytes
t&at a TCP sender can
transmit in one
transmission
ma*c,nd5 ma*c,nd5 , 0er bound on c,nd5
control5 control5increase5 , I/ set to 1* do not oen t&e
con'estion window w&en
t&e network is limited ?See
Sect) 1,)3@)
increase5
Tab#e %:=* Timer9related 1ariables o/ class TcpA$ent
.e/ault
C CC 1 ar i ab l e O T cl 1 ar i ab l e 1 a l u e . escr i ti o n
srtt5init5 srtt5init5 , Initial 1alue o/ t5srtt5
rttvar5init5 rttvar5init5 12 Initial 1alue o/ t5rttvar5
rt*c!r5init5 rt*c!r5init5 3), Initial 1alue o/ t5rt*c!r5
T5S#TT5.ITS T5S#TT5.ITS 3 %ultilicati1e /actor /or smoot&ed
(TT
T5#TTSA#5.ITS T5#TTSA#5.ITS 2 %ultilicati1e /actor /or (TT
de1iation
rttvar5e*p5 rttvar5e*p5 2 %ultilicati1e /actor /or (TO
comutation
decrease5n!m5 decrease5n!m5 ,)3 6indow decreasin' /actor
increase5n!m5 increase5n!m5 1), 6indow increasin' /actor
tcp5tick5 tcp5tick5 ,),1 Timer 'ranularity in seconds
ma*rto5 ma*rto5 1,,*,,, 0er bound on (TO in seconds
minrto5 minrto5 ,)2 !ower bound on (TO in seconds
%:=2 T$P Receiver
4 TCP recei1er is resonsible /or deallocatin' recei1ed TCP ackets and returnin'
cumulati1e 4CK ackets to t&e TCP sender) 4s discussed in Sect) #)1)2* a
cumula9 ti1e 4CK acket acknowled'es a TCP acket wit& t&e &i'&est conti'uous
seDuence
1,)2 TCP (ecei1er 232
last5c,nd5action5 N$4 T&e latest action on con'estion window
recover5 N$4 T&e &i'&est transmitted seDuence number durin' t&e
Tab#e %:=/ %iscellaneous 1ariables o/ class TcpA$ent
.e/ault
C CC 1 ar i ab l e 1 a l u e . escr i ti o n
con$5action5 , tr!e w&en t&e con'estion &as occurred)
sin$led!p5 1 I/ set to 1* t&e TCP sender will transmit new ackets
uon recei1in' /irst /ew dulicated 4CK
ackets)
prev5(i$(est5ack5 N$4 SeDuence number o/ an 4CK acket recei1ed be/ore
t&e current 4CK acket)
re1ious acket loss e1ent
4ig= %:=2 In/ormation necessary to 'enerate a cumulati1e acknowled'ement
number) 0on recei1in' a cumulati1e 4CK acket* t&e TCP sender assumes t&at
all ackets w&ose seDuence numbers are lower t&an or eDual to t&at o/ t&e 4CK
acket &a1e been success/ully recei1ed) 4 cumulati1e 4CK acket &as t&e
caability o/ acknowled'in' multile ackets) Cor eAamle* suose Packet 3 in
Ci') #)2 is not lost but is delayed and t&at it arri1es at t&e recei1er ri'&t a/ter
Packet 8 is recei1ed) 0on recei1in' Packet 3* t&e recei1er acknowled'es wit&
48* since it &as recei1ed Packets :H8 earlier)
In NS2* CCC imlementation o/ TCP recei1ers in1ol1es two main classes<
Acker and TcpSink) Class Acker is a &eler class resonsible /or
'eneratin' 4CK ackets) Class TcpSink contains an Acker obBect and acts as
inter/aces to a eerin' TCP sender)
238 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=/ .eclaration o/ class Acker
MMUMnsMtcpMtcpJsinkI(
2 class Acker 7
1 p!blic9
3 Acker&';
= virt!al UAcker&' 7 delete?@ seen5; 8
> inline int Se+no&' const 7 ret!rn &ne*t5 J 2'; 8
A inline int %a*seen&' const 7 ret!rn &ma*seen5'; 8
B int !pdate&int se+no) int n!m.ytes';
/ protected9
G int ne*t5;
20 int ma*seen5;
22 int ,ndmask5;
21 int
N
seen5;
23 int is5d!p5;
2= 8;
1D.2.1 Class Acker
Pro'ram 1,): s&ows t&e declaration o/ a CCC class Acker)
2
Class Acker
stores necessary in/ormation reDuired to 'enerate cumulati1e 4CK ackets in t&e
/ollowin' 1ariables<
seen5 4n array w&ose indeA and 1alue are t&e seDuence number
and t&e corresondin' acket siJe* resecti1ely
ne*t5 EAected seDuence number
ma*seen5 Hi'&est seDuence number e1er recei1ed
,ndmask5 %odulus mask* initialiJed to maAimum window siJe91
?set to 83 by de/aultO see Sect) 13):)1@
is5d!p5 True i/ t&e latest recei1ed TCP acket was recei1ed earlier
Ci'ure 1,)2 s&ows an eAamle o/ in/ormation stored in an Acker obBect) In
t&is case* Packets 1* 2* 3* 3* and 2 are recei1ed* but Packets : and 8 are missin')
T&ere/ore* Fne*t5G and Fma*seen5G are set to : and 2* resecti1ely) 4lso*
1ariable Fseen5G stores t&e siJe in bytes o/ Packets 1H2 in its resecti1e entries)
To determine w&et&er acket n is missin'* class Acker c&ecks t&e 1alue o/
seen5?n@) T&e acket is missin' i/ and only i/ seen5?n@ is Jero) Suose a
TCP recei1er recei1es a TCP acket number : w&en t&e status o/ t&e Acker
obBect is as in Ci') 1,)2) T&e Acker obBect will 'enerate an 4CK acket wit&
seDuence number 3) Howe1er* i/ t&e seDuence number o/ t&e recei1ed acket is not
: ?e)')* 2*
"* #@* t&e Acker obBect will create an 4CK acket wit& seDuence number
3)
2
Class Acker is not imlemented in t&e OTcl domain)
1,)2 TCP (ecei1er 23#
Program %:=0 T&e constructor o/ class Acker
MMUMnsMtcpMtcpJsinkIcc
2 Acker99Acker&' 9 ne*t5&0') ma*seen5&0') ,ndmask5&%W%'
1 7
3 seen5 : ne, int?%WS@;
= memset&seen5) 0) &si6eo"&int'
N
&%WS''';
> 8
MMUMnsMtcpMtcpJsinkIcc
A Ode"ine %WS A=
B Ode"ine %W% &%WSJ2'
4s discussed in Sect) #)1)2* a TCP sender can transmit at most w
unacknowled'ed ackets in a network* w&ere w is t&e current con'estion window
siJe) !et %WS be t&e %aAimum 6indow SiJe in a simulation ?see !ine 8 in
Pro'ram 1,)3@) T&en* w 2 /,O O %WSJ2' and t&ere can be at most %WS
unacknowled'ed ackets durin' t&e entire simulation) 4n Acker obBect needs
only %WS entries in t&e array Fseen5G to store in/ormation about
unacknowled'ed ackets)
Pro'ram 1,)3 s&ows t&e constructor o/ t&e CCC class Acker) T&e constructor
resets Fne*t5G and Fma*seen5G to Jero in !ine 1) !ine 3 allocates memory
sace /or array 1ariable Fseen5G wit& %WS entries) !ine : clears t&e allocated
memory to Jero) 4lso* F,ndmask5G is set to %W% ?%aAimum 6indow %ask
w&ic& is set to
83 in !ine 2@)
T&e abo1e %WS ?set by de/ault to 8: in !ine 8 o/ Pro'ram 1,)3@ entries o/
Fseen5G are reused to store t&e acket siJe corresondin' to all incomin' TCP
se9 Duence numbers) Class Acker uses a modulus oeration to ma a seDuence
number to an array indeA) 0on recei1in' a TCP acket wit& seDuence number
Fse+no*G an Acker obBect stores t&e acket siJe in t&e entry se+no E %WS
?w&ic& is t&e remainder o/ se+noM%WS@* o/ t&e array Fseen5*G w&ere FEG is a
modulus oerator) 6&en Fse+noG eAceeds %WS* se+no E %WS will be
restarted /rom t&e /irst entry ?i)e* t&e indeA number FoG@ to reuse t&e memory
allocated to Fseen5)G
4s discussed in Sect) 13):)1* a modulus oeration can also be imlemented
by bit maskin') In articular* se+no E %WS is in /act eDui1alent to se+no F
,ndmask5* w&ere F,ndmask5G is set initially to %W% in t&e constructor ?!ine 1
in Pro'ram 1,)3@* and %W% ?%aAimum 6indow %ask@ is de/ined as 83 ?!ines 8
and
2 in Pro'ram 1,)3@)
3
To /acilitate t&e understandin'* readers may consider t&e case
w&ere seDno is less t&an 8:* w&ere se+no F ,ndmask5 is simly se+no)
Class Acker &as two key /unctions< Se+no&' and !pdate&se+)
n!m.ytes') Cunction Se+no&' ?!ine 3 in Pro'ram 1,):@ returns t&e &i'&est
seDuence number o/ a burst o/ conti'uously recei1ed ackets) 4s s&own in
Pro'ram 1,)8* /unction !pdate&se+)n!m.ytes' udates its internal
1ariables accordin' to t&e inut ar'uments)
3
6&ile t&e ossible 1alue o/ se+no is in /,*< < < * 83333'* t&e ossible 1alue o/ se+no E A=
23" 1, Transort Control Protocols Part 2< Transmission Control Protocol
?w&ic& is eDual to se+no F A3 is in /,*< < < *83')
1,)2 TCP (ecei1er 23#
Program %:=6 Cunction !pdate o/ class Acker
MMUMnsMtcpMtcpJsinkIcc
2 int Acker99!pdate&int se+) int n!m.ytes'
1 7
3 bool j!st5marked5as5seen : QALSE;
= is5d!p5 : QALSE;
> int n!mToDeliver : 0;
A i" &se+ K ma*seen5' 7
B int i;
/ "or &i : ma*seen5 4 2; i < se+; 44i'
G seen5?i F ,ndmask5@ : 0;
20 ma*seen5 : se+;
22 seen5?ma*seen5 F ,ndmask5@ : n!m.ytes;
21 seen5?&ma*seen5 4 2' F ,ndmask5@ : 0;
23 j!st5marked5as5seen : T#DE;
2= 8
2> int ne*t : ne*t5;
2A i" &se+ < ne*t'
2B is5d!p5 : T#DE;
2/ i" &se+ K: ne*t FF se+ <: ma*seen5' 7
2G i" &seen5?se+ F ,ndmask5@ FF Cj!st5marked5as5seen'
10 is5d!p5 : T#DE;
12 seen5?se+ F ,ndmask5@ : n!m.ytes;
11 ,(ile &seen5?ne*t F ,ndmask5@' 7
13 n!mToDeliver 4: seen5?ne*t F ,ndmask5@;
1= 44ne*t;
1> 8
1A ne*t5 : ne*t;
1B 8
1/ ret!rn n!mToDeliver;
1G 8
Cunction !pdate&se+)n!m.ytes' takes two inut ar'uments< Fse+G and
Fn!m.ytesG w&ic& are t&e seDuence number and t&e siJe o/ an incomin' TCP
acket* resecti1ely) It udates 1ariables Fne*t5*G Fma*seen5*G Fseen5*G and
Fis5d!p5G* and returns t&e number o/ in9seDuence bytes w&ic& is ready to be
deli1ered to t&e alication) Crom Ci') 1,)2* Fse+G can be ?I@ less t&an Fne*t5*G
?II@ between Fne*t5G and Fma*seen5*G and ?III@ 'reater t&an Fma*seen5)G
Cunction !pdate&se+)n!m.ytes' reacts to t&ese t&ree cases as /ollows<
?i@ I/ Fse+G < Fne*t5*G /unction !pdate&se+)n!m.ytes' will set
Fis5d!p5G to be tr!e ?!ine 12@) T&is case imlies t&at t&is acket was
recei1ed earlier* and t&ere/ore* t&is acket is a dulicate acket)
?ii@ I/ Fse+G lies in between Fne*t5G and Fma*seen5*G /unction
!pdate&se+) n!m.ytes' will eAecute !ines 1#H28) !ine 1#
determines w&et&er Fse+G was recei1ed earlier) T&is &aens to be true
under t&e two /ollowin' conditions< ?1@ t&e corresondin' entry o/ Fseen5G
is nonJero and ?2@ j!st5marked5as5seen is "alse) T&e latter
condition is added since i/ se+ is a new seDuence number* !ine 11 would
also &a1e store t&e acket siJe is seen5) Howe1er* t&e 1ariable
R!st5marked5as5seen would &a1e been set as tr!e by !ine 13) Cor
Case ?ii@* Fis5d!p5G is set to tr!e)
2:, 1, Transort Control Protocols Part 2< Transmission Control Protocol
!ine 21 stores t&e acket siJe in seen5?se+ F ,ndmask5@)
:
!ines
22H28 udate Fne*t5G by ad1ancin' Fne*t5G until seen5?ne*t5 F
,ndmask5@ is emty) 4lso* !ine 23 kees addin' t&e acket siJe to
n!mToDeliver* w&ic& are returned in !ine 2") Essentially* t&e returned
1alue is t&e number o/ bytes w&ic& corresonds to Fne*t5G ad1ancement)
?iii@ I/ se+ K ma*seen5* imlyin' a new TCP acket* /unction !pdate&III'
will eAecute !ines 2H13) !ines "H# and 12 clear t&e seen5?ma*seen542@
t&rou'& seen5?se+J2@) It udates Fma*seen5G in !ine 1, and stores t&e
acket siJe in seen5?se+ F ,ndmask5@ in !ine 11) Since !ine 1, stores
Fse+G in Fma*seen5*G t&e condition in !ine 1" is satis/ied and !ines 1#H28
are to be eAecuted) I/ Case ?iii@ is eAecuted* Case ?ii@ will also be eAecuted)
T&ere/ore* !ine 13 sets Fj!st5marked5as5seenG to be tr!e* w&ic&
simly indicates t&at t&e current acket is not a dulicated acket* and !ine
2, will be skied)
1D.2.2 Class Tc%&ink
(eresentin' TCP recei1ers* class TcpSink reacts to recei1ed TCP ackets as
/ollows<
1) EAtract t&e seDuence number &se+' /rom t&e recei1ed TCP acket*
2) In/orm t&e Acker obBect o/ t&e seDuence number ?se+@ and t&e siJe o/ t&e
TCP
acket ?n!m.ytes@ t&rou'& /unction !pdate&se+)n!m.ytes' o/ class
Acker*
3) Create and send an 4CK acket to t&e TCP sender by in1okin' /unction
ack&p' o/ class TcpSink) T&e seDuence number in t&e 4CK acket is
obtained /rom /unction Se+no&' o/ t&e Acker obBect ?in1oked /rom
wit&in /unction ack&p'@)
Pro'ram 1,)2 s&ows t&e declaration o/ a CCC class Tcpsink* w&ic& is bound
to an OTcl class A$entMTCPSink) T&e only key 1ariable o/ class TcpSink is
a ointer to an Acker obBect* Facker5G in !ine ") Two main /unctions o/ class
TcpSink include recv&p)(' and ack&p')
S&own in Pro'ram 1,)"* /unction recv&p)(' is in1oked by an ustream
obBect to &and a TCP acket o1er to a TcpSink obBect) !ines :H8 in/orm t&e
Acker obBect* Facker5*G o/ an incomin' TCP acket Fpkt)G Here* t&e
seDuence number ?i)e)* t(JKse+no&'@ and acket siJe ?i)e)* n!m.ytes@ are
assed to Facker5G t&rou'& t&is /unction) 4'ain* /unction
!pdate&se+)n!m.ytes' returns t&e number o/ in9order bytes w&ic& can
be deli1ered to t&e alication) I/ t&is number is nonJero* it will be deli1ered to
t&e alication t&rou'& /unction recv.ytes&bytes' in !ine ") !ine #
in1okes /unction ack&pkt' to 'enerate an 4CK acket and send it to t&e TCP
sender) Cinally* !ine 1, deallocates t&e recei1ed TCP acket)
:
+it maskin' wit& F,ndmask G &as t&e same imact as a modulus wit& F,ndmask 42G does)
1,)2 TCP (ecei1er 2:1
Program %:=5 .eclaration o/ class TcpSink
MMUMnsMtcpMtcpJsinkI(
2 class TcpSink 9 p!blic A$ent 7
1 p!blic9
3 TcpSink&Acker
N
';
= void recv&Packet
N
pkt) Handler
N
';
> int command&int ar$c) const c(ar
N
const
N
ar$v';
A protected9
B void ack&Packet
N
';
/ Acker
N
acker5;
G 8;
Program %:=7 Cunction recv o/ class
TcpSink
MMUMnsMtcpMtcpJsinkIcc
2 void TcpSink99recv&Packet
N
pkt) Handler
N
'
1 7
3 int n!mToDeliver;
= int n!m.ytes : (dr5cmn99access&pkt'JKsi6e&';
> (dr5tcp
N
t( : (dr5tcp99access&pkt';
A n!mToDeliver : acker5JK!pdate&t(JKse+no&') n!m.ytes';
B i" &n!mToDeliver'
/ recv.ytes&n!mToDeliver';
G ack&pkt';
20 Packet99"ree&pkt';
22 8
Program %:=8 Cunction ack o/ class
TcpSink
MMUMnsMtcpMtcpJsinkIcc
2 void TcpSink99ack&Packet
N
opkt'
1 7
3 Packet
N
npkt : allocpkt&';
= (dr5tcp
N
otcp : (dr5tcp99access&opkt';
> (dr5tcp
N
ntcp : (dr5tcp99access&npkt';
A ntcpJKse+no&' : acker5JKSe+no&';
B do!ble no, : Sc(ed!ler99instance&'Iclock&';
/ ntcpJKts&' : no,;
G (dr5ip
N
oip : (dr5ip99access&opkt';
20 (dr5ip
N
nip : (dr5ip99access&npkt';
22 nipJK"lo,id&' : oipJK"lo,id&';
21 send&npkt) 0';
23 8
Pro'ram 1,)# s&ows t&e details o/ /unction ack&p') In t&is /unction* 1ariables
w&ose name be'ins wit& FoG and FnG are used /or an old acket and a new
acket* resecti1ely) !ine 8 uts an 4CK number in t&e 4CK acket) !ines 2H"
and #H11 con/i'ure timestam and /low I. o/ t&e 4CK acket* resecti1ely)
2:2 1, Transort Control Protocols Part 2< Transmission Control Protocol
Cinally* t&e con/i'ured acket is sent out usin' /unction send&npkt)0' o/
class A$ent in !ine 12* w&ere a new acket FnpktG is transmitted alon' wit&
a Null &andler)
%:=* T$P Sener
4 TCP sender &as t&e /ollowin' /our main resonsibilities<
Packet transmission< +ased on user demand /rom an alication* a TCP sender
creates and /orwards TCP ackets to a TCP recei1er)
+CB processing< 4 TCP sender obser1es a recei1ed 4CK attern and
determines w&et&er transmitted ackets were lost) I/ so* it will retransmit t&e
lost ackets) Crom t&e 4CK attern* it can also estimate t&e network condition
?e)')* end9to9 end bandwidt&@ and adBust t&e con'estion window accordin'ly)
Timer)related mechanism< 4 retransmission timer is used to ro1ide connection
reliability) 0nless reset by an 4CK acket arri1al* t&e retransmission timer
in/orms t&e TCP sender o/ acket loss a/ter t&e acket &as been transmitted /or
a eriod o/ #etransmission Time(ut -#T(0)
6indow ad3ustment< +ased on t&e 4CK attern and timeout e1ent* a TCP
sender adBusts its con'estion window to /ully use t&e network resource and
re1ent network con'estion)
T&e details o/ t&ese /our resonsibilities will be discussed in t&e neAt /our
sections)
%:=/ T$P Packet Transmission 4unctions
Class TcpA$ent ro1ides t&e /ollowin' /our main acket transmission
/unctions<
sendms$&nbytes'< Send FnbytesG o/ alication ayload) 6&en
nbytes:J2* t&e ayload is assumed to be in/inite)
sendm!c(&"orce)reason)ma*b!rst'< Send out a acket w&ose se9
Duence number is Ft5se+no5)G Kee sendin' out ackets as lon' as t&e
con'estion window allows and t&e total number o/ transmitted ackets durin'
a /unction in1ocation does not eAceed Fma*b!rst)G
o!tp!t&se+no)reason'< Create and send a acket wit& a seDuence
number
and a transmission reason as seci/ied by Fse+noG and Freason*G
resecti1ely)
send5one&'< Send a TCP acket wit& a seDuence number
Ft5se+no5)G
4mon' t&e abo1e /unctions* /unction sendms$&nbytes' is t&e only
p!blic
/unction deri1ed /rom class A$ent* w&ile t&e ot&er t&ree /unctions are internal to
1,): TCP Packet Transmission Cunctions 2:3
class TcpA$ent) 4'ain* /unction sendms$&nbytes' is in1oked by an
alica9 tion to in/orm a TcpA$ent obBect o/ user demand) Cunction
sendms$&nbytes' does not directly send out ackets) (at&er* it comutes t&e
number o/ TCP ackets reDuired to &old FnbytesG o/ data ayload* and increases
1ariable Fc!rse+5G by t&e comuted 1alue) In NS2* a TcpA$ent obBect kees
transmittin' TCP ackets as lon' as t&e seDuence number does not eAceed
Fc!rse+5)G Increasin' Fc!rse+5G is t&ere/ore eDui1alent to /eedin' data
ayload to a TcpA$ent obBect)
4not&er imortant 1ariable is Ft5se+no5*G w&ic& contains t&e de/ault TCP
seDuence number) 0nless ot&erwise seci/ied* a TCP sender always transmits a
TCP acket wit& t&e seDuence number stored in Ft5se+no5)G +ot& t&e /unc9
tions sendm!c(&"orce)reason)ma*b!rst' and send5one&' use
/unc9 tion o!tp!t&t5se+no5)reason' to send out a TCP acket w&ose
seDuence number is Ft5se+no5)G
Cunction send5m!c(&III' acts as a /oundation /or TCP acket
transmission) In most cases* TCP a'ent /irst stores t&e seDuence number o/ t&e
acket to be transmitted in Ft5se+no5)G T&en* it in1okes t&e /unction
send5m!c(&III' to send TCP ackets9startin' wit& t&at wit& t&e seDuence
number Ft5se+no5G as lon' as t&e transmission window ermits) 4s we s&all
see in Pro'ram 1,)11* eac& acket transmission is carried out usin' /unction
o!tp!t&t5se+no5) reason')
1D.$.1 5!nction sendmsg)nb$tes*
Cunction send5ms$&nbytes' is t&e main data transmission inter/ace /unction
deri1ed /rom class A$ent) 4 user ?e)')* alication@ in/orms a TCP sender o/
transmission demand t&rou'& t&is /unction) Cunction sendms$&nbytes'
usually takes one inut ar'ument* Fnbytes*G w&ic& is t&e amount o/ alication
ayload in bytes t&at a user needs to send) 6&en t&e user &as in/inite demand*
FnbytesG is seci/ied as 1)
Pro'ram 1,)1, s&ows t&e details o/ /unction sendms$&nbytes') !ines
:H2 trans/orm t&e inut user demand to t&e number o/ TCP ackets to be
transmitted ?i)e)* Fc!rse+5G@) !ine " starts data transmission by in1okin' /unc9
tion send5m!c(&0)0)ma*b!rst5') Note t&at !ine 1 seci/ies t&e limit ?i)e)*
TCP5%ALSE@ on t&e number o/ TCP seDuence numbers w&ic& can be created
by a certain TCP sender) 4'ain* i/ nbytes : J2* t&e TCP sender will be
backlo''ed until FTCP5%ALSEG TCP ackets are transmitted) I/ FnbytesG
is 'reater t&an 1* !ine 2 will comute t&e number o/ TCP ackets ?eac&
wit& siJe Fsi6e5G bytes@ w&ic& can accommodate FnbytesG o/ alication
ayload)
2:: 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=%: Cunction sendms$ o/ class TcpA$ent
MMUMnsMtcpMtcpI(
2 Ode"ine TCP5%ALSE 20B3B=2/1=
MMUMnsMtcpMtcpIcc
1 void TcpA$ent99sendms$&int nbytes) const c(ar
N
M
N
"la$s
N
M'
3 7
= i" &nbytes :: J2 FF c!rse+5 <: TCP5%ALSE'
> c!rse+5 : TCP5%ALSE;
A else
B c!rse+5 4: &nbytesMsi6e5 4 &nbytesEsi6e5 Y 2 9 0'';
/ send5m!c(&0) 0) ma*b!rst5';
G 8
1D.$.2 5!nction send much)force+reason+ma,burst*
T&ere are t&ree imortant oints in re'ards to /unction send5m!c(&"orce)
reason)ma*b!rst') Cirst* it creates and sends out as many ackets as t&e cur9
rent transmission window allows* but not 'reater t&an Fma*b!rstG ackets) Sec9
ond* e1ery acket is transmitted by eAecutin' o!tp!t&t5se+no5)reason')
Cinally* /unction send5m!c(&III' always sends out a TCP ackets wit&
seDuence number Ft5se+no5)G
Cunction send5m!c(&"orce)reason)ma*b!rst' takes t&ree /ollowin'
inut ar'uments* w&ere a tyical in1ocation o/ t&is /unction is
send5m!c(&0)0) ma*b!rst5'<
F"orceG< T&is 1alue is usually set to Jero) 6&en F"orceG : 2* TCP sender
will try to transmit data ackets e1en i/ some conditions are not met)
3
FreasonG< T&is 1alue seci/ies t&e reason /or data transmission) Cor a normal
transmission* FreasonG is set to ,) Ot&er ossible 1alues o/ FreasonG are
s&own in !ines 1H: in Pro'ram 1,)11) T&is inut ar'ument is later laced in t&e
/ield Freason5G o/ TCP acket &eader ?i)e)* (dr5tcp99reason5@ and will
be used /or 1arious uroses in simulation)
Fma*b!rstG< T&e maAimum number o/ ackets t&at can be transmitted /or
eac& in1ocation o/ /unction send5m!c(&"orce)reason)ma*b!rst')
Pro'ram 1,)11 s&ows t&e details o/ /unction send5m!c(&"orce)
reason) ma*b!rst') Cunction
send5m!c(&"orce)reason)ma*b!rst' /irst stores
3
Cor eAamle* a 1ariable Fover(ead G adds a certain delay time seci/ied by a
DelSndTimer obBect be/ore data transmission) +y de/ault* TCP sender does not transmit
w&en Fover(ead G is nonJero) Howe1er* it can transmit ackets immediately w&en "orce
: 2) Note t&at we do not discuss t&e details o/ class DelSndTimer &ere) T&e readers may
/ind t&e details o/ class DelSndTimer in /iles Tns$tc$tc)cc*&)
1,): TCP Packet Transmission Cunctions 2:3
Program %:=%% Cunctions send m!c( and window?@ o/ class
TcpA$ent
MMUMnsMtcpMtcpI(
2 Ode"ine TCP5#EASON5TI%EODT 0*02 MMTimeo!t
1 Ode"ine TCP5#EASON5DDPACV 0*01 MMD!plicated ACV
3 Ode"ine TCP5#EASON5#.P 0*03 MM#ate .ased Pacin$
= Ode"ine TCP5#EASON5PA#TIALACV 0*0= MMPartial ACV
MMUMnsMtcpMtcpIcc
> void TcpA$ent99send5m!c(&int "orce) int reason) int
ma*b!rst'
A 7
B int ,in : ,indo,&') npackets : 0;
/ ,(ile &t5se+no5 <: (i$(est5ack5 4 ,in FF t5se+no5 <
c!rse+5' 7
G i" &over(ead5 :: 0 XX "orce ' 7
20 o!tp!t&t5se+no5) reason';
22 npackets44;
21 t5se+no544;
23 8
2= ,in : ,indo,&';
2> i" &ma*b!rst FF npackets :: ma*b!rst'
2A break;
2B 8
2/ 8
2G int TcpA$ent99,indo,&'
10 7
12 ret!rn &c,nd5 < ,nd5 Y &int'c,nd5 9 &int',nd5';
11 8
t&e current con'estion window
8
in a 1ariable F,inG and sets t&e 1ariable
FnpacketsG to Jero in !ine 2) T&en* !ine " c&ecks w&et&er t&e TCP sender is
allowed to send a TCP acket wit& seDuence number Ft5se+no5)G I/ so* !ine 1,
will in1oke /unction o!tp!t&t5se+no5)reason' to send out a TCP acket)
4'ain* a TCP sender is allowed to transmit a acket i/ t&e /ollowin' two
conditions are satis/ied<
1) Con'estion window allows acket transmission< Cunction ,indo,&' in !ine
2 returns t&e minimum o/ t&e current con'estion window and t&e maAimum
win9 dow siJe) T&is minimum 1alue is stored in t&e 1ariable F,inG in !ine 2)
Since t&e latest recei1ed 4CK number is F(i$(est5ack5*G t&e TCP sender
can trans9 mit TCP ackets wit& seDuence numbers Ft5se+no5G t&rou'&
F(i$(est5 ack54,inG)
8
Crom !ines 1#H22 o/ Pro'ram 1,)11* /unction ,indo,&' returns t&e minimum o/ F,indo,
G ?t&e maAimum window siJe@ and Fc,nd G ?t&e current con'estion window siJe@ as t&e
current bounded con'estion window)
2:8 1, Transort Control Protocols Part 2< Transmission Control Protocol
2) TCP sender still &as data to transmit< T&e sender will send TCP ackets
unit t&e seDuence number reac&es Fc!rse+5)G Seci/ied in t&e user demand*
Fc!rse+5G is t&e &i'&est TCP seDuence number t&at t&e sender needs to
transmit)
4/ter a acket transmission* t&e de/ault seDuence number Ft5se+no5G
?!ine 12@ and t&e con'estion window siJe F,inG ?!ine 1:@ are udated) !ines 13H
12 sto t&e transmission* i/ TCP sender &as sent out Fma*b!rstG ackets) T&e
abo1e rocess reeats until t&e condition in !ine " becomes "alse)
1D.$." 5!nction out%ut)se-no+reason*
Takin' two inut ar'uments* /unction o!tp!t&se+no)reason' creates a
acket* sets t&e seDuence number and t&e reason /ield o/ TCP &eader to t&e inut
ar'uments Fse+noG and Freason*G resecti1ely* and /orwards t&e acket to t&e
low9le1el network usin' /unction send&p)(' o/ class A$ent)
Pro'rams 1,)12 and 1,)13 s&ow t&e details o/ /unction o!tp!t&se+no)
reason'* w&ic& consists o/ /i1e main arts) Cirst* !ine 3 creates a acket FpG
usin' /unction allocpkt&' o/ class A$ent) Second* !ines 8H28 con/i'ure
common* TCP* and /la' &eaders o/ t&e created ackets) Cor t&e common acket
&eader* /unc9 tion o!tp!t&III' con/i'ures acket siJe in !ines 1"H28) I/
F!seHeaders5G is tr!e* Ftcpip5base5(dr5si6e5G ?:, bytes by
de/ault@ will be added to t&e acket siJe) Since an S;N acket ?wit& se+no
:0 and syn :2@ contains no ay9load* its siJe is set to be
Ftcpip5base5(dr5si6e5G bytes ?!ine 22@) T&e /ollowin' TCP &eader /ields
are con/i'ured in !ines 8H12< seDuence number* timestam* timestam ec&o*
transmittin' reason* and latest obser1ed round tri time ?(TT@) Cinally* /unction
o!tp!t&III' con/i'ures t&e con'estion /la'
2
in t&e /la' &eader ?!ines 13H18@)
T&is con'estion /la' is set to be tr!e w&en TCP is tryin' to transmit a new
acket under con'estion* i)e)* bot& o/ t&e /ollowin' conditions in !ine 13 are
tr!e<
1) Con'estion &as occurred< .urin' network con'estion* TCP sender closes t&e
con'estion window by in1okin' /unction slo,do,n&(o,'* wit&in w&ic& t&e
1ariable Fcon$5action5G is set to tr!e)
2) TCP sender is transmittin' a new acket &is5ret* : "alse'< T&is /la'
set to tr!e* w&en a new acket ?not a retransmitted ackets@ is eAeriencin'
con'estion)
2
Cor eAamle* a router in t&e network may dro ackets marked wit& a congestion action /la'
to &el relie1e network con'estion) Howe1er* droin' a retransmitted acket may lead to TCP
connection reset) T&ere/ore* a TCP sender does not mark retransmitted ackets wit& a con'estion
action /la')
1,): TCP Packet Transmission Cunctions 2:2
Program %:=%2 Cunction o!tp!t o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99o!tp!t&int se+no) int reason'
1 7
3 int "orce5set5rt*5timer : 0;
= int is5retransmit : &se+no < ma*se+5';
> Packet
N
p : allocpkt&';
A (dr5tcp
N
tcp( : (dr5tcp99access&p';
B tcp(JKse+no&' : se+no;
/ tcp(JKts&' : Sc(ed!ler99instance&'Iclock&';
G tcp(JKts5ec(o&' : ts5peer5;
20 tcp(JKreason&' : reason;
22 tcp(JKlast5rtt&' : int&int&t5rtt5'
N
tcp5tick5
N
2000';
21 int databytes : (dr5cmn99access&p'JKsi6e&';
23 i" &con$5action5 FF Cis5retransmit' 7
2= (dr5"la$s
N
(" : (dr5"la$s99access&p';
2> ("JKcon$5action&' : T#DE;
2A con$5action5 : QALSE;
2B 8
2/ i" &se+no :: 0' 7
2G i" &syn5' 7
10 databytes : 0;
12 c!rse+5 4: 2;
11 (dr5cmn99access&p'JKsi6e&' : tcpip5base5(dr5
si6e5;
13 8
1= 8 else i" &!seHeaders5 :: tr!e' 7
1> (dr5cmn99access&p'JKsi6e&' 4: (eadersi6e&';
1A 8
T&e t&ird art o/ /unction o!tp!t&se+no)reason' is used to send out
t&e con/i'ured acket usin' /unction send&p)(' o/ class A$ent in !ine
22) T&e /ourt& art udates t&e rele1ant 1ariables o/ t&e TcpA$ent obBect in
!ines
2"H:") I/ t&e condition in !ine 3, is tr!e* TCP sender will no lon'er &a1e data
to transmit) In t&is case* !ine 31 in/orms t&e alication so by in1okin' /unction
idle&' o/ class A$ent) (ele1ant 1ariables to be udated are ndatapack5*
ndatabytes5* nre*mitpack5* nremitbytes5* in !ines 2"* 2#* :2* and
:3* resecti1ely) T&e /ormer two 1ariables denote t&e data transmitted by t&e
TcpA$ent obBect in ackets and bytes* w&ile t&e latter two are t&ose
corresondin' to t&e retransmitted ackets only) !ines 33H3# udate t&e related
1ariables w&en Fse+noG K Fma*se+5)G T&ese 1ariables include Fma*se+5G
and ot&er (TT estimation 1ariables) 6e will discuss about t&e (TT estimation
later in Sect) 1,)8)
T&e /inal art is to start t&e retransmission timer by in1okin' /unction
set5rt*5 timer&' in !ine :") Note t&at eac& TCP sender &as only one
retransmission timer) 0nder a normal situation* t&e timer is started only w&en it is
idle ?i)e)* its status is not TI%E#5PENDIN-@) Howe1er* it is also started w&en
(i$(est5ack5 :: ma*se+5* re'ardless o/ t&e timer5s status ?see !ine S:3H
:"@)
2:" 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=%* Cunction o!tp!t o/ class TcpA$ent ?cont)@
1B send&p) 0';
1/ 44ndatapack5;
1G ndatabytes5 4: databytes;
30 i" &se+no :: c!rse+5 FF se+no K ma*se+5'
32 idle&';
31 i" &se+no K ma*se+5' 7
33 ma*se+5 : se+no;
3= i" &Crtt5active5' 7
3> rtt5active5 : 2;
3A i" &se+no K rtt5se+5' 7
3B rtt5se+5 : se+no;
3/ rtt5ts5 : Sc(ed!ler99instance&'Iclock&';
3G 8
=0 8
=2 8 else 7
=1 44nre*mitpack5;
=3 nre*mitbytes5 4: databytes;
== 8
=> i" &(i$(est5ack5 :: ma*se+5'
=A "orce5set5rt*5timer : 2;
=B i" &C&rt*5timer5Istat!s&' :: TI%E#5PENDIN-'
XX "orce5set5rt*5timer'
=/ set5rt*5timer&';
=G 8
Program %:=%/ Cunction send one o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99send5one&'
1 7
3 i" &t5se+no5 <: (i$(est5ack5 4 ,nd5 FF t5se+no5 < c!rse+5
FF t5se+no5 <: (i$(est5ack5 4 c,nd5 4
d!packs5 ' 7
= o!tp!t&t5se+no5) 0';
> t5se+no5 44 ;
A 8
B 8
1D.$.$ 5!nction send one)*
Ci'ure 1,): s&ows t&e details o/ /unction send5one&') Cunction send5one&'
is 1ery similar to /unction send5m!c(&III') It reares seDuence numbers
startin' at Ft5se+no5G and asses t&em to /unction o!tp!t&t5se+no5)
0' /or acket creation and transmission) T&e main di//erence is t&at w&ile
/unction send5m!c(&III' may send out se1eral ackets* /unction
send5one&III' sends out only one acket) Cunction send5one&III' is
desi'ned to send a new acket durin' a /ast retransmit &ase /or e1ery recei1ed
dulicated 4CK acket
,
0
P

P
r
e
$
P
r
o
c
e
s
s
i
n
4
1,)3 4CK Processin' Cunctions 2:#
rec((61t)
88nac16ac1CE
se3no @ Se3 no: of 61tE
Q lastCac1C
(ne> ,0P)
se3no
@@ lastCac1C
(du6licated ,0P)
0ase /
rec(Cne>ac1Chel6er(61t)
0ase //
R du6licated ,0P
threshold
)o: of
Du6licated
,0Ps
@@ du6licated ,0P
threshold
0ase ///
ne>ac1(61t)
sendCone(61t) du6ac1Caction()
free(61t)
se3no Q lastCac1C
no
yes
sendmuch(!D!DmaxburstC)
retrun
4ig= %:=* Cunction recv&p)(' o/ class
TcpA$ent
?see Sect) 1,)3@) In t&is case* !ine 3 in/lates t&e con'estion windows by t&e
number o/ dulicated 4CK &d!packs5') 4s will be discussed in Sect) 1,)3* t&is
/unction is in1oked i/ t&e otion Fsin$led!p5G is set to 1 durin' t&e recetion
o/ t&e /irst dulicated 4CK ackets)
%:=0 A$D Processing 4unctions
T&e second resonsibility o/ a TCP sender is to rocess 4CK ackets) 4n 4CK
acket could be a new 4CK acket or a dulicated 4CK acket) 4 new 4CK
acket slides t&e con'estion window to t&e ri'&t and oens t&e con'estion window
to allow t&e TCP sender to transmit more ackets) 4 dulicated 4CK acket* on
t&e ot&er &and* indicates out9o/9order acket deli1ery or acket loss ?see Ci') #)2*
/or eAamle@) 4'ain* TCP Ta&oe assumes t&at acket loss uon detectin' t&e
Fn!md!packs5Gt& ?3rd by de/ault@ dulicated 4CK acket) It sets t&e slow9start
t&res&old to &al/ o/ t&e current con'estion window* sets t&e con'estion window
siJe to F,nd5init5G ?w&ic& is usually set to 1@* and retransmits t&e lost acket)
.urin' a Cast (etransmit &ase* t&e TCP sender transmits a new acket /or e1ery
23, 1, Transort Control Protocols Part 2< Transmission Control Protocol
recei1ed dulicated 4CK acket ?due to in/lated con'estion window@) 6&en a
new 4CK acket is recei1ed* t&e TCP sender sets its con'estion window to t&e
same as slow9start t&res&old* and returns to its normal oeration)
Class TcpA$ent ro1ides t&e /our /ollowin' key 4CK Processin'
/unctions<
recv&p)('< T&is is t&e main 4CK recetion /unction) It determines w&et&er
t&e recei1ed acket ?
N
p@ is a new 4CK acket or a dulicated 4CK acket* and
acts accordin'ly)
recv5ne,ack5(elper&p'< T&is /unction is in1oked /rom wit&in /unc9
tion recv&p)(' w&en a new 4CK acket is recei1ed) It in1okes /unction
ne,ack&p' to udate rele1ant 1ariables* and oens t&e con'estion window i/
necessary)
ne,ack&p'< In1oked /rom wit&in /unction recv5ne,ack5(elper&p'*
t&is /unction udates 1ariables related to seDuence number* 4CK number* and
(TT estimation rocess* and restarts t&e retransmission timer)
d!pack5action&'< T&is /unction is in1oked /rom wit&in /unction
recv&p)(' w&en a dulicated 4CK acket is recei1ed and Cast (etransmit
rocess is launc&ed) It cuts down t&e con'estion window* reares t&e seDuence
number o/ t&e lost acket /or retransmission* and resets t&e retransmission
timer)
1D.+.1 5!nction recv)%+h*
Ci'ure 1,)3 and Pro'ram 1,)13 s&ow t&e dia'ram and imlementation* resec9
ti1ely* /or /unction recv&p)(') Cunction recv&p)(' re9rocesses t&e
recei1ed 4CK ackets in !ines 8H1:* w&ere Ft5se+no5G and Fc,nd5G are
adBusted) .eendin' o/ t&e recei1ed 4CK tye ?i)e)* new or dulicated@* !ines 8H
1: ?4CK re9rocessin'@ rocess an 4CK acket accordin' to t&e /ollowin' t&ree
cases<
$ase ' (New A$D)< I/ a new 4CK acket is recei1ed ?i)e)* !ine 8 returns
tr!e@* !ine 2 will in1oke /unction recv5ne,ack5(elper&p' to adBust
con'estion window ?c,nd5@ and reare a new seDuence number
?t5se+no5@ /or acket transmission)
$ase '' (-u&#icate A$D)< In t&is case* a dulicated 4CK acket is recei1ed
?i)e)* !ine 8 returns "alse@ but t&e number o/ dulicated 4CK ackets
recei1ed so /ar &as not reac&ed Fn!md!packs5G ?i)e)* !ine # returns
"alse@) !ine
12 will in1oke /unction send5one&' to transmit new TCP ackets under
t&e con'estion window in/lated by t&e number o/ recei1ed dulicated 4CK
ackets ?see t&e de/inition o/ Cast (eco1ery in sect) #)1)2)2@) Note t&at 1ariable
Fsin$led!p5G is an NS2 otion /or con'estion window in/lation) T&e abo1e
actions are eAecuted w&en Fsin$led!p5G is tr!e only) I/
Fsin$led!p5G is "alse* t&e TCP sender will not send a new acket /or
e1ery recei1ed 4CK acket)
1,)3 4CK Processin' Cunctions 231
Program %:=%0 Cunction recv o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99recv&Packet
N
pkt) Handler
N
'
1 7
3 (dr5tcp
N
tcp( : (dr5tcp99access&pkt';
= int valid5ack : 0;
> 44nackpack5;
A i" &tcp(JKse+no&' K last5ack5' 7
B recv5ne,ack5(elper&pkt';
/ 8 else i" &tcp(JKse+no&' :: last5ack5' 7
G i" &44d!packs5 :: n!md!packs5 FF CnoQast#etrans5' 7
20 d!pack5action&';
22 8 else i" &d!packs5 < n!md!packs5 FF sin$led!p5 ' 7
21 send5one&';
23 8
2= 8
2> i" &tcp(JKse+no&' K: last5ack5'
2A valid5ack : 2;
2B Packet99"ree&pkt';
2/ i" &valid5ack'
2G send5m!c(&0) 0) ma*b!rst5';
10 8
$ase ''' (4ast retransmit)< I/ t&e recei1ed 4CK is t&e last ?i)e)*
Fn!md!packs5Gt&@ dulicated 4CK acket* t&e TCP sender will enter t&e
Cast (etransmit &ase* by in1okin' /unction d!pack5action&' ?!ine 1,@)
Note t&at an otion Cla' FnoQast#etrans5G is an NS otion /or a Cast
(etransmit &ase) T&e TCP sender will not enter a Cast (etransmit &ase* i/
FnoQast#etrans5G is tr!e)
4/ter eAecutin' one o/ t&e abo1e t&ree cases* !ine 12 deallocates t&e 4CK
acket
N
pkt by eAecutin' "ree&pkt') I/ t&e recei1ed 4CK is 1alid ?i)e)*
valid5ack5:2@* !ine 1# will create and transmit TCP ackets usin' /unction
send5m!c(&0)0)ma*b!rst5') Here a recei1ed 4CK acket is said to be 1alid
i/ it is a new 4CK acket ?i)e)* tcp(JKse+no&' K last5ack5@ or a
dulicated 4CK ?i)e)* tcp(JKse+no&' : last5ack5@) I/ an 4CK acket
is in1alid* a TCP sender will only destroy t&e 4CK acket* but will not create and
/orward new ackets)
1D.+.2 5!nction recv ne.ack
hel%er)%kt*
Cunction recv5ne,ack5(elper&pkt' is a &eler /unction in1oked w&en a
new 4CK acket is recei1ed) 4s s&own in Pro'ram 1,)18* t&e /unction recv5
ne,ack5(elper&pkt' /irst in1okes /unction ne,ack&pkt' in !ine 2 to
udate rele1ant 1ariables and to rocess t&e retransmission timer) 6&en EAlicit
Con'estion Noti/ication ?ECN@ is not enabled ?i)e)* by de/ault ECT ?ECN Caable
232 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=%6 Cunction recv ne,ack (elper o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99recv5ne,ack5(elper&Packet
N
pkt' 7
1 ne,ack&pkt';
3 i" &Cect5' 7
= i" &Ccontrol5increase5 XX
&control5increase5 FF &net,ork5limited&' :: 2'''
> openc,nd&';
A 8
B i" &&(i$(est5ack5 K: c!rse+5J2' FF Cclosed5' 7
/ closed5 : 2;
G "inis(&';
20 8
22 8
Program %:=%5 Cunction net,ork limited o/ class TcpA$ent
MMUMnsMtcpMtcpIcc
2 int TcpA$ent99net,ork5limited&' 7
1 int ,in : ,indo, &' ;
3 i" &t5se+no5 K &prev5(i$(est5ack5 4 ,in''
= ret!rn 2;
> else
A ret!rn 0;
B 8
Transort System@ is set to Jero@* !ine 3 will oen t&e con'estion window ?by
in1okin' /unction openc,nd&'@ w&en at least one o/ t&e /ollowin' conditions
is true ?!ine :@<
Fcontrol5increase5G . ,< 7ariable Fcontrol5increase5*G w&en set
to 1* suresses t&e con'estion window oenin') 6&en Fcontrol5
increase5G is Jero* a TCP sender can /reely increase t&e con'estion
window)
Fcontrol5increase5G V , but t&e network is limited< 6&en Fcontrol5
increase5G is 1* t&e TCP sender is allowed to oen t&e con'estion window
only w&en t&e re1ious con'estion window is not su//icient to transmit t&e
current acket ?i)e)* t&e network is limited@) In NS2* a network is said to
be limited w&en Ft5se+no5G is less t&an prev5(i$(est5ack5 4 ,in*
w&ere Fprev5(i$(est5ack5G is t&e 4CK number be/ore t&e recetion o/
t&e current 4CK acket and F,inG is t&e current con'estion window ?see
Pro'ram 1,)12@) In t&is case* it is necessary to oen t&e con'estion window* in
order to transmit a new acket) Note t&at i/ t&e TCP sender stos transmission
due to any reason ot&er t&an t&e reason t&at t&e network is limited* /unction
recv5ne,ack5(elper&pkt' will not oen t&e con'estion window)
Cinally* i/ t&e TCP sender no lon'er &as data to transmit* !ine " in Pro'ram
1,)18 will close t&e connection by settin' Fclosed5G to 1* and !ine # will
in1oke /unction "inis(&')
1,)3 4CK Processin' Cunctions 233
Program %:=%7 Cunction ne,ack o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99ne,ack&Packet
N
pkt'
1 7
3 do!ble no, : Sc(ed!ler99instance&'Iclock&';
= (dr5tcp
N
tcp( : (dr5tcp99access&pkt';
> d!packs5 : 0;
A last5ack5 : tcp(JKse+no&';
B prev5(i$(est5ack5 : (i$(est5ack5 ;
/ (i$(est5ack5 : last5ack5;
G i" &t5se+no5 < last5ack5 4 2'
20 t5se+no5 : last5ack5 4 2;
22 (dr5"la$s
N
"( : (dr5"la$s99access&pkt';
21 i" &rtt5active5 FF tcp(JKse+no&' K: rtt5se+5' 7
23 i" &Cect5' 7
2= t5backo""5 : 2;
2> ecn5backo""5 : 0;
2A 8
2B rtt5active5 : 0;
2/ rtt5!pdate&no, J rtt5ts5';
2G 8
10 ne,timer&pkt';
12 8
1D.+." 5!nction ne.ack)%kt*
Pro'ram 1,)1" s&ows t&e details o/ /unction ne,ack&pkt') !ines 3H1, u9
date 1ariables d!pack5* last5ack5* prev5(i$(est5ack5* (i$(est5
ack5* and t5se+no5) !ines 12H1# udate (TT estimation 1ariables and timeout
backo// 1alue) Cinally* !ine 2, starts a retransmission timer /or t&e transmittin'
acket) 6e will discuss t&e details o/ (TT estimation and retransmission timer
later in Sect) 1,)8)
1D.+.$ 5!nction du%ack action)*
T&e main resonsibilities o/ /unction d!pack5action&' are to< ?1@ decrease
con'estion window siJe* ?2@ set Ft5se+no5G to t&e seDuence number o/ t&e lost
TCP acket* and ?3@ restart retransmission timer) Pro'ram 1,)1# s&ows t&e details
o/ /unction d!pack5action&') !ine 3 re'isters /ast retransmission e1ent ?i)e)*
QAST5#ETL@ /or tracin') !ine 8 records CWND5ACTION5DDPACV as t&e latest
window adBustment action ?i)e)* Flast5c,nd5action5G@) !ine 2 closes t&e
con'estion window by in1okin' /unction
slo,do,n&CLOSE5SSTH#ESH5HALQ
X CLOSE5CWND5ONE'* /eedin' &ow t&e slow9start t&res&old and con'estion
window are to be con/i'ured as an inut ar'ument) Cinally* !ine " in1okes /unc9
tion reset5rt*5timer&0)0' to set Ft5se+no5G to (i$(est5ack542*
23: 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=%8 Cunction d!pack action o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99d!pack5action&'
1 7
3 i" &(i$(est5ack5 K recover5' 7
= recover5 : ma*se+5;
> trace5event&HQAST5#ETLH';
A last5c,nd5action5 : CWND5ACTION5DDPACV;
B slo,do,n&CLOSE5SSTH#ESH5HALQXCLOSE5CWND5ONE';
/ reset5rt*5timer&0)0';
G ret!rn;
20 8
and restarts t&e retransmission timer) T&e details o/ /unctions reset5rt*5
timer&III' and slo,do,n&III' will be discussed in Sects) 1,)8 and
1,)2* resecti1ely)
TCP Ta&oe reacts to a dulicated 4CK acket di//erently) !ines :H# in
Pro'ram 1,)1# are eAecuted only w&en all t&e ackets transmitted durin' t&is
acket loss &a1e been acknowled'ed) Here* 1ariable Frecover5G records t&e
&i'&est TCP seDuence number ?i)e)* Fma*se+5G@ transmitted durin' t&is acket
loss e1ent) !ine
: sets Frecover5G to be Fma*se+5G so t&at it can be used in t&e neAt acket
loss e1ent) T&e condition in !ine 3* (i$(est5ack5 K recover5* imlies
t&at
t&e TCP acket wit& &i'&est seDuence number transmitted durin' t&is re1ious
loss
must be acknowled'ed) I/ t&is condition is not satis/ied* t&e TCP sender will wait
/or timeout and retransmit t&e lost acket)
%:=6 Timer.Re#ate 4unctions
4not&er resonsibility o/ a TCP sender is to use a retransmission timer to ro1ide
connection reliability) T&e main comonents o/ t&is art include estimation o/
smoot&ed (TT ?round tri time@ and (TT 1ariation* comutation o/ (TO ?retrans9
mission timeout@* imlementation o/ +E+ ?binary eAonential backo//@* utiliJation
o/ a retransmission timer* and de/inin' actions to be er/ormed at timeout)
1D./.1 RTT Saple Collection
4 TCP sender needs to collect (TT samles to estimate smoot&ed (TT and (TT
1ariation* and to comute retransmission timeout ?(TO@ 1alue) 4n (TT samle is
measured as t&e time di//erence between t&e oint w&ere a acket is transmitted
and t&e oint w&ere t&e associated 4CK acket arri1es at t&e sender)
1,)8 Timer9(elated Cunctions 233
4ig= %:=/ T&e (TT samlin'
rocess
out6ut(se3noDreason)
du6ac1Caction()
,0'/9+ /),0'/9+
resetCrtxCtimer(mildD bac1off)
ne>ac1(61t) J
se3no @ rttCse3 C ='' Sam6le @
no> S rttCtsC
In NS2* eac& TCP sender &as only one set o/ 1ariables includin' 1ariables
rtt5active5* rtt5ts5* and rtt5se+5 ?see Table 1,)1@ to track (TT sam9
les) It can collect only one (TT samle at a time H meanin' not all t&e ackets
are used to collect (TT samles)
Ci'ure 1,): s&ows t&e dia'ram o/ t&e (TT collection rocess) T&e rocess
starts in t&e inacti1e state w&ere rtt5active5:0) T&e collection is acti1ated
?i)e)* t&e rocess enters t&e acti1e state@ w&en a TCP sender sends out a new
acket usin' /unction o!tp!t&se+no)reason') Crom Pro'ram 1,)13* !ine
33 sets Frtt5active5G to be 1)
"
!ines 32 and 3" record t&e TCP seDuence
number and t&e current time in t&e 1ariables Frtt5se+5G and rtt5ts5*
resecti1ely)
4n (TT samle is collected w&en t&e associated 4CK acket returns ?see !ines
12H1# o/ /unction ne,ack&pkt' in Pro'ram 1,)1"@) Li1en t&at t&e collection
rocess is acti1e ?i)e)* rtt5active5:2@* !ine 12 determines w&et&er t&e incom9
in' 4CK acket belon's to t&e same collectin' samle) It is so i/ t&e seDuence
number in t&e recei1ed 4CK acket is t&e same as t&at stored in Frtt5se+5G
?set at t&e be'innin' o/ t&e collectin' rocess@) Note t&at t&e lo'ical relation &ere
is FK:G rat&er t&an F::*G since some TCP 1ariants may not 'enerate an 4CK
acket /or e1ery recei1ed TCP acket) 4t t&e end o/ t&e collection rocess* !ine
12 sets Frtt5active5G to Jero indicatin' t&at t&e collectin' rocess &as
comleted ?i)e)* t&e rocess mo1es back to inacti1e state@* and !ine 1" takes an
(TT samle by in1okin' rtt5!pdate&no,Jrtt5ts5' ?de/ined in Pro'ram
1,)22@)
T&e abo1e (TT collection rocess oerates /airly well under normal situations)
Howe1er* a acket loss may in/late an (TT samle and a//ect t&e accuracy o/ (TO
collection rocess) In t&is case* t&e measured (TT would be t&e (TT 1alue lus
t&e time used to retransmit t&e lost ackets) To kee it simle* NS2 simly
cancels t&e (TT collection rocess w&en a acket loss occurs) In articular*
/unctions d!pack5action&' ?!ine " in Pro'ram 1,)1#@ and timeo!t&tno'
?!ines 1: and 18 in Pro'ram 1,)28@ in1oke /unction
reset5rt*5timer&III' to set Frtt5active5G to Jero* essentially
cancellin' t&e (TT collection rocess)
"
I/ t&e Frtt active G is nonJero* TCP sender will ski t&e collection rocess)
238 1, Transort Control Protocols Part 2< Transmission Control Protocol
1D./.2 RTT *stiation
4/ter collectin' an (TT samle* a TCP sender /eeds t&e samle FtaoG to /unction
rtt5!pdate&tao' to estimate smoot&ed (TT ?t5srtt5@* (TT 1ariation
?t5rttvar5@* and unbounded (TO ?t5rt*c!r5@
#
based on ?#)1@H?#)3@* w&ere
X . 2U"* Y . 3U:* and . 1) Instead o/ directly comutin' t&ese t&ree
1ariables* NS2 maniulates ?#)1@H?#)3@ suc& t&at eac& term in t&ese eDuations is
multilied wit& 2
n
* w&ere n is an inte'er) 4s discussed in Sect) 13):)2*
multilication and di1ision by 2
n
can be imlemented in CCC by s&i/tin' a
binary 1alue to t&e le/t and ri'&t* resecti1ely* by n bits) T&is bit s&i/tin'
tec&niDue is used in /unction rtt5!pdate&tao' to comute Ft5srtt5*G
Ft5rttvar5*G and Ft5rt*c!r5)G
4t time k* let t )k$ be t&e (TT samle* t )k$ be t&e smoot&ed (TT 1alue*
t
)k$
be t&e (TT 1ariation* and re/er to t )k C 1$ t )k$) Crom ?#)1@ to ?#)3@*
1
t )k C 1$ .
"

2t )k$ C t )k C 1$
1

.
"
2t )k$ C t )k$ C t )k C 1$ t )k$
1

.
"
"t)k$ C
1
?1,)1@

t
)k C 1$ .
:
)3
t
)k$ C B B$
1
.
:
)3
t
)k$ :
t
)k$ C :
t
)k$ C B B$
1
.
:
)
t
)k$ C :
t
)k$ C B B$ ?1,)2@
(TO
u
)k C 1$ . Qt )k C 1$ C :
t
)k C 1$ ?1,)3@
w&ere (TO
u
)k C 1$ is an unbounded (TO) EDuations ?1,)1@H?1,)3@ are now
rearran'ed so t&at all t&e multilicati1e /act are 2
n
O n . /,O 2O 3' ?i)e)* t&e multile
o/
1* :* and "@) NS2 uses bit s&i/tin' oeration in lace o/ multilication to imlement
?1,)1@H?1,)3@)
#
4n actual 1alue o/ (TO must be bounded by a minimum 1alue and a maAimum 1alue)
A t5rt*c!r5 : rt*c!r5init5;
B t5backo""5 : 2;
/ 8
Program %:=2: Cunction rtt init&' o/ class TcpA$ent* and de/ault 1alues
/or t&e timer9related 1ariables
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99rtt5init&'
1 7
3 t5rtt5 : 0;
= t5srtt5 : int&srtt5init5 M tcp5tick5' << T5S#TT5.ITS;
> t5rttvar5 : int&rttvar5init5 M tcp5tick5' << T5#TTSA#5
.ITS;
MMUMnsMtclMlibMnsJde"a!ltItcl
G A$entMTCP set T5S#TT5.ITS 3 Oin bits
20 A$entMTCP set T5#TTSA#5.ITS 1 Oin bits
22 A$entMTCP set srtt5init5 0 Oin seconds
21 A$entMTCP set rttvar5init5 21 Oin seconds
23 A$entMTCP set rt*c!r5init5 3I0 Oin seconds
2= A$entMTCP set T5S#TT5.ITS 3 Oin bits
2> A$entMTCP set T5#TTSA#5.ITS 1 Oin bits
2A A$entMTCP set rttvar5e*p5 1 Oin bits
2B A$entMTCP set tcp5tick5 0I2 Oin seconds
2/ A$entMTCP set ma*rto5 200000 Oin seconds
2G A$entMTCP set minrto5 0I1 Oin seconds
1D./." O#er#ie& of State
.aria-les
State o/ 1ariables contain t&e current status o/ a TCP a'ent) (elated timer state
1ariables are s&own in Tables 1,)1 and 1,)3) %ost o/ t&e 1ariables are well
eAlained by t&eir descritions) 6e now discuss a /ew oints related to t&ese
1ariables)
Cirst* CCC timer 1ariables are initialiJed in /unction rtt5init&' ?!ines 1H
" in Pro'ram 1,)2,@) OTcl timer inst1ars* on t&e ot&er &and* are initialiJed in
/ile
Tns$tcl$lib$ns9de/ault)tcl s&own in !ines #H1# o/ Pro'ram 1,)2,)
Second* Ftcp5tick5G is a simulation time unit ?i)e)* 'ranularity@ in seconds)
Herea/ter* we will re/er to a simulation time unit as a Ftick)G T&e de/ault 1alue o/
Ftcp5tick5G is 1,, ms) In ot&er words* one FtickG is set by de/ault to ,)1 ?see
!ine 12 in Pro'ram 1,)2,@)
T&ird* Ft5backo""5G is used as a binary eAonential backo// /actor ?i)e)* in
?1,)3@@) 4 TCP sender doubles its retransmission timer /or e1ery timeout e1ent)
In NS2* a TCP sender doubles Ft5backo""5G /or e1ery timeout e1ent and
comutes t&e unbounded (TO as Ft5rt*c!r5
N
t5backo""5G ?see !ine 2
in Pro'ram 1,)23@)
Cinally* t&ere are two main oints related to 1ariables Ft5srtt5G and
Ft5rttvar5)G One is t&at t&ese 1ariables are stored in Fticks*G rat&er t&an
seconds) Howe1er* t&eir initial 1alues are in seconds) !ines : and 3 in Pro'ram
1,)2, di1ide
23" 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=2% Class #t*Timer and related
comonents
MMUMnsMtcpMtcpI(
2 class #t*Timer 9 p!blic TimerHandler 7
1 p!blic9
3 #t*Timer&TcpA$ent
N
a' 9 TimerHandler&' 7 a5 : a; 8
= protected9
> virt!al void e*pire&Event
N
e';
A TcpA$ent
N
a5;
B 8;
MMUMnsMtcpMtcpIcc
/ void #t*Timer99e*pire&Event
N
'
G 7
20 a5JKtimeo!t&TCP5TI%E#5#TL';
22 8
21 void TcpA$ent99set5rt*5timer&'
23 7
2= rt*5timer5Iresc(ed&rtt5timeo!t&'';
2> 8
t&e initial 1alues o/ smoot&ed (TT and (TT 1ariation by Ftcp5tick5G to obtain
t&e time in FticksG ?rat&er t&an in seconds@) 4not&er oint is about t&e di1ision
oeration ?by " and :* resecti1ely@) To a1oid round9o// error durin' a di1ision*
t&ese two 1ariables are multilied by " and :* resecti1ely* at t&e initialiJation)
4'ain* !ines : and 3 in Pro'ram 1,)2, s&i/t Ft5srtt5G and Ft5rttvar5G to
t&e le/t by T5S#TT5.ITS:3 bits and T5#TTSA#5.ITS : 1 bits*
resecti1ely) T&is bit s&i/tin' is eDui1alent to multilyin' " and : to Ft5srtt5G
and Ft5rttvar5*G resecti1ely)
1D./.$ Retransission Tier
4 TCP sender uses a retransmission timer to ro1ide end9to9end reliability) 6&en
transmittin' a acket* it starts a retransmission timer) 0on t&e timer eAiration*
t&e timer in/orms t&e TCP sender o/ a acket timeout) Here t&e TCP sender
assumes t&at t&e acket is lost and retransmits t&e lost acket) I/ an 4CK acket is
recei1ed be/ore t&e timeout* t&e timer will be stoed ?i)e)* cancelled@) T&e details
o/ NS2 timer imlementation is 'i1en in Sect) 13)1)
NS2 models retransmission timers usin' a CCC class #t*Timer s&own in
Pro'ram 1,)21) .eri1ed /rom class TimerHandler* class #t*Timer &as one
1ariable Fa5G w&ic& is a ointer to a TcpA$ent obBect) It deri1es t&ree main
/unctions< sc(ed&delay'* resc(ed&delay'* and cancel&') It o1errides
one /unction e*pire&e' o/ class TimerHandler) Cunction sc(ed&delay'
starts t&e timer and sets t&e timer to eAire at FdelayG seconds in /uture) Cunction
1,)8 Timer9(elated Cunctions 23#
cancel&' stos t&e endin' timer) Cunction resc(ed&delay' restarts
t&e timer and a'ain sets t&e timer to eAire at FdelayG seconds in /uture) Cinally*
/unction e*pire&e' de/ines a set o/ actions w&ic& are taken at t&e timer
eAiration)
NS2 creates a two9way connection between TcpA$ent and #t*Timer
obBects usin' t&e /ollowin' mec&anism) Cirst* class TcpA$ent declares an
#t*Timer obBect ?rt*5timer5 in !ine : in Pro'ram 1,)3@ as its member
1ariable) E1ery TcpA$ent obBect t&ere/ore &as a direct access to an #t*Timer
obBect) Second* on t&e re1erse direction* class #t*Timer declares a ointer Fa5G
to a TcpA$ent obBect in !ine 8 o/ Pro'ram 1,)21 as its member 1ariable)
Cinally* a TcpA$ent ob9 Bect is seci/ied as a tar'et o/ t&e ointer Fa5G in t&e
constructor o/ t&e #t*Timer obBect) Crom !ine 2 in Pro'ram 1,)3* t&e
constructor o/ class TcpA$ent creates a Frt*5timer5G by /eedin' Ft(isG
?i)e)* a ointer to itsel/@ as an inut ar'ument) Crom !ine 3 in Pro'ram 1,)21* t&e
constructor o/ Frt*5timer5G stores Ft(isG in its 1ariable Fa5*G creatin' a
connection /rom t&e Frt*5timer5G back to t&e TcpA$ent obBect)
Note t&at in !ine : in Pro'ram 1,)3* a TCP sender &as only one retransmission
timer) T&ere/ore* t&e TCP timeout mec&anism alies to only one acket at a time)
T&e retransmission timer is started w&en a new acket is transmitted ?by /unction
o!tp!t&III'O see !ine :" in Pro'ram 1,)13@) Here* t&e timer is not allowed to
start i/ it is in use ?i)e)* its status is TI%E#5PENDIN-@) T&is is in contrast to t&e
actual TCP imlementation w&ere retransmission timers are set /or all transmitted
ackets)
1D./.+ 5!nction O#er#ie&
Class TcpA$ent ro1ides t&e /ollowin' se1en key timer9related
/unctions<
rtt5!pdate&tao'< Takes an (TT samle FtaoG as an inut ar'ument* u9
dates smoot&ed (TT ?t5srtt5@* (TT 1ariation ?t5rttvar5@* and
unbounded (TO ?t5rt*c!r5@ accordin' to ?1,)1@* ?1,)2@* and ?1,)3@*
resecti1ely)
rtt5timeo!t&'< Comutes t&e bounded (TO 1alue based on t5rt*c!r5*
minrto5* and ma*rto5* as well as TCP binary eAonential backo// ?+E+@
mec&anism w&ic& make use o/ t&e current 1alue o/ t5backo""5)
rtt5backo""&'< .ouble t&e binary eAonential backo// multilicati1e /actor
t5backo""5)
set5rt*5timer&'< (estart t&e retransmission timer)
reset5rt*5timer&mild)backo""'< (estart t&e retransmission timer
and
cancel t&e (TT samle collectin' rocess) I/ FmildG is Jero* set t5se+no5 to
(i$(est5ack542) 4lso* in1oke /unction rtt5backo""&' i/ Fbacko""G
is nonJero)
28, 1, Transort Control Protocols Part 2< Transmission Control Protocol
ne,timer&pkt'< Take an 4CK acket FpktG as an inut ar'ument) Start t&e
retransmission timer i/ TCP connection is acti1e)
1,
Cancel t&e timer* ot&erwise)
timeo!t&tno'< I/ t&e connection is acti1e* close t&e con'estion window*
adBust Ft5backo""5*G retransmit t&e lost acket* and restart t&e
retransmission timer) Ot&erwise* restart t&e retransmission timer ?but does not
er/orm ot&er action@)
11
1D././ 5!nction rtt
u%date)tao*
Cunction rtt5!pdate&tao' udates t&ree main timer 1ariables< smoot&ed
(TT ?t5srtt5@* (TT 1ariation ?t5rttvar5@* and (etransmission TimeOut
?(TOO t5rt*c!r5@) S&own in Pro'ram 1,)22* /unction rtt5!pdate&tao'
takes an (TT samle as an inut ar'ument) It is in1oked /rom wit&in /unction
ne,ack&pkt'* w&en a new 4CK acket is recei1ed and a new (TT samle is
no, J rtt5ts5 ?see !ine 1" in Pro'ram 1,)1"@)
Cunction rtt5!pdate&tao' ali'ns t&e inut ar'ument FtaoG wit& Ftcp5
tick5G and stores t&e ali'ned 1alued in 1ariable Ft5rtt5G as t&e latest (TT
sam9 le ?!ines :H8@) +e/ore roceedin' /urt&er* let us de/ine t&e
/ollowin' 1ariables
t .

t
.
t srtt
"
. t srtt KKT S#TT .ITS
?1,):@
t rttvar
:
. t rttvar KKT #TTSA# .ITS
?1,)3@
. t rtt t . t rtt )t srtt KKT S#TT .ITS$
?1,)8@
w&ere T5S#TT5.ITS and T5#TTSA#5.ITS* are de/ined in Pro'ram 1,)2, as
3 and 2* resecti1ely) 4'ain* 1ariables Ft5srtt5G and Ft5rttvar5G are
stored in multiles o/ " and : ?see !ines : and 3 in Pro'ram 1,)2,@) T&ere/ore*
t&eir relations&i to actual smoot&ed (TT ?t @ and (TT 1ariation ?
t
@ is 'i1en by
?1,):@ and ?1,)3@* resecti1ely)
+ased on t&e abo1e 1ariables* !ines "H13 comute t&e smoot&ed (TT 1alue)
In ?1,)1@ and ?1,)2@* we rearran'e t&e 1ariables Ft5srtt5G and Ft5rttvar5G
as /ollows<
1,
4 TCP connection is said to be acti1e and idle w&en it &as data to transmit and does not &a1e
data to transmit* resecti1ely)
11
4s we will see* a retransmission timer does not sto w&en a TCP connection becomes idle) 4t
t&e eAiration* a TCP sender does not&in' but restarts t&e timer) +y keein' t&e timer runnin'*
1,)8 Timer9(elated Cunctions 281
t&e timer will be a1ailable as soon as t&e TCP sender becomes acti1e)
Program %:=22 Cunction rtt !pdate o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99rtt5!pdate&do!ble tao'
1 7
3 do!ble no, : Sc(ed!ler99instance&'Iclock&';
= do!ble ticko"" : "mod&no,Jtao4boot5time5) tcp5tick5';
> i" &&t5rtt5 : int&&tao 4 ticko""' M tcp5tick5'<2';
A t5rtt5 : 2;
B i" &t5srtt5 C: 0' 7
/ re$ister s(ort delta : t5rtt5 J &t5srtt5 KK
T5S#TT5.ITS';
G i" &&t5srtt5 4: delta' <: 0'
20 t5srtt5 : 2;
22 i" &delta < 0'
21 delta : Jdelta;
23 delta J: &t5rttvar5 KK T5#TTSA#5.ITS';
2= i" &&t5rttvar5 4: delta' <: 0'
2> t5rttvar5 : 2;
2A 8 else 7
2B t5srtt5 : t5rtt5 << T5S#TT5.ITS;
2/ t5rttvar5 : t5rtt5 << &T5#TTSA#5.ITSJ2';
2G 8
10 t5rt*c!r5 : &&&t5rttvar5 << &rttvar5e*p5 4 &T5S#TT5
.ITS J T5#TTSA#5.ITS''' 4 t5srtt5' KK T5S#TT5.ITS '
N
tcp5tick5;
12 ret!rn;
11 8
t srtt )k C 1$ . "t )k C 1$ . "t )k$ C )k$ . t srtt )k$ C )k$
?1,)2@
t rttvar )k C 1$ . :
t
)k C 1$ . B B
t
)k$ C :
t
)k$
. B B Qt rttvar &k'KKT S#TT .ITS
C t rttvar )k$< ?1,)"@
In Pro'ram 1,)22* !ine " comutes FdeltaG ?i)e)* @ as indicated in ?1,)8@)
!ine
# udates Ft5srtt5G accordin' to ?1,)2@ and !ines 11 and 12 comute B B) !ines
13 and 1: udate Ft5rttvar5G accordin' to ?1,)"@) Crom !ines #H1, and 1:H13*
bot& Ft5srtt5G and Ft5rttvar5G will be set to 1* i/ t&eir udated 1alues are
less
t&an Jero) 4lso* !ines "H13 are in1oked w&en Ft5srtt5G is nonJero only) 6&en
Ft5srtt5G is Jero* Ft5srtt5G and Ft5rttvar5G are simly set to " times
?!ine 12@ and twice o/ ?!ine 1"@ t&e (TT samle ?i)e)* Ft5rtt5G@* resecti1ely)
NS2 comutes ?usin' ?1,)3@@ and stores t&e unbounded 1alue o/ (TO in 1ariable
Ft5rt*c!r5G ?!ine 2,@) It is comuted as t C :
t
s&own in ?#)3@) T&e uer9
bound and t&e lower9bound in ?#)3@ will be imlemented w&en an unbounded (TO
1,)8 Timer9(elated Cunctions 283
is assi'ned to t&e retransmission timer ?e)')* in /unction rtt5timeo!t&'@) T&e
comutation o/ Ft5rt*c!r5G in !ine 2, consists o/ /our stes<
?i@ Scale Ft5rttvar5G< 7ariables Ft5srtt5G and Ft5rttvar5G are stored
as multiles o/ 2
T S#TT .ITS
. " and 2
T #TTSA# .ITS
. :* resecti1ely) !ine
2, con1erts t&e scale o/ Ft5rtt5var5G into t&e same scale o/ Ft5srtt5G
as /ollows<
"
t rttvar W t rttvar
:
. t rttvar KKT #TTSA# .ITS<<T S#TT .ITS
. t rttvar <<)T S#TT .ITS T #TTSA# .ITS$
?ii@ %ultily 2
rttvar e*p
. 2
2
. : to t&e 1alue obtained /rom Ste ?i@) .enote
t&e result /rom Ste ?i@ as Ft5rtt5var5G
)1$
) See t&e de/ault 1alue o/
rttvar5e*p5 in !ine 18 o/ ro'ram 1,)2,)
t rttvar
)1$
W : t rttvar
)1$
. t rttvar
)1$
<<rttvar
e*p
?iii@ .enote t&e 1alue comuted in Ste ?ii@ be t5rtt5var5
)2$
) 4dd
t5srtt5 to t5rtt5var5
)2$
)
t rttvar
)2$
W t rttvar
)2$
C t srtt
?i1@ Con1ert t&e comuted 1alue to seconds< !et t5rtt5var5
)3$
be t&e 1alue
comuted in Ste ?iii@) T&is 1alue is stored in ticks and is in t&e scale o/
t5srtt5 ?i)e)* multile o/ "@) To c&an'e t&e unit o/ t5rtt5var5
)3$
to
seconds*
t rttvar
)3$
W t rttvar
)3$
KKT S#TT .ITS
N
tcp
tick
w&ic& is eDui1alent to !ine 2, in Pro'ram 1,)22)
1D./.4 5!nction rtt
timeout)*
S&own in Pro'ram 1,)23* /unction rtt5timeo!t&' comutes t&e bounded
(TO* based on unbounded (TO ?t5rt*c!r5@* (TO lower bound ?minrto5@*
(TO uer bound ?ma*rto5@* and TCP binary eAonential backo// ?+E+@
mec&anism) NS2 imlements t&e +E+ mec&anism usin' a multilicati1e /actor
Ft5backo""5)G T&e timeout 1alue* w&ic& is used by t&e retransmission timer* is
a roduct o/ Ft5rt*c!r5G and Ft5backo""5G ?see !ine 2@) T&e lower bound
and t&e uer9 bound are imlemented in !ines :H3 and !ines "H#* resecti1ely)
282 1, Transort Control Protocols Part 2< Transmission Control Protocol
Note t&at w&ile
1,)8 Timer9(elated Cunctions 283
Program %:=2* Cunctions rtt timeo!t and rtt backo"" o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 do!ble TcpA$ent99rtt5timeo!t&'
1 7
3 do!ble timeo!t;
= i" &t5rt*c!r5 < minrto5'
> timeo!t : minrto5
N
t5backo""5;
A else
B timeo!t : t5rt*c!r5
N
t5backo""5;
/ i" &timeo!t K ma*rto5'
G timeo!t : ma*rto5;
20 i" &timeo!t < 1I0
N
tcp5tick5'
22 timeo!t : 1I0
N
tcp5tick5;
21 ret!rn &timeo!t';
23 8
2= void TcpA$ent99rtt5backo""&'
2> 7
2A i" &t5backo""5 < A='
2B t5backo""5 <<: 2;
2/ i" &t5backo""5 K /' 7
2G t5rttvar5 4: &t5srtt5 KK T5S#TT5.ITS';
10 t5srtt5 : 0;
12 8
11 8
t&e lower9bound alies to t5rt*c!r5 be/ore alyin' t&e +E+ mec&anism*
t&e uer bound does so a/ter t&e +E+) Hence* !ines 1,H11 lace anot&er lower9
bound constraint ?i)e)* 1I0
N
tcp5tick5@ /or t&e 1alue a/ter t&e +E+)
1D./.? 5!nction rtt
backoff)*
Cunction rtt5backo""&' alies TCP binary eAonential backo// ?+E+@
mec&9 anism to a multilicati1e /actor Ft5backo""5)G 4s discussed in
Sect) #)1)2* Ft5backo""5G is doubled /or e1ery timeout and is reset to its initial
1alue w&en a new 4CK acket is recei1ed) 4s we will see* /unction
rtt5backo""&' is in1oked by /unction
reset5rt*5timer&mild)backo""'to double Ft5backo""5)G Pro'ram
1,)23 s&ows t&e details o/ /unction rtt5backo""&') I/ t&e current
Ft5backo""5G is less t&an 8: ?!ine 18@* it will be doubled ?i)e)* s&i/ted to t&e
le/t by one bit in !ine 12@) 4lso* a lar'e 1alue o/ Ft5backo""5G ?e)')* [ " in
!ine 1"@ imlies a lon' inter1al between two (TT samles) In t&is case* smoot&ed
(TT and (TT 1ariation may not well reresent t&e actual network (TT) In t&is
case* (TT s&ould be a /unction o/ t&e most recent (TT samle only) T&ere/ore*
!ine 2, sets Ft5srtt5G to Jero) 4/ter t&is oint* /unction rtt5!pdate&tao'
will in1oke !ines 12 and 1" ?rat&er t&an !ines "H13@ in Pro'ram 1,)22 to estimate
network (TT)
28: 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=2/ Cunction reset rt* timer o/ class TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99reset5rt*5timer&int mild) int backo""'
1 7
3 i" &backo""'
= rtt5backo""&';
> set5rt*5timer&';
A i" &Cmild'
B t5se+no5 : (i$(est5ack5 4 2;
/ rtt5active5 : 0;
G 8
1D./.@ 5!nction set rt, timer)* and
5!nction
reset rt, timer)
mild+backoff*
Pro'rams 1,)21 and 1,)2: s&ow t&e details o/ /unctions set5rt*5timer&'
and reset5rt*5timer&mild)backo""'* resecti1ely) Crom !ine 1: in
Pro'ram 1,)21* /unction set5rt*5timer&' simly sets t&e timer to eAire
at t seconds in /uture* w&ere t is t&e timeout 1alue returned /rom /unction
rtt5timeo!t&' ?see also Pro'ram 1,)23@)
Crom Pro'ram 1,)2:* /unction reset5rt*5timer&mild)backo""' &as
/our main tasks<
1) (estart t&e retransmission timer ?!ine 3@
2) 0date t&e backo// multilicati1e /actor Ft5backo""5*G i/ t&e inut ar'ument
Fbacko""G is nonJero ?!ines 3 and :@
3) 0date t&e neAt transmittin' seDuence number) Store (i$(est5ack542 in
Ft5se+no5*G i/ t&e inut ar'ument FmildG is Jero ?!ines 8 and 2@
:) Cancel t&e endin' (TT samle collection rocess by settin'
Frtt5active5G
to Jero ?!ine "@)
1D./.1D 5!nction ne.timer)%kt*
Cunction ne,timer&pkt' is in1oked /rom wit&in /unction ne,ack&pkt'
w&en a new 4CK acket is recei1ed and t&e TCP sender is about to send out
anot&er acket) 4s s&own in Pro'ram 1,)23* it takes a ointer pkt to an 4CK
acket as an inut ar'ument) I/ t&e TCP sender still &as data to transmit ?i)e)*
!ine : returns tr!e@* !ine 3 will restart t&e retransmission timer by in1ok9
in' set5rt*5timer&') Ot&erwise* !ine 2 will cancel t&e timer by in1okin'
cancel5rt*5timer&')
1,)8 Timer9(elated Cunctions 283
Program %:=20 Cunction ne,timer o/ class
TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99ne,timer&Packet
N
pkt'
1 7
3 (dr5tcp
N
tcp( : (dr5tcp99access&pkt';
= i" &t5se+no5 K tcp(JKse+no&' XX tcp(JKse+no&' < ma*se+5'
> set5rt*5timer&';
A else
B cancel5rt*5timer&';
/ 8
1D./.11 5!nction timeout)tno*
Cunction timeo!t&tno' is in1oked w&en a retransmission timer eAires) It
adBusts con'estion window as well as slow9start t&res&old* and retransmits t&e lost
acket) 4'ain* /unction e*pire&e' is in1oked w&en t&e timer eAires) Crom
!ine
1, in Pro'ram 1,)21* /unction e*pire&e' o/ class #t*Timer simly
in1okes
/unction timeo!t&TCP5TI%E#5#TL' o/ t&e associated TcpA$ent obBect)
4s
s&own in !ines 1H1# o/ Pro'ram 1,)28* /unction timeo!t&tno' takes a timer
otion ?tno@ as an inut ar'ument* w&ere t&e ossible 1alues o/ FtnoG are
de/ined
in !ines 2,H23 o/ Pro'ram 1,)28) In t&is section* we are interested in TCP Ta&oe)
T&ere/ore* we will discuss t&e case w&ere only timeo!t&TCP5TI%E#5#TL'
is in1oked)
T&e basic oeration o/ /unction timeo!t&tno' is to close t&e con'es9
tion window ?!ine 1,@* restart t&e retransmission timer ?!ines 1: and 18@* and
retransmit t&e lost acket ?!ine 1"@) 6e will discuss t&e details o/ /unction
slo,do,n&III' w&ic& closes t&e con'estion window in Sect) 1,)2) T&e re9
transmission timer is restarted usin' t&e /unction reset5rt*5timer&mild)
backo""' ?see Pro'ram 1,)2:@) Cor Jero 1alue o/ Fmild*G t&is /unction sets
Ft5se+no5G to F(i$(est5ack542G) T&e non Jero and Jero 1alues o/ t&e sec9
ond inut ar'ument Fbacko""G in/orm /unction reset5rt*5timer&mild)
backo""' to and not to ?resecti1ely@ udate t&e binary eAonential backo//
multilicati1e /actor ?t5backo""5@) 4'ain* t&e TCP sender assumes t&at all
ackets wit& seDuence number lower t&an F(i$(est5ack5G are success/ully
transmitted) 4t a timeout e1ent* it assumes t&at t&e /irst lost acket ?i)e)* t&e acket
to be retransmitted@ is t&e acket wit& seDuence number (i$(est5ack542)
4/ter rearin' Ft5se+no5G ?i)e)* set to (i$(est5ack542@ /or retransmission*
!ine 1" eAecutes send5m!c(&0) TCP5#EASON5TI%EODT) ma*b!rst5'
to transmit t&e lost acket)
4/ter a TCP sender transmits all t&e ackets ro1ided by an attac&ed a9
lication* its 1ariable Ft5se+no5G is eDual to 1ariable Fc!rse+5*G and 1ari9
able Fma*se+5G stos increasin') 4/ter t&e last acket ?wit& seDuence number
Fma*se+5G@ is acknowled'ed* 1ariable F(i$(est5ack5G is eDual to
28: 1, Transort Control Protocols Part 2< Transmission Control Protocol
Fma*se+5)G 4t t&is oint* t&e TCP sender enters an idle state) Its retransmission
1,)2 6indow 4dBustment Cunctions 282
Program %:=26 Cunction timeo!t o/ class TcpA$ent and t&e ossible 1alues
o/ its inut ar'ument FtnoG
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99timeo!t&int tno'
1 7
III
3 i" &c,nd5 < 2' c,nd5 : 2;
= i" &(i$(est5ack5 :: ma*se+5 FF Cslo,5start5restart5' 7
> 8 else 7
A recover5 : ma*se+5;
B i" &(i$(est5ack5 < ma*se+5' 7
/ 44nre*mit5;
G last5c,nd5action5 : CWND5ACTION5TI%EODT;
20 slo,do,n&CLOSE5SSTH#ESH5HALQXCLOSE5CWND5#ESTA#T';
22 8
21 8
23 i" &(i$(est5ack5 :: ma*se+5'
2= reset5rt*5timer&0)0';
2> else
2A reset5rt*5timer&0)2';
2B last5c,nd5action5 : CWND5ACTION5TI%EODT;
2/ send5m!c(&0) TCP5#EASON5TI%EODT) ma*b!rst5';
2G 8
MMUMnsMtcpMtcpI(
10 Ode"ine TCP5TI%E#5#TL 0
12 Ode"ine TCP5TI%E#5DELSND 2
11 Ode"ine TCP5TI%E#5.D#STSND 1
13 Ode"ine TCP5TI%E#5DELACV 3
1= Ode"ine TCP5TI%E#5 =
1> Ode"ine TCP5TI%E#5#ESET >
timer* &owe1er* does not sto at t&is moment) It kees eAirin' /or e1ery eriod
o/ (TO) Crom !ine 1: o/ Pro'ram 1,)28* /unction timeo!t&tno' will in1oke
reset5rt*5timer&0)0'* w&ic& stores t&e 1alue o/ (i$(est5ack542 in
1ariable Ft5se+no5G but does not c&an'e t&e multilicati1e /actor
Ft5backo""5)G 4lso* /unction send5m!c(&0) TCP5#EASON5TI%EODT)
ma*b!rst5' will not send out any acket since Ft5se+no5G is not less t&an
Fc!rse+5G ?see Pro'ram 1,)11@)
6&en t&e alication sends more user demand ?i)e)* data ayload@ by in1okin'
sendms$&nbytes'* 1ariable Fc!rse+5G is incremented and t&e TCP connec9
tion becomes acti1e) In t&is case* /unction send5m!c(&0)0)ma*b!rst5'
will send out ackets* startin' wit& t&e acket wit& seDuence number
t5se+no5: ma*5se+542 : (i$(est5ack5 4 2)
T&ere are two imortant details in /unction timeo!t&tno') One is t&at
re'ard9 less o/ w&et&er connection is busy or idle* !ine 12 sets t&e 1ariable
Flast5c,nd5 action5G w&ic& records t&e latest action imosed on t&e
con'estion window to be CWND5ACTION5TI%EODT) 4not&er is related to
1ariable Frecover5)G (ecall
288 1, Transort Control Protocols Part 2< Transmission Control Protocol
t&at Frecover5G contains t&e &i'&est seDuence number amon' all t&e
transmitted TCP ackets at t&e latest loss e1ent ?i)e)* eit&er timeout or Cast
(etransmit@) !ine 8 &ence records t&e &i'&est TCP seDuence number transmitted
so /ar in t&e 1ariable Frecover5)G
%:=5 Winow A1ustment 4unctions
Crom Sect) #)1)2* a TCP sender dynamically adBusts con'estion window to /ully
use t&e network resource) 6&en t&e network is underutiliJed* a TCP sender
increases transort9le1el transmission rate by oenin' t&e con'estion window)
In t&e slow9start &ase* w&ere t&e con'estion window ?c,nd5@ is less t&an
t&e slow9start t&res&old ?sst(res(5@* a TCP sender increases t&e con'estion
window by one /or e1ery recei1ed 4CK acket) I/ Fc,nd5G is not less t&an
Fsst(res(5*G on t&e ot&er &and* a TCP sender will be in t&e con'estion
a1oidance &ase* and t&e con'estion window is increased by 2Mc,nd5 /or e1ery
recei1ed 4CK acket)
6&en t&e network is con'ested* a TCP sender closes t&e con'estion window to
&el relie1e network con'estion) 4s discussed in Sect) #)1)2* TCP may decrease
t&e window by &al/ or may reset t&e con'estion window siJe to one* deendin' on
t&e situation)
Class TcpA$ent ro1ides two main /unctions* w&ic& can be used to adBust
t&e con'estion window<
openc,nd&'< Increases t&e siJe o/ t&e con'estion window) T&e increasin'
met&od deends on Fc,nd5G and Fsst(res(5)G
slo,do,n&(o,'< .ecreases t&e siJe o/ t&e con'estion window by t&e
met&od seci/ied in F(o,)G
T&e ossible 1alues o/ F(o,G are de/ined in Pro'ram 1,)22) 4ll ossible 1alues
o/ F(o,G contain 32 bits* and con/orm to t&e /ollowin' /ormat< 1 o/ FoneG bit
and 31 o/ FJeroG bits) T&e di//erence amon' t&e 1alues de/ined in Pro'ram 1,)22
lies in t&e osition o/ t&e FoneG bit) T&is /ormat acts as a simle identi/ication
o/ t&e inut met&od F(o,G t&rou'& an F4N.G oerator) Cor eAamle* suose
t&e inut ar'ument F(o,G is set to CLOSE5CWND5ONE ?.2@) !et F*G be a
1ariable w&ic& can be any 1alue in Pro'ram 1,)22) T&en* (o, F * would be
nonJero i/ and only i/ *:CLOSE5CWND5ONE) T&is assi'nment is also able to
contain se1eral Fslo,do,nG met&ods in one 1ariable usin' an FO(G oera9
tor) Cor eAamle* let F(o,G be CLOSE5CWND5ONEXCLOSE5SSTH#ESH5HALQ)
T&en* (o, F * would be nonJero i/ and only i/ *:CLOSE5CWND5ONE or
*:CLOSE5SSTH#ESH5 HALQ)
1,)2 6indow 4dBustment Cunctions 28#
Program %:=25 Possible 1alues o/ F(o,G H t&e inut ar'ument o/ /unction
Fslo,do,nG
MMUMnsMtcpMtcpI(
2 Ode"ine CLOSE5SSTH#ESH5HALQ 0*00000002
1 Ode"ine CLOSE5CWND5HALQ 0*00000001
3 Ode"ine CLOSE5CWND5#ESTA#T 0*0000000=
= Ode"ine CLOSE5CWND5INIT 0*0000000/
> Ode"ine CLOSE5CWND5ONE 0*00000020
A Ode"ine CLOSE5SSTH#ESH5HALSE 0*00000010
B Ode"ine CLOSE5CWND5HALSE 0*000000=0
/ Ode"ine TH#EE5DA#TE#5SSTH#ESH 0*000000/0
G Ode"ine CLOSE5CWND5HALQ5WA[ 0*00000200
20 Ode"ine CWND5HALQ5WITH5%IN 0*00000100
22 Ode"ine TCP5IDLE 0*00000=00
21 Ode"ine NO5ODTSTANDIN-5DATA 0*00000/00
Program %:=27 Cunction openc,nd o/ class TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99openc,nd&'
1 7
3 i" &c,nd5 < sst(res(5' 7
= c,nd5 4: 2;
> 8 else 7
A do!ble increment : increase5n!m5 M c,nd5;
B c,nd5 4: increment;
/ 8
G i" &ma*c,nd5 FF &int&c,nd5' K ma*c,nd5''
20 c,nd5 : ma*c,nd5;
22 8
1D.4.1 5!nction o%enc.nd)*
Cunction openc,nd&' is in1oked w&en a new 4CK acket is recei1ed ?see
/unction recv5ne,ack5(elper&' in !ine 3 o/ Pro'ram 1,)18@) It oens
t&e con'estion window and allows t&e TCP sender to transmit more ackets
wit&out waitin' /or acknowled'ement) Pro'ram 1,)2" s&ows t&e details o/
/unction openc,nd&') Crom !ine 3* i/ Fc,nd5G is less t&an Fsst(res(5*G
t&e TCP sender will be in t&e slow9start &ase and Fc,nd5G will be increased by
2) Ot&erwise* t&e TCP sender must be in a con'estion a1oidance &ase* and
Fc,nd5G will be increased by 2Mc,nd5 ?!ines 8 and 2@* w&ere
Fincrease5n!m5G is usually set to 1) In bot& cases* !ines # and 1, bound
Fc,nd5G wit&in Fma*c,nd5*G t&e rede/ined maAimum con'estion window siJe)
28" 1, Transort Control Protocols Part 2< Transmission Control Protocol
Program %:=28 Cunction Fslo,do,nG o/ class TcpA$ent
MMUMnsMtcpMtcpIcc
2 void TcpA$ent99slo,do,n&int (o,'
1 7
3 do!ble ,in) (al",in) decrease,in;
= int slo,start : 0;
> i" &c,nd5 < sst(res(5'
A slo,start : 2;
B (al",in : ,indo,d&' M 1; ,in : ,indo,d&';
/ decrease,in : decrease5n!m5
N
,indo,d&';
G i" &(o, F CLOSE5SSTH#ESH5HALQ'
20 i" &"irst5decrease5 :: 2XXslo,start XX
last5c,nd5action5 :: CWND5ACTION5TI%EODT'
22 sst(res(5 : &int' (al",in;
21 else
23 sst(res(5 : &int' decrease,in;
2= else i" &(o, F TH#EE5DA#TE#5SSTH#ESH'
2> i" &sst(res(5 < 3
N
c,nd5M=' sst(res(5 : &int'
&3
N
c,nd5M=';
2A i" &(o, F CLOSE5CWND5HALQ'
2B i" &"irst5decrease5::2XXslo,startXXdecrease5n!m5
::0I>'7
2/ c,nd5 : (al",in;
2G 8 else
10 c,nd5 : decrease,in;
12 else i" &(o, F CWND5HALQ5WITH5%IN' 7
11 c,nd5 : decrease,in;
13 i" &c,nd5 < 2' c,nd5 : 2;
1= 8 else i" &(o, F CLOSE5CWND5#ESTA#T' c,nd5:int&,nd5
restart5';
1> else i" &(o, F CLOSE5CWND5INIT' c,nd5 : int&,nd5init5';
1A else i" &(o, F CLOSE5CWND5ONE' c,nd5 : 2;
1B i" &sst(res(5 < 1' sst(res(5 : 1;
1/ i" &(o, F &CLOSE5CWND5HALQXCLOSE5CWND5#ESTA#TX
CLOSE5CWND5INITXCLOSE5CWND5ONE''
1G con$5action5 : T#DE;
30 i" &"irst5decrease5 :: 2' "irst5decrease5 : 0;
32 8
1D.4.2 5!nction slo.do.n)ho.*
Cunction slo,do,n&(o,' closes t&e con'estion window based on t&e met&od
seci/ied in t&e inut ar'ument F(o,)G It is in1oked /rom wit&in /unction
d!pack5 action&' and timeo!t&tno' to decrease transort layer
transmission rate) Cunction d!pack5action&' in1okes /unction
slo,do,n&(o,' /eedin' (o,
: CLOSE5SSTH#ESH5HALQ X CLOSE5CWND5ONE ?!ine 2 in Pro'ram
1,)1#@ as an inut ar'ument) Crom Pro'ram 1,)2#* t&is in1ocation &al1es t&e
current slow9 start t&res&old ?!ines #H13@ and resets t&e con'estion window to
1 ?!ine 28@)
22, 1, Transort Control Protocols Part 2< Transmission Control Protocol
Cunction timeo!t&tno'* on t&e ot&er &and* in1okes /unction
slo,do,n&(o,' wit& an inut ar'ument F(o,G :
CLOSE5SSTH#ESH5HALQ X CLOSE5CWND5 #ESTA#T as an inut
ar'ument ?!ine 1, in Pro'ram 1,)28@) Crom Pro'ram 1,)2#* t&is in1ocation &al1es
t&e current slow9start t&res&old ?!ines #H13@ and resets t&e con'estion window to
a redi/ined window9restart 1alue ?!ine 2:@) In bot& cases* NS2 uses an FO(G
oerator to combine &ow to adBust t&e slow9start t&res&old and &ow to adBust t&e
con'estion window* and /eed it as an inut ar'ument to /unction
slo,do,n&(o,')
T&e details o/ /unction slo,do,n&(o,' are s&own in Pro'ram 1,)2#) In
t&is /unction* !ines :H8 /irst set a 1ariable Fslo,startG to one and Jero
w&en TCP is in t&e slow9start &ase ?i)e)* c,nd5< sst(res(5@ and in t&e
con'estion a1oidance &ase ?i)e)* c,nd5K: sst(res(5@* resecti1ely) !ine
2 stores &al/ o/ t&e window siJe in a 1ariable F(al",inG and t&e window
siJe in a 1ariable F,in)G 7ariable Fdecrease5n!m5G in !ine " is set to
,)3 by de/ault) T&ere/ore* t&e local 1ariable Fdecrease,inG is &al/ o/ t&e
current con'estion window) T&e 1ariable Fdecrease5n!m5G ro1ides an o9
tion /or window decrement* w&ere di//erent TCP 1ariants may set t&e 1alue o/
decrease5n!m5 di//erently ?e)')* ,)3* ,)2@) !ines #H28 s&ow di//erent window
closin' met&od* w&ic& will be in1oked accordin' to t&e inut ar'ument F(o,)G
!ine 22 ensures t&at t&e minimum slow9start t&res&old is 2) !ine 2# sets t&e
1ariable Fcon$5action5G to be tr!e i/ t&e window adBustment met&od*
F(o,*G is eit&er o/ CLOSE5CWND5HALQ* CLOSE5CWND5#ESTA#T*
CLOSE5CWND5INIT* or CLOSE5CWND5ONE) 4'ain* t&e 1ariable
Fcon$5action5G is used in /unction o!tp!t&se+no)reason' to set t&e
con'estion /la' o/ t&e transmitted acket) Cinally* !ine 32 sets
F"irst5decrease5G to Jero* indicatin' TCP &as decreased t&e con'estion
window at least once)
!ines #H13 adBust t&e slow9start t&res&old ?sst(res(5@ based on t&e 1alue
o/ F(o,G<
CLOSE5SSTH#ESH5HALQ ?!ines 11 and 13@< Sets t&e slow9start t&res&old
Fsst(res(5G to t&e &al/ ?&al/win or decreasewin@ o/ t&e current con'estion
window siJe Fc,nd5)G
TH#EE5DA#TE#5SSTH#ESH ?!ine 13@< Sets t&e slow9start t&res&old
Fsst(res(5G to at least 3$: o/ its current 1alue)
Similarly* !ines 18H2# adBust t&e con'estion window ?c,nd5@ based on t&e
1alue o/ F(o,G<
CLOSE5CWND5HALQ ?!ines 12H2,@< .ecreases t&e current con'estion
window siJe ?i)e)* Fc,nd5G@ by &al/ ?F(al",inG Fdecrease,inG@)
CWND5HALQ5WITH5%IN ?!ines 22 and 23@< Sets t&e current con'estion
window siJe to Fdecrease,inG but not less t&an 1)
CLOSE5CWND5#ESTA#T ?!ine 2:@< Sets t&e current con'estion window siJe
to t&e redi/ined window9restart 1alue ,nd5restart5)
CLOSE5CWND5INIT ?!ine 23@< Sets t&e current con'estion window siJe to
F,nd5init5G ?i)e)* initial 1alue o/ con'estion window siJe@)
CLOSE5CWND5ONE ?!ine 28@< Sets t&e current con'estion window siJe to
1)
1,)# EAercises 221
%:=7 $ha&ter Summary
TCP is a reliable connection9oriented transort layer rotocol) It ro1ides a con9
nection wit& end9to9end error control and con'estion control) NS2 imlements
TCP senders and TCP recei1ers usin' CCC classes TcpA$ent and TcpSink*
w&ic& are bound to OTcl classes A$entMTCP and A$entMTCPSink*
resecti1ely) 4 TCP sender &as /our main resonsibilities) Cirst* based on user
demand* it creates and /orwards ackets to a TCP recei1er) Second* it ro1ides an
end9to9end connection wit& reliability by means o/ acket retransmission) T&ird* it
imlements timer9related comonents to estimate round tri time ?(TT@ and
retransmission timeout ?(TO@* used to determine w&et&er a acket is lost) Cinally*
it dynamically adBusts transort9le1el transmission rate to /ully use t&e network
resource wit&out causin' network con'estion) 4 TCP recei1er is resonsible /or
creatin' ?cumulati1e@ 4CK ackets and /orwards t&em back to t&e TCP sender)
%:=8 "<ercises
1) 6&ic& NS2 class is resonsible /or rocessin' and creatin' TCP acknowled'9
ment acketsR
a) 6&at are t&e names and tyes o/ 1ariables w&ic& store in/ormation about
recei1ed acketsR
b) 0on recei1in' a TCP acket* w&at is t&e number t&is class uts in t&e
acknowled'ment acketR EAlain t&e rocess) .raw a dia'ram i/ necessary)
c) 4t a certain moment* w&at is t&e maAimum number o/ TCP ackets t&at t&is
class needs to retain) How does NS2 en'ineer a data structure to kee t&is
in/ormation about t&ese acketsR
2) How does an alication tell TCP to start sendin' acketsR 6&en does TCP
sto sendin' acketsR
3) 6&at are t&e /unctions o/ class TcpA$ent related to acket transmissionR
6&at are t&eir di//erencesR
:) Crom wit&in w&ic& /unction does class TcpA$ent create a
acketR
3) 6&ic& met&od does TCP use to transmit ackets H immediate or delayed acket
transmissionR Crom wit&in w&ic& /unction does it transmit acketsR EAlain t&e
transmission rocess)
8) TCP usually transmits se1eral ackets wit&out acknowled'ment) Eac& acket
can be used to collect round9tri time samles) 6&at is t&e maAimum number
o/ round9tri time samles t&at a TCP a'ent can collect at a certain timeR 6&at
are t&e 1ariables t&at t&e TCP a'ent uses to collect t&ese samlesR
222 1, Transort Control Protocols Part 2< Transmission Control Protocol
2) 6&at is t&e urose o/ t&e 1ariable Ftcp5tickG o/ class TcpA$entR
") EAlain &ow NS2 comutes t&e smoot&ed round9tri time* round9tri time
1ariation* and instantaneous retransmission timeout) .iscuss t&e similarities$
di//erences wit& t&at recommended by M33N)
$ha&ter %%
A&&#ication2 9ser -eman 'nicator
Oeratin' on to o/ a transort layer a'ent* an alication models user demand /or
data transmission) 4 user is assumed to create bursts o/ data ayload or alication
ackets) T&ese ayload bursts are trans/ormed into transort layer ackets w&ic&
are t&en /orwarded to a transort layer recei1in' a'ent) 4lications can be
classi/ied into traffic generator and simulated application) 4 tra//ic 'enerator
creates user demand based on a rede/ined sc&edule) 4 simulated alication* on
t&e ot&er &and* creates t&e demand as i/ t&e alication is runnin')
In t&e /ollowin'* we /irst discuss t&e relations&i between an alication and a
transort layer a'ent in Sect) 11)1) Class Application is introduced in Sect)
11)2) Sections 11)3 and 11): discuss t&e detailed imlementation o/ tra//ic
'enerators and simulated alications* resecti1ely) Cinally* t&e c&ater summary
is 'i1en in Sect) 11)3)
%%=% Re#ationshi& Between an A&&#ication an a Trans&ort
+ayer Agent
Crom time to time* an alication needs to eAc&an'e user demand in/ormation wit&
a transort layer a'ent) 4n alication declares a ointer Fa$ent5G to an attac&ed
a'ent) Similarly* an a'ent de/ines a ointer Fapp5G to an attac&ed alication) T&e
user demand in/ormation is eAc&an'ed between an alication and an a'ent
t&rou'& t&ese two ointers) Section #)2)2 'i1es a /our9ste a'ent con/i'uration
met&od* w&ic& binds an alication and a transort layer a'ent to'et&er) T&e
details o/ t&ese /our stes are 'i1en below<
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 11* = Srin'er Science>+usiness %edia* !!C 2,12
223
11)1 (elations&i +etween an 4lication and a Transort !ayer 4'ent 223
Ste& %2 $reate a Sening Agent3 a Receiving Agent3 an an A&&#ication
4n a'ent and an alication can be created usin' instroc ne,/II' as /ollows<
set a$ent ?ne, A$entM<a$ent5typeK@
set app ?ne, ApplicationM<app5typeK@
w&ere <a$ent5typeK and <app5typeK denote t&e tye o/ an a'ent ?e)')*
TCP
or DDP@ and an alication ?e)')* Tra""icMC.# or QTP@*
resecti1ely)
Ste& 22 $onnect an Agent to an A&&#ication
4 two way connection between an alication and an a'ent can be created usin'
an
OTcl command o/ class Application w&ose syntaA is s&own
below<
Papp attac(Ja$ent Pa$ent
w&ere Papp and Pa$ent are Application and A$ent obBects) T&e
details o/ instroc attac(Japp/s5type' are s&own in Pro'ram 11)1) !ine 2
stores an inut A$ent obBect in t&e 1ariable Fa$ent5)G !ine 12 in1okes
/unction attac(App&t(is' o/ class A$ent* w&ile !ines 1#H22 create a
connection /rom t&e A$ent obBect to t&e Application obBect) Crom !ine
21* /unction attac(App&app' stores an inut Application obBect FappG
in t&e 1ariable Fapp5G o/ t&e A$ent obBect) Since !ine 12 /eeds t&e ointer
Ft(isG to /unction attac(App&III' o/ t&e Application obBect* it
simly sets t&e ointer a$ent5JKapp5 to oint to t&e Application
obBect)
Ste& *2 Attaching an Agent to a +ow.+eve#
Network
Here* we consider t&e case w&ere an a'ent is connected to a node in a low9le1el
network) 4s discussed in Sect) 8)3)3* an a'ent can be attac&ed to a node usin' t&e
instroc attac(Ja$ent/node a$ent' o/ class Sim!lator* w&ere FnodeG
and Fa$entG are t&e Node* and A$ent obBects* resecti1ely) T&is instroc
creates a two9way connection between a Node obBect FnodeG and an A$ent
obBect Fa$ent)G It sets 1ariable a$ent99tar$et5 to oint to FnodeG and
installs Fa$entG in t&e demultileAer ?i)e)* inst1ar dm!*5@ o/ Fnode)G
T&e rocess o/ attac&in' an a'ent to a node in1ol1es t&ree OTcl classes<
Sim!lator* Node* and #t%od!le) Ci'ure 11)1 s&ows t&e main oeration w&en
FPns attac(Ja$ent Pnode Pa$entG is eAecuted<
1) Instroc attac(Ja$ent/node a$ent' o/ class Sim!lator in1okes
Pnode attac( Pa$ent)
22: 11 4lication< 0ser .emand Indicator
Program %%=% 4n OTcl command attac(Ja$ent o/ class Application
and /unction attac(App o/ class A$ent
MMUMnsMappsMappIcc
2 int Application99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 TclF tcl : Tcl99instance&';
= III
> i" &ar$c :: 3' 7
A i" &strcmp&ar$v?2@) Hattac(Ja$entH' :: 0' 7
B a$ent5 : &A$ent
N
' TclObject99look!p&ar$v?1@';
/ i" &a$ent5 :: 0' 7
G tclIres!lt"&Hno s!c( a$ent EsH) ar$v?1@';
20 ret!rn&TCL5E##O#';
22 8
21 a$ent5JKattac(App&t(is';
23 ret!rn&TCL5OV';
2= 8
2> III
2A 8
2B ret!rn &Process99command&ar$c) ar$v'';
2/ 8
MMUMnsMcommonMa$entIcc
2G void A$ent99attac(App&Application
N
app'
10 7
12 app5 : app;
11 8
4ig= %%=% Internal
mec&anism o/ instroc
attac(Ja$ent/node
Class Simulator
Tns attach$a4ent Tnode Ta4ent
a$ent' o/ class
Sim!lator
(i)
Instproc attac!+a%ent -noe a%ent.
Tnode attach Ta4ent
Class Noe
(ii)
Instproc attac! -a%ent port.
$ set 6ort UTdmuxC alloc$6ort UUSimulator instanceV nulla4entVV
$ Ta4ent set a4entCaddrC U,ddrParams addr2id TaddressCV
$ Ta4ent set a4entC6ortC T6ort
$ Tself add$tar4et Ta4ent T6ort
(iii)
Instproc a+tar%et-a%ent port.
foreach m UTself set 6tnotifCV F
Tm attach T6ort Ta4ent
H
Class Rt$oule
(i()
Instproc attac! -a%ent port.
$ Ta4ent tar4et UUTself nodeV entryV
$ UUTself nodeV dmuxV install T6ort Ta4ent
11)2 4lications 222
2) Instroc attac(/a$ent' o/ class Node allocates a ort /or an inut a'ent
Pa$ent* con/i'ures t&e inst1ars Fa$ent5addr5G and Fa$ent5port5G o/
t&e inut a'ent Pa$ent* and in1okes t&e instroc addJtar$et/a$ent
port' to ask e1ery routin' module stored in t&e inst1ar ptnoti"5 to attac&
Fa$entG to t&e Node)
3) Instroc addJtar$et/a$ent port' o/ class Node in1okes instroc
attac(/ a$ent port' o/ eac& routin' module ?o/ class #t%od!le@ stored
in t&e inst1ar ptnoti"5)
:) Instroc attac(/a$ent port' o/ class #t%od!le creates a connection
between a node and an a'ent) Here* Pa$ent sets its Ptar$et5 to oint to
t&e entry o/ Pnode* w&ile Pnode installs Pa$ent in t&e slot FportG o/
its demultileAer Fdm!*5)G T&is connection is created /or bot& sendin' and
recei1in' a'ents)
Ste& /2 Associating a Sening Agent with a Receiving Agent
To associate a sendin' a'ent wit& a recei1in' a'ent* NS2 uses an instroc
connect
o/ class Sim!lator* w&ose syntaA is s&own below<
Pns connect Ps5a$ent Pr5a$ent
w&ere Pns* Ps5a$ent* and Pr5a$ent are Sim!lator* sendin' A$ent* and
recei1in' A$ent obBects* resecti1ely)
Pro'ram 11)2 s&ows t&e details o/ instroc connect/src dst') !ines 3 and
: in1oke instroc simple*Jconnect/src dst'* w&ic& set u a connection
/rom FsrcG to Fdst*G
1
and simple*Jconnect/dst src' w&ic& creates a
connection /rom FdstG back to Fsrc)G
Inst1ars Fdst5addr5G and Fdst5port5G are con/i'ured in !ines # and 1,)
6&en an a'ent creates a acket* it stores 1alues in 1ariables Fdst5Iaddr5G and
Fdst5Iport5G in t&e acket &eader) .urin' a acket /orwardin' rocess* a low9
le1el network deli1ers ackets to t&e a'ent corresondin' to w&ose address and
ort
are seci/ied in t&e acket
&eader)
%%=2 A&&#ications
4n alication is de/ined in a CCC class Application as s&own in
Pro'ram 11)3) Class Application &as only one key 1ariable Fa$ent5G w&ic&
is a ointer to class A$ent) Ot&er two 1ariables* Fenable#ecv5G and
1
Crom Table #)3* inst1ars Fdst addr G and Fdst port G are bound to t&e CCC
1ariables
Faddr G and Fport G o/ t&e obBect Fdst *G resecti1ely* in t&e CCC domain)
228 11 4lication< 0ser .emand Indicator
Program %%=2 Instrocs connect and simple*Jconnect o/ class
Sim!lator
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc connect 7src dst8 7
1 III
3 Psel" simple*Jconnect Psrc Pdst
= Psel" simple*Jconnect Pdst Psrc
> III
A 8
B Sim!lator instproc simple*Jconnect 7 src dst 8 7
/ III
G Psrc set dst5addr5 ?Pdst set a$ent5addr5@
20 Psrc set dst5port5 ?Pdst set a$ent5port5@
22 III
21 8
Program %%=* .eclaration o/ class Application
MMUMnsMappsMappI(
2 class Application 9 p!blic Process 7
1 p!blic9
3 Application&';
= virt!al void send&int nbytes';
> virt!al void recv&int nbytes';
A virt!al void res!me&';
B protected9
/ virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
G virt!al void start&';
20 virt!al void stop&';
22 A$ent
N
a$ent5;
21 int enable#ecv5;
23 int enable#es!me5;
2= 8;
Fenable#es!me5*G are /la' 1ariables* w&ic& indicate w&et&er an
Application obBect s&ould react to /unctions recv&nbytes' and
res!me&'* resecti1ely) T&ese two /la' 1ariables are set to Jero by de/ault)
11.2.1 5!nctions of Classes A%%lication and
Agent
4/ter t&eir connection is created* an alication and an a'ent may in1oke p!blic
/unctions o/ eac& ot&er t&rou'& t&e ointers Fa$ent5G and Fapp5*G resec9
ti1ely) T&e key p!blic /unctions o/ class Application include
/unctions send&nbytes'* recv&nbytes'* and res!me&'* w&ile t&ose o/
class A$ent are /unctions send&nbytes'* sendms$&nbytes'* close&'*
listen&'* and set5pkttype&pkttype')
11)2 4lications 22#
Program %%=/ Imlementation o/ /unctions send* recv* and res!me o/ class
Application
MMUMnsMappsMappIcc
2 void Application99send&int nbytes'
1 7
3 a$ent5JKsendms$&nbytes';
= 8
> void Application99recv&int nbytes'
A 7
B i" &C enable#ecv5'
/ ret!rn;
G TclF tcl : Tcl99instance&';
20 tclIeval"&HEs recv EdH) name5) nbytes';
22 8
21 void Application99res!me&'
23 7
2= i" &C enable#es!me5'
2> ret!rn;
2A TclF tcl : Tcl99instance&';
2B tclIeval"&HEs res!meH) name5';
2/ 8
4art /rom t&ese p!blic /unctions* class Application also ro1ides
protected /unctions start&' and stop&' to start and sto an
Application obBect* resecti1ely) Cinally* t&ere are /i1e key OTcl commands
/or class Application w&ic& can be in1oked /rom t&e OTcl domain< start/'*
stop/'* a$ent/'* send/nbytes'* and attac(Ja$ent/a$ent')
11.2.2 P!-lic 5!nctions of Class A%%lication
Pro'ram 11): s&ows t&e details o/ t&e t&ree /ollowin' p!blic /unctions o/ class
Application<
send&nbytes'< In/orm t&e attac&ed transort layer a'ent t&at a user needs to
send FnbytesG o/ data ayload) !ine 3 sends t&e demand to t&e attac&ed a'ent
by eAecutin' Fa$ent5JKsendms$&nbytes')G
recv&nbytes'< (ecei1e FnbytesG bytes /rom a recei1in' transort layer
a'ent) 4 0.P a'ent seci/ies FnbytesG as t&e number o/ bytes in a recei1ed
acket) In case o/ 0.P* FnbytesG is eDual to acket siJeO on t&e ot&er &and*
TCP seci/ies FnbytesG as t&e number o/ in9seDuence recei1ed bytes) .ue to
ossibility o/ out9o/9order acket deli1ery* FnbytesG can be 'reater t&an t&e
siJe o/ one acket in case o/ TCP)
22" 11 4lication< 0ser .emand Indicator
Program %%=0 .eclaration o/ class Tra""ic-enerator
MMUMnsMtoolsMtra"$enI(
2 class Tra""ic-enerator 9 p!blic Application 7
1 p!blic9
3 Tra""ic-enerator&';
= virt!al do!ble ne*t5interval&int F' : 0;
> virt!al void init&' 78
A virt!al do!ble interval&' 7 ret!rn 0; 8
B virt!al int on&' 7 ret!rn 0; 8
/ virt!al void timeo!t&';
G virt!al void recv&' 78
20 virt!al void res!me&' 78
22 protected9
21 virt!al void start&';
23 virt!al void stop&';
2= do!ble ne*tPkttime5;
2> int si6e5;
2A int r!nnin$5;
2B Tra""icTimer timer5;
2/ 8;
res!me&'< In1oked by a sendin' a'ent* t&is /unction indicates t&at t&e a'ent
&as sent out all data corresondin' to t&e user demand) Cor a TCP sender* t&is
/unction is in1oked w&en it sends out all t&e ackets re'ardless o/ w&et&er t&e
transmitted ackets &a1e been acknowled'ed)
Note t&at bot& /unctions recv&nbytes' and res!me&' will do not&in'
i/ Fenable#ecv5G : 0 and Fenable#es!me5G : 0* resecti1ely)
Ot&erwise* !ines 1, and 12 in Pro'ram 11)3 will in1oke OTcl commands or
instrocs recv/nbytes' and res!me/' in t&e OTcl domain* resecti1ely)
+y de/ault* bot& Fenable#ecv5G and Fenable#es!me5G are set to Jero*
and /unctions recv&nbytes' and res!me&' simly do not&in')
4 user may seci/y actions to be done uon in1ocation o/ /unctions
recv&nbytes' and res!me&' by
1) Settin' Fenable#ecv5G and$or Fenable#es!me5G to one)
2) Seci/yin' t&e actions in
a) Cunctions recv&nbytes' and$or res!me&'*
b) Instrocs recv/nbytes' and$or res!me/' in t&e OTcl domain* or
c) OTcl commands recv/nbytes' and$or res!me/' in t&e /unction
command&')
It is imortant to er/orm bot& t&e stes abo1e) Cailin' to er/orm t&e second
ste will result in a run9time error* since t&e OTcl commands or t&e instrocs
recv/nbytes' and res!me/' are unde/ined in class Application)
11)3 Tra//ic Lenerators 2"1
11.2." Related P!-lic 5!nctions of Class Agent
Class Application may in1oke t&e /ollowin' /unctions o/ class A$ent
t&rou'& 1ariable Fa$ent5G<
send&nbytes'< Send FnbytesG o/ alication ayload ?i)e)* user demand@
to a recei1in' a'ent) I/ nbytes:J2* t&e user demand would be in/inite)
sendms$&nbytes)"la$s'< Similar to /unction send&nbytes'* remo1e
t&is sace* but also /eed F"la$sG as an inut 1ariable)
close&'< 4sk an a'ent to close t&e connection ?alicable only to
TCP@
listen&'< 4sk an a'ent to listen to ?i)e)* wait /or@ a new connection
?alicable
only to Cull TCP@
set5pkttype&pkttype'< Set t&e 1ariable Ftype5G o/ t&e attac& a'ent to
be Fpkttype)G
11.2.$ OTcl Coands of Class A%%lication
.e/ined in t&e /unction command* OTcl commands associated wit& class
Application are as
/ollows<
start/'< In1oke /unction start&' to start t&e
alication)
stop/'< In1oke /unction stop&' to sto t&e
alication)
a$ent/'< (eturn t&e name o/ t&e attac&ed a'ent)
send/nbytes'< Send FnbytesG bytes o/ user ayload to t&e attac&ed a'ent
by in1okin' /unction send&nbytes')
attac(Ja$ent/a$ent'< Create a two9way connection between itsel/ and t&e
inut A$ent obBect ?a$ent@)
T&e details o/ t&e abo1e OTcl command can be /ound in /ile
Tns$as$a)cc)
%%=* Traffic ;enerators
4 tra//ic 'enerator models user be&a1ior w&ic& /ollows a rede/ined sc&edule)
In articular* it sends a demand to transmit one burst o/ user ayload to an
attac&ed a'ent at a time seci/ied in t&e sc&edule* re'ardless o/ t&e state o/ t&e
a'ent) In NS2* t&ere are /our main tra//ic 'enerators<
Constant +it (ate ?C+(@< Send a /iAed siJe ayload to t&e attac&ed a'ent)
+y de/ault* t&e inter1al between two ayloads ?i)e)* t&e sendin' rate@ is /iAed*
but it can be otionally randomiJed)
2", 11 4lication< 0ser .emand Indicator
EAonential On$O//< 4ct t&e same as C+( durin' an ON eriod) Sto
'eneratin' tra//ic durin' an OCC eriod) ON and OCC eriods are eAonentially
distributed* and are alternated w&en one eriod terminates)
Pareto On$O//< Similar to t&e EAonential On$O// tra//ic 'enerator) Howe1er*
t&e durations o/ ON and OCC eriods /ollow a Pareto distribution)
Tra//ic Trace< Lenerate tra//ic accordin' to a 'i1en trace /ile* w&ic& contains a
series o/ inter9burst transmission inter1als and ayload burst siJes)
11.".1 An O#er#ie& of Class Traffic/enerator
NS2 imlements tra//ic 'enerators usin' class Tra""ic-enerator)
Pro'ram 11)3 s&ows t&e declaration o/ t&e abstract class Tra""ic-enerator*
w&ere /unction ne*t5interval&si6e'in !ine : is ure 1irtual) Class
Tra""ic -enerator consists o/ t&e /ollowin' 1ariables<
timer5 4 Tra""icTimer obBect* w&ic& determines w&en a
new burst o/ ayload is created)
ne*tPkttime5 Simulation time t&at t&e neAt ayload will be assed to
t&e attac&ed transort layer a'ent
si6e5 4lication ayload siJe
r!nnin$5 tr!e i/ t&e Tra""ic-enerator obBect is runnin'
Class Tra""ic-enerator deri1es and o1errides t&e /ollowin' /our key
/unctions o/ class Application) It deri1es /unctions recv&nbytes' and
res!me&' ?i)e)* s&are t&e imlementation@ /rom class Application* and
o1errides /unctions start&' and stop&' o/ class Application)
Cunctions start&' and stop&' in/orm t&e Tra""ic-enerator obBect
to start and sto* resecti1ely* 'eneratin' user ayload) In Pro'ram 11)8*
/unction start&' initialiJes t&e Tra""ic-enerator obBect by in1okin'
/unction init&'
2
in !ine 3* and sets Fr!nnin$5G to 1 in !ine :) It comutes
and stores t&e time until t&e neAt ayload burst is 'enerated in t&e 1ariable
Fne*tPkttime5G in !ine 3) Cinally* it sets t&e Ftimer5G to eAire at
Fne*tPkttime5G seconds in /uture ?!ine 8@) Crom !ines " to 13 in Pro'ram
11)8* /unction stop&' does t&e oosite o/ /unction start&') It cancels t&e
endin' timer ?i/ any@ in !ine 11* and sets Fr!nnin$5G to , in !ine 12)
2
In !ine 3 o/ Pro'ram 11)3* /unction init&' simly does not&in')
11)3 Tra//ic Lenerators 2"3
Program %%=6 Cunctions start* stop* and timeo!t o/ class
Tra""ic-enerator
MMUMnsMtoolsMtra"$enIcc
2 void Tra""ic-enerator99start&'
1 7
3 init&';
= r!nnin$5 : 2;
> ne*tPkttime5 : ne*t5interval&si6e5';
A timer5Iresc(ed&ne*tPkttime5';
B 8
/ void Tra""ic-enerator99stop&'
G 7
20 i" &r!nnin$5'
22 timer5Icancel&';
21 r!nnin$5 : 0;
23 8
2= void Tra""ic-enerator99timeo!t&'
2> 7
2A i" &C r!nnin$5'
2B ret!rn;
2/ send&si6e5';
2G ne*tPkttime5 : ne*t5interval&si6e5';
10 i" &ne*tPkttime5 K 0'
12 timer5Iresc(ed&ne*tPkttime5';
11 else
13 r!nnin$5 : 0;
1= 8
Class Tra""ic-enerator also de/ines t&e /ollowin' t&ree new
/unctions<
ne*t5interval&si6e' Takes ayload siJe Fsi6eG as an inut ar'u9
ment* and returns t&e delay time a/ter w&ic&
a new ayload is 'enerated ?!ine :@) T&is
/unction is ure 1irtual and must be imle9
mented by t&e instantiable deri1ed classes o/ class
Tra""ic-enerator)
init&' InitialiJes t&e tra//ic 'enerator)
timeo!t&' Sends a user ayload to t&e attac&ed alication
and restart Ftimer5)G T&is /unction is in1oked
w&en Ftimer5G eAires)
T&e details o/ /unction timeo!t&' are s&own in !ines 1:H2: o/ Pro'ram
11)8) Cunction timeo!t&' does not&in' i/ t&e Tra""ic-enerator obBect
is not runnin' ?!ines 18H12@) Ot&erwise* it will send Fsi6e5G bytes o/ user
ayload to t&e attac&ed a'ent usin' /unction send&nbytes' ?de/ined in
Pro'ram 11):@) T&en*
2"2 11 4lication< 0ser .emand Indicator
4ig= %%=2 %ain mec&anism o/ a tra//ic 'enerator
!ine 1# will comute Fne*tPkttime5)G I/ Fne*tPkttime5G K 0* !ine 21
will in/orm Ftimer5G to eAire a/ter a eriod o/ Fne*tPkttime5)G Ot&erwise*
!ine
23 will sto t&e Tra""ic-enerator by settin' Fr!nnin$5G to
Jero)
11.".2 Main Mechanis of a Traffic ,enerator
Ci'ure 11)2 illustrates t&e main mec&anism o/ a tra//ic 'enerator* w&ic& relies
&ea1ily on t&e 1ariable Ftimer5G w&ose class is Tra""icTimer deri1ed /rom
class TimerHandler) 4s discussed in Sect) 13)1* class TimeHandler
consists o/ t&ree states< TI%E#5IDLE* TI%E#5PENDIN-* and
TI%E#5HANDLIN-) Eac& o/ t&ese states corresonds to one o/ two
Tra""ic-enerator states< Idle ?i)e)* r!nnin$5:0@ and 4cti1e ?i)e)*
r!nnin$5:2@) 6&ile state TI%E#5IDLE corresonds to t&e idle state o/ a
Tra""ic-enerator obBect* t&e ot&er two timer states are wit&in t&e acti1e
state o/ a Tra""ic-enerator obBect)
Startin' in an idle state* a tra//ic 'enerator mo1es to acti1e state w&en /unction
start&' is in1oked) Here t&e Ftimer5G state is set to TI%E#5PENDIN-)
4t t&e eAiration* Ftimer5G mo1es to state TI%E#5HANDLIN- and in1okes
/unction timeo!t&' o/ class Tra""ic-enerator) 4/ter eAecutin' /unc9
tion timeo!t&'* it c&an'es t&e state to TI%E#5PENDIN-* resc&edules itsel/*
and reeats t&e abo1e rocess) 6&en Ftimer5G state is TI%E#5PENDIN- or
TI%E#5HANDLIN-* t&e tra//ic 'enerator can be stoed by in1okin' /unction
stop&')
11)3 Tra//ic Lenerators 2"3
Program %%=5 .eclaration o/ class Tra""icTimer* /unction e*pire o/ class
Tra""icTimer* and t&e constructor o/ class Tra""ic-enerator
MMUMnsMtoolsMtra"$enI(
2 class Tra""icTimer 9 p!blic TimerHandler 7
1 p!blic9
3 Tra""icTimer&Tra""ic-enerator
N
t$' 9 t$en5&t$' 78
= protected9
> void e*pire&Event
N
';
A Tra""ic-enerator
N
t$en5;
B 8;
MMUMnsMtoolsMtra"$enIcc
/ void Tra""icTimer99e*pire&Event
N
'
G 7
20 t$en5JKtimeo!t&';
22 8
21 Tra""ic-enerator99Tra""ic-enerator&' 9
ne*tPkttime5&J2') r!nnin$5&0') timer5&t(is' 78
Pro'ram 11)2 s&ows t&e declaration o/ class Tra""icTimer* w&ic& deri1es
/rom class TimerHandler ?see Sect) 13)1@) Class Tra""icTimer &as a
key 1ariable Ft$en5*G a ointer to a Tra""ic-enerator obBect ?!ine 8@) 4t
t&e eAiration* NS2 in1okes /unction e*pire&e' o/ Ftimer5G ?!ines "H11@*
w&ic& in turn in1okes /unction timeo!t&' o/ t&e associated
Tra""ic-enerator obBect ?i)e)*
N
t$en5@)
4 two9way connection between Tra""ic-enerator and Tra""icTimer
obBects is created as /ollows) Class Tra""ic-enerator declares Ftimer5G as
its ointer to a Tra""icTimer obBect ?!ine 12 in Pro'ram 11)3@) 4 Tra""ic9
-enerator obBect instantiates Ftimer5G by /eedin' a ointer to itsel/ ?i)e)*
Ft(isG@ as an inut ar'ument ?!ine 12 in Pro'ram 11)2@) T&e construction o/
1ariable Ftimer5G in turn assi'ns t&e inut ointer ?i)e)* Ft(isG@ to its ointer
to a Tra""ic-enerator obBect* Ft$en5G ?!ine 3 in Pro'ram 11)2@* creatin' a
connection back to t&e Tra""icTimer obBect)
11."." 2!ilt(in Traffic ,enerators in %S2
%%=*=*=% $onstant Bit Rate ($BR) Traffic
4 C+( tra//ic 'enerator creates a /iAed siJe ayload burst /or e1ery /iAed inter1al)
4s s&own in Pro'ram 11)"* NS2 imlements C+( tra//ic 'enerators usin' a
2": 11 4lication< 0ser .emand Indicator
Program %%=7 Class C.#Tra""icClass w&ic& binds CCC class C.#
Tra""ic
and OTcl class ApplicationMTra""icMC.# to'et&er
MMUMnsMtoolsMcbr5tra""icIcc
2 static class C.#Tra""icClass 9 p!blic TclClass 7
1 p!blic9
3 C.#Tra""icClass&' 9 TclClass&HApplicationMTra""icMC.#H' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, C.#5Tra""ic&'';
A 8
B 8 class5cbr5tra""ic;
Tab#e %%=% Inst1ars o/ a C+( tra//ic 'enerator
Inst1ar .e/ault 1alue .escrition
packetSi6e5 21, 4lication ayload siJe in bytes
rate5 :"" 1,
3
Sendin' rate in bs
random5 , ?/alse@ I/ tr!e* introduce a random time to t&e
inter9burst transmission inter1al)
ma*pkts5 18
2
%aAimum number o/ alication ayload ackets
t&at C+( can send
CCC class C.#5Tra""ic w&ic& is bound to an OTcl class ApplicationM
Tra""icMC.#* w&ose key inst1ars wit& t&eir de/ault 1alues are s&own in
Table 11)1)
Note t&at* by de/ault t&e inter9burst transmission inter1al* w&ic& is t&e inter1al
between t&e be'innin' o/ two successi1e ayload bursts* can be comuted by
di1idin' t&e ayload burst siJe by t&e sendin' rate) +y de/ault* t&e inter9burst
transmission inter1al is 21, "U:""<,,, 3<:: ms) T&e detailed mec&anism /or
class C.#5Tra""ic will be discussed in Sect) 11)3):)
%%=*=*=2 "<&onentia# ,nE,ff Traffic
4n eAonential on$o// tra//ic 'enerator acts as a C+( tra//ic 'enerator durin' an
ON inter1al and does not 'enerate any ayload durin' an OCC inter1al) ON and
OCC eriods are bot& eAonentially distributed) 4s s&own in Pro'ram 11)#* NS2
imle9 ments EAonential On$O// tra//ic 'enerators usin' a CCC class
ELPOO5Tra""ic w&ic& is bound to an OTcl class
ApplicationMTra""icME*ponential* w&ose key inst1ars wit& t&eir
de/ault 1alues are s&own in Table 11)2)
%%=*=*=* Pareto ,nE,ff Traffic
4 Pareto On$O// tra//ic 'enerator does t&e same as an EAonential On$O//
'enerator but t&e ON and OCC eriods con/orm to a Pareto distribution) 4s
s&own in Pro'ram 11)1,* NS2 imlements Pareto On$O// tra//ic 'enerators
usin' a CCC
11)3 Tra//ic Lenerators 2"2
Program %%=8 Class ELPTra""icClass w&ic& binds CCC class ELPOO
Tra""ic and OTcl class ApplicationMTra""icME*ponential
to'et&er
MMUMnsMtoolsMe*pooIcc
2 static class ELPTra""icClass 9 p!blic TclClass 7
1 p!blic9
3 ELPTra""icClass&' 9 TclClass&HApplicationM
Tra""icME*ponentialH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, ELPOO5Tra""ic&'';
A 8
B 8 class5e*poo5tra""ic;
Tab#e %%=2 Inst1ars o/ an eAonential on$o// tra//ic 'enerator
Inst1ar .e/ault 1alue .escrition
packetSi6e5 21, 4lication ayload siJe in bytes
rate5 8: 1,
3
Sendin' rate in bs durin' an ON eriod
b!rst5time5 ,)3 41era'e ON eriod in seconds
idle5time5 ,)3 41era'e OCC eriod in seconds
Program %%=%: Class POOTra""icClass w&ic& binds CCC class POO
Tra""ic and OTcl class ApplicationMTra""icMPareto to'et&er
MMUMnsMtoolsMparetoIcc
2 static class POOTra""icClass 9 p!blic TclClass 7
1 p!blic9
3 POOTra""icClass&' 9 TclClass&HApplicationMTra""icM
ParetoH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, POO5Tra""ic&'';
A 8
B 8 class5poo5tra""ic;
class POO5Tra""ic w&ic& is bound to an OTcl class
ApplicationMTra""icM Pareto* w&ose key inst1ars wit& t&eir de/ault
1alues are s&own in Table 11)3)
%%=*=*=/ Traffic Trace
4 tra//ic trace 'enerates ayload bursts accordin' to a 'i1en trace /ile) 4s s&own in
Pro'ram 11)11* NS2 imlements tra//ic trace usin' t&e CCC class
Tra""icTrace w&ic& is bound to an OTcl class
ApplicationMTra""icMTrace) 0nlike ot&er tra//ic 'enerators described
be/ore* we need to seci/y a tra//ic trace /ile in t&e OTcl domain usin' t&e
OTcl command attac(Jtrace"ile o/ class ApplicationM
Tra""icMTrace ?see EAamle 11)1@)
2"8 11 4lication< 0ser .emand Indicator
Tab#e %%=* Inst1ars o/ a Pareto$o// tra//ic 'enerator
Inst1ar .e/ault 1alue .escrition
packetSi6e5 21, 4lication ayload in bytes
rate5 8: 1,
3
Sendin' rate in bs durin' an ON eriod
b!rst5time5 ,)3 41era'e ON eriod in seconds
idle5time5 ,)3 41era'e OCC eriod in seconds
s(ape5 1)3 4 FS&aeG arameter o/ a Pareto distribution
Program %%=%% Class Tra""icTraceClass w&ic& binds CCC class
Tra""ic
Trace and OTcl class ApplicationMTra""icMTrace
to'et&er
MMUMnsMtraceMtra""ictraceIcc
2 static class Tra""icTraceClass 9 p!blic TclClass 7
1 p!blic9
3 Tra""icTraceClass&' 9 TclClass&HApplicationMTra""icM
TraceH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn&ne, Tra""icTrace&'';
A 8
B 8 class5tra""ictrace;
E%ample ** 4 C+( tra//ic 'enerator in EAamle #)1 can be relaced wit& a
tra//ic trace by substitutin' !ines 1,H12 in Pro'ram #)2 wit& t&e /ollowin' lines<
set t"ile ?ne, Trace"ile@
Pt"ile "ilename e*ampleJtrace
set tt ?ne, ApplicaitonMTra""icMTrace@
Ptt attac(Jtrace"ile Pt"ile
Ptt attac(Ja$ent P!dp
4 tra//ic trace /ile is a ure binary /ile) 4 codeword in t&e binary /ile consists
o/ two 329bit /ields) T&e /irst /ield indicates inter9burst transmission inter1al in mi9
croseconds* w&ile t&e second is t&e ayload siJe in bytes ?see /ile
Tns$tcl$eA$eAamle9 trace as an eAamle tra//ic trace /ile@)
11.".$ Class C!R Traffic9 An *1aple Traffic
,enerator
T&is section resents a CCC imlementation o/ class C.#5Tra""ic w&ose
declaration is s&own in Pro'ram 11)12) Class C.#5Tra""ic deri1es /rom class
Tra""ic-enerator and &as t&e /ollowin' main 1ariables<
rate5 C+( sendin' rate in bs
interval5 Packet inter9arri1al time in seconds
11): Simulated 4lications 2"#
Program %%=%2 .eclaration* /unction start* and /unction init o/ class
C.# Tra""ic
MMUMnsMtoolsMcbr5tra""icIcc
2 class C.#5Tra""ic 9 p!blic Tra""ic-enerator 7
1 p!blic9
3 C.#5Tra""ic&';
= virt!al do!ble ne*t5interval&intF';
> inline do!ble interval&' 7 ret!rn &interval5'; 8
A protected9
B virt!al void start&';
/ void init&';
G do!ble rate5;
20 do!ble interval5;
22 do!ble random5;
21 int se+no5;
23 int ma*pkts5;
2= 8;
2> void C.#5Tra""ic99start&'
2A 7
2B init&';
2/ r!nnin$5 : 2;
2G timeo!t&';
10 8
12 void C.#5Tra""ic99init&'
11 7
13 interval5 : &do!ble'&si6e5 << 3'M&do!ble'rate5;
1= i" &a$ent5'
1> i" &a$ent5JK$et5pkttype&' C: PT5TCP FF
a$ent5JK$et5pkttype&' C: PT5TQ#C'
1A a$ent5JKset5pkttype&PT5C.#';
1B 8
random5 I/ tr!e* t&e inter9arri1al time will be random
se+no5 C+( seDuence number
ma*pkts5 0er bound on t&e seDuence number
+ased on t&e main mec&anism discussed in Sect) 11)3)2* NS2 acti1ates a tra//ic
'enerator by in1okin' /unction start&') 6&en acti1ated* a tra//ic 'enerator
in1okes its /unction timeo!t&'* w&ic& 'enerates an alication ayload*
eriodi9 cally) 4n inter1al between two consecuti1e timeo!t&' in1ocations is
determined by t&e /unction ne*t5interval&si6e') T&e timeo!t&'
in1ocations occur reeatedly until t&e tra//ic 'enerator is deacti1ated ?by an
in1ocation o/ /unction close&'@)
4s s&own in Pro'ram 11)12* /unction start&' in1okes /unction init&'
?!ine
12@ to initialiJe t&e tra//ic 'enerator* sets Fr!nnin$5G to 1 ?!ine 1"@* and in1okes
/unction timeo!t&' ?!ine 1#@) T&e details o/ /unction init&' are s&own in
2"" 11 4lication< 0ser .emand Indicator
Program %%=%* Cunction ne*t interval o/ class C.# Tra""ic
MMUMnsMtoolsMcbr5tra""icIcc
2 do!ble C.#5Tra""ic99ne*t5interval&intF si6e'
1 7
3 interval5 : &do!ble'&si6e5 << 3'M&do!ble'rate5;
= do!ble t : interval5;
> i" &random5'
A t 4: interval5
N
#andom99!ni"orm&J0I>) 0I>';
B si6e : si6e5;
/ i" &44se+no5 < ma*pkts5'
G ret!rn&t';
20 else
22 ret!rn&J2';
21 8
!ines 21H2" o/ Pro'ram 11)12) !ine 23 comutes t&e inter9burst transmission
inter1al as transmission rate ?rate5@ di1ided by ayload burst siJe Fsi6e5<<3G
?in bits@)
3
Cunction init&' would also set t&e acket tye o/ t&e attac&ed
a'ent to PT5C.#* unless t&e acket tye &as already been set to PT5TCP or
PT5TQ#C ?!ines 23H28@)
Crom Pro'ram 11)8* /unction timeo!t&'* sends out Fsi6e5G bytes o/ ali9
cation ayload ?!ine 1"@* recomutes Fne*tPkttime5G as a 1alue returned /rom
t&e ne*t5interval&si6e5' ?!ine 1#@* and sc&edules t&e timer Ftimer5G
to eAire at Fne*tPkttime5G seconds in /uture ?!ine 21@) 4'ain* t&e /unc9
tion ne*t5interval&si6e5' is ure 1irtual and must be imlemented by
instantiable c&ild classes o/ class Tra""ic-enerator) Class C.#5Tra""ic
imlements t&is /unction ?Pro'ram 11)13@* by returnin' t&e acket inter9arri1al
time con1erted /rom ayload siJe Fsi6e5G and C+( transmission rate Frate5G
?!ines
3 and #@) Otionally* !ine 8 may add or subtract a random 1alue to t&e comuted
inter1al i/ Frandom5G is set to tr!e) 4lso* i/ t&e alication ayload is 'reater
t&an Fma*pkts5*G !ine 11 will return 1 rat&er t&an t&e comuted inter1al)
%%=/ Simu#ate A&&#ications
0nlike tra//ic 'enerators* a simulated alication does not &a1e a rede/ined
sc&edule /or ayload 'eneration) (at&er* it acts as i/ an actual alication is
runnin') NS2 ro1ides two built9in simulated alications< CTP and Telnet)
3
Since t&e units o/ t&e 1ariables Fsi6e G and Frate G are FbytesG and Fbits er
second*G resecti1ely* !ine # multilies Fsi6e G wit& " by s&i/tin' Fsi6e G to t&e le/t by
3 bits ?see Sect) 13):)2@)
2#, 11 4lication< 0ser .emand Indicator
11.$.1 5ile Transfer Protocol
Cile Trans/er Protocol ?CTP@ is a rotocol w&ic& di1ides a 'i1en /ile into small
ieces and trans/ers t&em to a destination &ost) 0nlike a 'eneral CTP in ractice*
an NS2 CTP module does not need an inut /ile) It simly in/orms an attac&ed
sendin' transort layer a'ent o/ /ile siJe in bytes) 0on recei1in' user demand
?e)')* /ile siJe@* t&e a'ent creates ackets w&ic& can accommodate t&e /ile and
/orwards t&em to a connected recei1in' transort layer a'ent t&rou'& a low9le1el
network ser1ices) 4lso* an NS2 CTP module is not resonsible /or seci/yin' a
destination &ost) .estination &ost identi/ication is t&e resonsibility o/ a transort
layer a'ent instead* t&e simulator emloys t&e instroc connect/src dst'
?Sect) 11)1@ in order to associate a source wit& a destination)
.ue to its simlicity* an CTP module is imlemented in t&e OTcl domain only)
.e/ined in class ApplicationMQTP* w&ic& deri1es class Application* its
main OTcl commands and instrocs include
attac(Ja$ent/a$ent' (e'ister t&e inut a$ent as an attac&ed
a'ent) start/' In/orm t&e attac&ed a'ent o/ a
demand to transmit a /ile wit& in/inite siJe by eAecutin'
Fsend J2)G
stop/' Sto t&e endin' /ile trans/er session)
send/nbytes' Send a /ile wit& siJe nbytes bytes by in9
1okin' /unction sendms$&nbytes' o/ t&e
attac&ed a'ent)
prod!ce/nbytes' In/orm t&e attac&ed a'ent to transmit until its
seDuence number &as reac&ed t&e minimum o/
nbytes and ma*se+5)
prod!cemore /nbytes' In/orm t&e attac&ed a'ent to transmit nbytes
more ackets)
11.$.2 Telnet
Telnet is an interacti1e client9ser1er teAt9based alication) 4 Telnet client lo's
on to a ser1er* and sends teAt messa'es to t&e ser1er) T&e ser1er in turn eAecutes
t&e recei1ed messa'e and returns t&e result to t&e client) Clearly* Telnet is not
imlemented based on a rede/ined sc&edule* since its data tra//ic is created in
resonse to user demand) Howe1er* NS2 models a Telnet alication in t&e same
way as it does /or tra//ic 'enerators< sendin' a /iAed siJe acket /or e1ery
randomiJed inter1al)
NS2 de/ines a Telnet alication in CCC class TelnetApp and OTcl class
ApplicationMTelnet* w&ic& deri1es /rom class Application) It uses t&e
11)3 C&ater Summary 2#1
1alue stored in 1ariable Fsi6e5G o/ t&e attac&ed a'ent as t&e siJe o/ eac& Telnet
acket* and comutes t&e inter9burst transmission inter1al as /ollows<
Case I< I/ Finterval5G is nonJero* t&e inter9burst transmission inter1al is
c&osen /rom an eAonential distribution wit& mean Finterval5)G
Case II< I/ Finterval5G is Jero* t&e inter9burst transmission inter1al is
c&osen /rom an emirically 'enerated distribution FtcplibG de/ined in /ile
Tns$tc$tclib9telnet)cc)
Telnet &as only one con/i'urable 1ariable Finterval5)G In common wit&
ot&er Application obBects* it can be started and stoed usin' command
start/' and stop/'* resecti1ely)
%%=0 $ha&ter Summary
Sittin' on to o/ a transort layer a'ent* an alication in/orms t&e attac&ed a'ent
o/ user demand) 4lications can be classi/ied into tra//ic 'enerators and simulated
a9 lications) 4 tra//ic 'enerator creates user demand based on a rede/ined
sc&edule* w&ile a simulated alication does so as i/ t&e alication is runnin')
+uilt9in tra//ic 'enerators in NS2 include C+( ?constant bit rate@* eAonential
on$o//* Pareto on$o//* and Tra//ic Trace) 4 C+( tra//ic 'enerator creates /iAed
siJe ayloads /or e1ery /iAed inter1al) EAonential on$o// and Pareto on$o// tra//ic
'enerators create /iAed siJe ayloads durin' an ON eriod and create no ayload
durin' an OCC eriod) T&e ON and OCC durations are c&osen /rom an eAonential
distribution and a Pareto distribution* resecti1ely) Cinally* ayload siJe and inter9
burst transmission inter1al /or a tra//ic trace tra//ic 'enerator are obtained /rom an
inut trace /ile)
NS2 &as two built9in simulation alication< CTP ?Cile Trans/er Protocol@ and
Telnet) CTP in/orms t&e attac&ed a'ent o/ t&e /ile siJe ?in bytes@ to be trans/erred)
T&e attac&ed a'ent is resonsible /or creatin' ackets w&ic& can accommodate
a /ile* and c&oosin' t&e destination o/ t&e CTP session) In ractice* Telnet is a
clientHser1er alication* w&ose tra//ic deends on t&e interaction between client
and ser1er) Howe1er* NS2 imlements a Telnet as a tra//ic 'enerator) In articular*
it creates a /iAed siJe ayload /or e1ery random inter1al* w&ose distribution is
eit&er eAonential or FtcplibG de/ined in Tns$tc$tclib9telnet)cc)
Class Application is t&e base class /or all t&e abo1e alications)
It ro1ides /ew key OTcl commands and instrocs to con/i'ure Application
obBects) 4n instroc attac(Ja$ent/a$ent' re'isters t&e inut Fa$entG as
an attac&ed a'ent) Instrocs start/' and stop/' in/orm an alication to
start and sto 'eneratin' data ayload) .eri1ed classes o/ class Application
reuse t&ese /unctionalities and de/ine t&eir own /unctionalities /or t&eir own
uroses)
2#2 11 4lication< 0ser .emand Indicator
%%=6 "<ercises
1) !et Pn2 and Pn1 be two nodes and let Pns be t&e Simulator)
a) Create an CTP a'ent to trans/er a /ile wit& siJe 1, %+ytes /rom Node Pn2
to Node Pn1) EAlain ste9by9ste &ow data are 'enerated* tra1erse t&e
network* arri1e Node Pn1* and are destroyed)
b) Create a C+( tra//ic /rom Node Pn2 to Node Pn1) Set t&e acket siJe to
1,, bytes and bit rate to : kbs) EAlain acket /low mec&anism includin'
timin' mec&anism ?i)e)* w&en and &ow muc& t&e alication sends out data@)
2) 6&at are t&e di//erences o/ alication and transort layers in t&e TCP$IP
rotocol stack and in t&e NS2 imlementationR
3) How does an alication send$recei1e user demand to$/rom an a'entR Seci/y
OTcl and$or CCC statements to do so)
:) .e1elo an alication w&ic& &as two sta'es) 4t t&e &ea1y9tra//ic sta'e* t&e
alication continuously ro1ide data to t&e a'ent) 4t t&e li'&t9tra//ic sta'e* it
'enerates ackets in t&e same way t&at C+( does) .esi'n an eAeriment* and
run simulation to test your de1eloed alication)
3) %odi/y class Application by /orcin' it to rint out a messa'e w&en its
/unctions recv&nbyte' and res!me&' are in1oked)
$ha&ter %2
Wire#ess Mobi#e A Hoc Networks
NS2 classi/ies communication networks into t&ree main cate'ories) Cirst* wired
networks are c&aracteriJed by wired communication links) C&ater 2 s&ows a
simle /orm o/ t&e wired links called SimpleLinks w&ic& can be used to
connect re'ular Node discussed in C&a) 8)
T&e second cate'ory is ure wireless networks* w&ic& contain no wired links)
4ll communications are carried out 1ia FwirelessG communication c&annels only)
One cate'ory o/ wireless networks in w&ic& t&ere is no central node or coordinator
suc& as a base9station ?+S@ or an access9oint ?4P@ is known as wireless mo'ile
ad hoc networks) In t&is tye o/ networks* t&ere is no in/rastructure and t&e
mobile nodes 'enerally communicate on a eer9to9eer basis) T&is is in contrast
to an in/rastructure9based network w&ere mobile nodes communicate 1ia t&e
controller node ?e)')* +S or 4P@* w&ic& is 'enerally connected to a wired network
in/rastructure) .ue to t&e absence o/ any &ysical wired communication links* all
nodes in a wireless ad &oc network are able to mo1e /reely durin' simulation) NS2
incororates bot& wireless communication and node mobility into re'ular nodes*
and de/ines a new tye o/ nodes called %obile Nodes)
Cinally* &ybrid networks contain bot& wired and wireless communication links)
In NS2 terminolo'y* t&is tye o/ networks is called wired9cum9wireless networks)
0n/ortunately* NS2 imlementation is not as simle as includin' (e'ular Nodes
and %obile Nodes in a Tcl Simulation Scrit) T&e issues arise w&en nodes
need to &a1e bot& wired and wireless inter/aces) NS2 desi'ns a new node tye
called +ase Station Nodes w&ic& act as 'ateways between wired and wireless
domains)
T&is c&ater /ocuses on t&e second tye o/ wireless communication networks H
wireless mobile ad &oc networks)
1
In articular* t&e em&asis is on 5o'ile Nodes
associated wit& wireless mobile ad &oc networks) 4n o1er1iew o/ %obile Nodes
is 'i1en in Sect) 12)1) Sections 12)2H12)3 eAlain NS2 imlementation /or network
1
T&e imlementation o/ wired9cum9wired networks is out o/ t&e scoe o/ t&is book) Interested
readers are recommended to re/er to M12N)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 12* = Srin'er Science>+usiness %edia* !!C 2,12
2#3
12)1 4n O1er1iew o/ 6ireless Networkin' 2#3
d
e
r
i
(
e
layer* data link layer* %4C layer* and &ysical layer* resecti1ely)
Imlementation o/ node mobility is discussed in Sect) 12)8) Cinally* t&e c&ater
summary is 'i1en in Sect) 12)2)
%2=% An ,verview of Wire#ess Networking
In NS2* t&e central imlementation o/ wireless networkin' lies in %obile Nodes)
Comlyin' to t&e OOP concet* %obile Nodes in&erit all attributes and be&a1iors
/rom its redecessor* (e'ular Node discussed in C&a) 8)
12.1.1 Mo-ile %ode
In Ci') 12)1* %obile Nodes are reresented by a CCC class %obileNode w&ic&
is bound to an OTcl class NodeM%obileNode) T&e class &ierarc&y is de/ined in
t&e CCC domain only* w&ere t&e CCC class deri1es %obileNode /rom class
Node* but t&e OTcl class NodeM%obileNode is a to9le1el class)
Pro'ram 12)1 s&ows declaration o/ t&e CCC class %obileNode) In addition
to attributes in&erited /rom its arent class* t&e class %obileNode de/ines
attributes ?e)')* coordinate ?L5*[5*\5@ and speed5@ to suort node mobility)
12.1.2 Architect!re of Mo-ile %ode
4not&er /undamental c&aracteristic o/ %obile Nodes is t&e ability to communi9
cate wit&out &ysically wired c&annel) In NS2* t&is c&aracteristic is contributed
by se1eral CCC comonents* ut to'et&er in an OTcl obBect called a NodeM
%obileNode obBect)
Ci'ure 12)2 s&ows t&e arc&itecture o/ a %obile Node* w&ic& consists o/ two
main
arts< re'ular node art and mobile eAtension
art)
C&& OTcl
)ode
)ode
)odeNMobile)ode
4ig= %2=% Class &ierarc&y o/
mobile nodes
Mobile)ode
Program %2=% 4 CCC class %obileNode w&ic& is bound to an OTcl class
NodeM%obile
MMUnsMcommonMmobileJnodeI(
2 class %obileNode 9 p!blic Node
1 7
3 protected9
= do!ble L5)[5)\5; MMT(e c!rrent location
> do!ble speed5; MMIn meters per second
A do!ble dL5)d[5)d\5; MMDnits
B do!ble destL5)dest[5;MMT(e destination
/ Event pos5intr5;
G do!ble position5!pdate5time5; MMLast !pdated
position
20 do!ble position5!pdate5interval5; MMDpdate interval
22 PositionHandler pos5(andle5; MMQor randomJmotion
only
21 private9
23 int random5motion5; MMAre ,e r!nnin$ random
motionY
2= Topo$rap(y
N
T5; MMDe"ine an area "or
movin$
2> LIST5ENT#[&%obileNode' link5; MMA $lobal list o" mobile
nodes
2A 8;
MMUnsMcommonMmobileJnodeIcc
2B static class %obileNodeClass 9 p!blic TclClass 7
2/ p!blic9
2G %obileNodeClass&' 9 TclClass&HNodeM%obileNodeH' 78
10 TclObject
N
create&int) const c(ar
N
const
N
' 7
12 ret!rn &ne, %obileNode';
11 8
13 8 class5mobilenode;
%2=%=2=% Regu#ar Noe Part
T&is art is similar to t&at o/ re'ular nodes) T&e di//erences lie in classi/ier con/i'9
uration and acket /orwardin' mec&anism) T&e /orwardin' mec&anism deends
on tyes o/ %obile Nodes as /ollows<
Source Node< Packets are created by an alication) T&ey enter t&e node entry
2
and are assed to t&e address classi/ier) In t&is case* t&e destination address
would be di//erent /rom t&e address o/ t&is Node) T&e address classi/ier*
t&ere/ore* /orwards t&e acket to t&e routin' a'ent 1ia Fde"a!lt5tar$et5)G
2
T&e node entry does not actually eAist) It is an instroc o/ class Node w&ic& returns t&e
/irst acket recetion obBect) In Ci') 12)2* t&e node entry is t&e address classi/ier)
12)1 4n O1er1iew o/ 6ireless Networkin' 2#2
P
o
r
t

0
l
a
s
s
i
f
i
e
r
,
d
d
r
e
s
s
0
l
a
s
s
i
f
i
e
r
)odeWs
/P ,ddress
SourceN
Sin1
entryC
2%%
Re%ular noe part
$o/ile e0tension part
defaulttar4etC
=outin4
,4ent
,ddress
=esolution
Protocol
(,=P)
ar6tableC
macC
u6tar4etC
Lin1 Layer (LL)
do>ntar4etC
tar4etC
/nterface 5ueue (/.3)
do>ntar4etC
Medium ,ccess 0ontrol (M,0)
u6tar4etC
=adio
6ro6a4ationC
u6tar4etC do>ntar4etC
Pro6a4ation
Model
)et>or1 /nterface ()et/.)
u6tar4etC channelC
0hannel
4ig= %2=2 T&e arc&itecture o/ mobile nodes
4estination Node< Packets enter a mobile node t&rou'& node entry /rom t&e
link layer) T&ey are assed t&rou'& an address classi/ier) In t&is case* t&e
destination address is t&e same as t&e node address) T&e ackets are t&ere/ore
assed to t&e ort classi/ier w&ic& t&en /orwards t&e ackets to t&e attac&ed
sink alication)
&orwarding Node< Packets are assed /rom t&e link layer to t&e node entry
and t&e address classi/ier) In t&is case* t&e acket is /orwarded to t&e routin'
a'ent* since t&e address in t&e acket &eader does not matc& wit& t&e node5s
address)
%2=%=2=2 Mobi#e "<tension Part
T&is art is an eAtension /rom t&e re'ular node art) It includes all t&e comonents
in t&e lower art o/ Ci') 12)2) Eac& o/ t&ese comonents is seci/ied by t&e otions
Tab#e %2=% .etails o/ mobile node con/i'uration< Otions and corresondin' inst1ars o/ t&e
Sim!lator obBect* and t&eir descritions
Otion Inst1ar .escrition
Jad(oc#o!tin$ ro!tin$A$ent5 (outin' rotocol ?e)')* AODS@)
JllType lltype5 !ink layer tye ?e)')* LL@)
JmacType macType5 %edium access control tye ?e)')* %acM
/01522@)
Ji"+Type i"+Type5 Tye o/ t&e underlyin' bu//er mana'ement disci9
line ?e)')* !e!eMDropTailMPri!e!e@
Ji"+Len i"+len5 SiJe o/ t&e bu//er in ackets ?e)')* /i1e ackets@
JantType antType5 4ntenna tye ?e)')* AntennaMOmniAntenna@
JpropType propType5 Tye o/ t&e underlyin' radio roa'ation
models
?e)')* Propa$ationMT,o#ay-ro!nd@
Jp(yType p(yType5 Network inter/ace tye ?e)')* P(yMWirelesJ
sP(y@
Jc(annelType c(annelType5 C&annel tye ?e)')* C(annelMWirelessC(aJ
nnel@
JtopoInstance topoInstance5 4n OTcl instance w&ic& identi/y too'ra&y
?e)')* ne, Topolo$y@
Ja$entTrace a$entTrace5 Turnin' a'ent trace ON or OQQ
Jro!terTrace ro!terTrace5 Turnin' routin' trace ON or OQQ
JmacTrace macTrace5 Turnin' %4C trace ON or OQQ
JmovementTrace movementTrace5 Turnin' mo1ement trace ON or OQQ
o/ instroc nodeJcon"i$/ar$s') T&e 1alues and descrition /or most
/reDuently used otions are s&own in Table 12)1) T&e comlete list o/ otions can
be /ound in t&e /ile Tns$tcl$lib$ns9lib)tcl)
12.1." ,eneral Pac'et 5lo& in a 3ireless
%et&or'
Ipleentation
In Ci') 12)2* obBects in a %obile Node are 1ertically connected) T&ese obBects
re/er to uer and lower obBects usin' t&eir CCC ointers F!ptar$et5G and
Fdo,ntar$et5G w&ic& can be con/i'ured usin' OTcl commands do,nJ
tar$et/III' and !pJtar$et/III'* resecti1ely ?e)')* see eAamle usa'e in
!ines 22 and 2# o/ Pro'ram 12)8@)
.ue to t&e 1ertical arc&itecture* ackets 'enerally mo1e uward and downward)
T&ey mo1e uward w&en t&ey need to be rocessed locally) On t&e ot&er &and*
t&ey mo1e downward w&en t&ey need to be transmitted o1er t&e air) NS2
determines t&e direction to w&ic& a acket is mo1in' usin' a /ield Fdirection5G
o/ t&e common acket &eader ?see Pro'ram ")8@) Packets mo1in' uward and
downward &a1e t&is /ield marked wit& FDPG and FDOWN*G resecti1ely)
12)1 4n O1er1iew o/ 6ireless Networkin' 2##
12.1.$ Mo-ile %ode Config!ration Process
4 rocess o/ creatin' %obile Nodes consists o/ two key stes<
Ste& % F Mobi#e Noe $onfiguration< Store con/i'uration in/ormation in
inst1ars o/ t&e Sim!lator usin' t&e /ollowin' instroc<
Pns nodeJcon"i$ J<optionK <val!eK
w&ere Pns is t&e Sim!lator obBect) T&e a1ailable <optionK and t&eir
<val!eK are 'i1en in Table 12)1) 4mon' all otions* Jad(oc#o!tin$ is
mandatory) I/ con/i'ured* Ste 2 will create %obile Nodes* rat&er t&an (e'ular
Nodes)
Ste& 2 F Mobi#e Noe $onstruction< Create a mobile node as in Ci') 12)2
usin' t&e OTcl statement
Pns node
E%ample 2** T&e /ollowin' is an eAcert /rom a built9in eAamle ?see t&e /ile
Tns$tcl$eA$simle9wireless)tcl@)
Pns nodeJcon"i$ Jad(oc#o!tin$ AODS T
JllType LL T
JmacType %acM/01522 T
Ji"+Type !e!eMDropTailMPri!e!e T
Ji"+Len >0 T
JantType AntennaMOmniAntenna T
JpropType Propa$ationMT,o#ay-ro!nd T
Jp(yType P(yMWirelessP(y T
Jc(annelType C(annelMWirelessC(annel T
JtopoInstance Ptopo T
Ja$entTrace ON T
Jro!terTrace ON T
JmacTrace OQQ T
JmovementTrace OQQ
T&is OTcl statement con/i'ures all %obile Nodes as /ollows) T&e routin' rotocol
is 4O.7 M32N* t&e link layer tye is LL* and t&e %4C rotocol is IEEE ",2)11
M3#N) Eac& %obile Node &as a bu//er w&ic& can &old uto 3, ackets) T&e ser1ice
disciline is based on rioritiJed Dueue w&ic& 'i1es riority to routin' ackets)
T&e tye o/ antanna is omni9directional) T&e roa'ation model is two9ray
roa'ation model M3"N) T&e &ysical network transmission and t&e tye o/ t&e
s&ared c&annel are bot& wireless) Cinally* t&e statement turns a'ent and router
traces on* and turns %4C and mo1ement traces o//)
2#" 12 6ireless %obile 4d Hoc Networks
Program %2=2 Instroc nodeJcon"i$ and ot&er 1ariable settin' instrocs o/
class
Sim!lator
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc nodeJcon"i$ ar$s 7
1 set ar$s ?eval Psel" initJvars Par$s@
3 Psel" instvar addressType5 ro!tin$A$ent5 propType5
macTrace5 T
= III
> i" ?in"o e*ists p(yTrace5@ 7
A Sim!lator set P(yTrace5 Pp(yTrace5
B 8
/ i" 7?in"o e*ists propType5@8 7
G set propInstance5 ?ne, PpropType5@
20 Sim!lator set propInstCreated5 2
22 8
21 III
23 8
2= Sim!lator instproc ad(oc#o!tin$ 7val8 7
2> Psel" set ro!tin$A$ent5 Pval
2A 8
2B Sim!lator instproc llType 7val8 7 Psel" set llType5 Pval 8
2/ Sim!lator instproc macType 7val8 7 Psel" set macType5 Pval8
Object
%2=%=/=% Ste& %2 Mobi#e Noe configuration
.iscussed earlier in Sect) 8)1)3* t&e instroc nodeJcon"i$/ar$s' creates and
con/i'ures inst1ars o/ t&e Sim!lator obBect) T&e list o/ inst1ars o/ class
Sim!lator corresondin' to eac& otion is s&own in Table 12)1) T&e 1alues
in t&ese inst1ars will later be used in Ste 2 to create %obile Nodes)
Pro'ram 12)2 s&ows t&e details o/ t&e instroc nodeJcon"i$/ar$s' ?!ines
1H13@* and instrocs used to set node con/i'uration inst1ars ?!ines 1:H1"@) T&e
instroc nodeJcon"i$/ar$s' takes as inut ar'uments a list 1ariable
Far$sG w&ic& contains otions and 1alues /or node con/i'uration ?see EAamle
12)1@) T&e only main statement o/ t&is instroc is to in1oke t&e instroc initJ
var/ar$s' o/ class Object ?!ine 2@ to initialiJe t&e inst1ars o/ class
Sim!lator) T&e rest o/ t&is instroc ?!ines 3H11@ is Bust to set u 1ariables and
obBects as con/i'ured by t&e instroc initJvar/III')
Pro'ram 12)3 s&ows t&e details o/ t&e instroc initJvar/ar$s') T&is
instroc
takes node con/i'uration otions and 1alues as its inut ar'uments) !ine 2 in1okes
t&e instroc initJde"a!ltJvars/classes' to initialiJe de/ault 1ariables o/
t&e inut class ?i)e)* Sim!lator in t&is case@) !ines :H1: are t&e main loo /or
t&is instroc) T&ey iterate /or e1ery node otion) !ines 3 and 8 store t&e /irst ?i)e)*
t&e otion@ and t&e second ?i)e)* t&e 1alue@ entries o/ t&e inut ar'ument Far$sG
12)1 4n O1er1iew o/ 6ireless Networkin' 3,1
Program %2=* 7ariable initialiJation instrocs
MMUtclclMtclJobjectItcl
2 Object instproc initJvars 7ar$s8 7
1 Psel" initJde"a!ltJvars ?Psel" in"o class@
3 set s(ado,5ar$s HH
= "or 78 7Par$s C: HH8 7set ar$s ?lran$e Par$s 1 end@8 7
> set key ?linde* Par$s 0@
A set val ?linde* Par$s 2@
B i" 7Pval C: HH FF ?strin$ matc( 7J?AJ6@
N
8 Pkey@8 7
/ set cmd ?strin$ ran$e Pkey 2 end@
G i" C?catc( HPsel" Pcmd PvalH@ 7
20 contin!e
22 8
21 8
23 lappend s(ado,5ar$s Pkey Pval
2= 8
2> ret!rn Ps(ado,5ar$s
2A 8
2B instproc initJde"a!ltJvars 7classes8 7
2/ "oreac( cl Pclasses 7
2G i" 7Pcl :: HObjectH8 contin!e
10 Psel" initJde"a!ltJvars H?Pcl in"o s!perclass@H
12 "oreac( var ?Pcl in"o vars@ 7
11 i" ?catc( HPsel" set PvarH@ 7
13 Psel" set Pvar ?Pcl set Pvar@
1= 8
1> 8
1A 8
1B 8
in local 1ariables FkeyG and FvalG* resecti1ely) !ine 2 remo1es t&e re/iAin'
&y&en FJG /rom t&e node con/i'uration otion strin' stored in t&e 1ariable Fkey)G
!ine " stores t&e result in a local 1ariable Fcmd)G T&en !ine #* in1okes t&e
instroc
Pcmd sulyin' Pval as an inut ar'ument)
3
EAamles o/ t&ese instrocs
Pcmd are s&own in !ines 1:H1" o/ Pro'ram 12)2) Eac& o/ t&ese instrocs stores
a node con/i'uration 1alue in a corresondin' inst1ar o/ class Sim!lator)
4'ain* t&is in/ormation s&all be later used in Ste 2)
Crom wit&in t&e instroc initJvar/ar$s'* !ine 2 in1okes t&e instroc
initJde"a!ltJvars/classes' w&ose details are s&own in !ines 12H22)
T&is instroc initialiJes de/ault 1ariables /or all classes w&ose name is stored in
t&e inut ar'uments) +ased on t&e OOP concet* t&e initialiJation must occur at
t&e base class /irst) !ine 2, recursi1ely mo1es t&e rocess toward t&e to9le1el
3
Note t&at* t&e command Fcatc(G returns t&e eAecution result o/ t&e /ollowin' Tcl statement)
Cor eAamle* t&e eAecution result is Jero /or success/ul eAecution) T&e set o/ ossible eAecution
results is s&own in Pro'ram 3)")
3,, 12 6ireless %obile 4d Hoc Networks
Program %2=/ Instroc Node o/ class Sim!lator< T&e wireless9related
eAcert
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc node ar$s 7
1 Psel" instvar Node5 ro!tin$A$ent5 ,ired#o!tin$5
satNodeType5
3 i" 7 ?in"o e*ists ro!tin$A$ent5@ FF &Pro!tin$A$ent5
C: HH' 8 7
= set node ?eval Psel" createJ,irelessJnode Par$s@
> III
A 8
B ret!rn Pnode
/ 8
G III
20 ret!rn Pnode
22 8
class) T&en* t&e 1ariable initialiJation actions roceed downward /rom t&ere) T&e
1ariable initialiJation actions are de/ined in !ines 21H23) T&e statement FPsel"
set PvarG ?!ine 22@ seci/ies Pvar as an inst1ar o/ t&is obBect) T&e
statement reeats /or e1ery de/ault inst1ar o/ class Pcl) T&e list o/ inst1ars is
'i1en by t&e statement FPcl in"o varsG ?!ine 21@) 4lso* t&e initialiJation
actions reeats /or e1ery class in t&e inut list FclassesG ?!ine 21@)
4/ter t&e abo1e rocess comletes* t&e inst1ars in Table 12)1 would contain
roer 1alues) 6e are now ready to create mobile nodes)
%2=%=/=2 Ste& 22 Mobi#e Noe $onstruction
Similar to (e'ular Nodes* %obile Nodes are created usin' t&e instroc node
/ar$s' o/ t&e Sim!lator obBect) T&is instroc reads t&e con/i'uration stored
in t&e inst1ars o/ t&e Sim!lator obBect* and creates a %obile Node accord9
in'ly) 0nless ot&erwise seci/ied* t&e /ollowin' eAlanation would be based on
EAamle 12)1)
T&e %ain Process
Pro'ram 12): s&ows t&e details o/ t&e instroc FnodeG o/ class Sim!lator)
T&e aim o/ t&is instroc is to create a %obile Node) !ine 3 c&ecks w&et&er t&e
inst1ar Fro!tin$A$ent5G con/i'ured durin' Ste 1 eAists and is nonemty) I/
so* !ine : creates a %obile Node by in1okin' an instroc createJ,irelessJ
node/ar$s') T&e details o/ t&e instroc createJ,irelessJnode/ar$s' are
s&own in Pro'ram 12)3* w&ere t&e main statements are !ines 3* 8* 1"* 1#* and 2,*
as s&own in Ci') 12)3)
12)1 4n O1er1iew o/ 6ireless Networkin' 3,3
Simulator
create$node$instance
create$aod($a4ent
)odeN
Mobile)ode
add$interface
attach
to6o4ra6hy
)ode
Mobile)ode
Program %2=0 Instrocs createJ,irelessJnode and createJnodeJ
instance o/ class Sim!lator
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc createJ,irelessJnode ar$s 7
1 III
3 set node ?eval Psel" createJnodeJinstance Par$s@
= s,itc( Je*act Pro!tin$A$ent5 7
> AODS 7
A set ra$ent ?Psel" createJaodvJa$ent Pnode@
B 8
/ DS# 7
G Psel" at 0I0 ]]Pnode startJdsrH
20 8
22 III
21 de"a!lt 7
23 eval Pnode addr Par$s
2= p!ts HWron$ node ro!tin$ a$entCH
2> e*it
2A 8
2B 8
2/ Pnode addJinter"ace Pc(an PpropInstance5 PllType5
PmacType5 Pi"+Type5 Pi"+len5 Pp(yType5 PantType5
PtopoInstance5
2G Pnode attac( Pra$ent ?Node set rta$ent5port5@
10 Pnode topo$rap(y PtopoInstance5
12 ret!rn Pnode
11 8
13 Sim!lator instproc createJnodeJinstance ar$s 7
1= set nodeclass NodeM%obileNode
1> ret!rn ?eval ne, Pnodeclass Par$s@
1A 8
/; Line 3
//; Line &
///; Line 1
/9; Line 1B
9; Line 2!
in6ut of the
inst6roc )ode
A Node object
inst(ars set
in Ste6 1
A routing agent
A topography
object
0lass inst6roc
0reated )ode
ob7ect (to //)
0reated ,4ent
ob7ect (to /9)
)*)+

4ig= %2=* Key OTcl statements in1oked durin' an eAecution o/ t&e instroc createJ
,irelessJnode o/ class Sim!lator as s&own in Pro'ram 12)3
I) The inst&roc create#node#instance of c#ass &imulator (+ine *)
creates a %obile Node instance /rom an OTcl class FNodeM%obileG ?see
!ines 23H28 /or t&e details@)
Tab#e %2=2 Classes* OTcl commands* and 1ariables w&ic& connect t&e mobile node comonents
to'et&er
C CC c l ass O Tcl co mm and Na me o/ 1 ar i ab l e T ye o/ t & e 1 ar i ab l e
LL).iConnector !pJtar$et F!ptar$et5G NsObject
N
LL).iConnector do,nJtar$et Fdo,ntar$et5G NsObject
N
LL arptable arptable5 A#PTable
N
LL mac mac5 %ac
N
%ac neti" neti"5 P(y
N
P(y c(annel c(annel)do,ntar$et5 C(annel
N
)NsObject
N
P(y c(annel c(annel)do,ntar$et5 C(annel
N
)NsObject
N
P(y FnodeG node5 Node
N
WirelessP(y propa$ation propa$ation5 Propa$ation
N
WirelessP(y antenna ant5 Antenna
N
Topo$rap(y



c(annel



c(annel5



WirelessC(annel
N
II) The inst&roc create#aodv#agent of c#ass &imulator (+ine 6)
creates an 4O.7 routin' a'ent ?see Pro'ram 12)"@)
III) The inst&roc add#interface of c#ass Node"obileNode (+ine %7)
creates and con/i'ures %obile Node comonents as s&own in Ci') 12)2 ?see
Pro'ram 12)8@)
I7) The inst&roc attach of c#ass Node (+ine %8) attac&es t&e inut routin'
a'ent to t&e underlyin' Node obBect ?see t&e details in Pro'ram 8)18@)
7) The ,Tc# comman to%ogra%h$ of $CC c#ass obileNode (+ine
2:)
seci/ies t&e inut as a topo$rap(y obBect /or t&e %obile Node)
Patc&in' Comonents o/ %obile Nodes
T&e mobile eAtension art in Ci') 12)2 consists o/ se1eral comonents) T&ese
comonents are atc&ed to'et&er by t&e instroc addJinter"ace/III' o/ class
NodeM%obileNode)
Pro'ram 12)8 s&ows t&e details o/ t&e instroc addJinter"ace/ar$s' o/
class NodeM%obileNode) !ines 8H1, create &ysical network inter/ace* %4C*
inter/ace Dueue* link layer* and antenna obBects* as seci/ied by t&e inut
arameters)
T&e created obBects are stored in local 1ariables in !ines 13H18) !ine 12 creates
and stores an 4(P obBect in a local 1ariable Farptable5)G T&e rest o/ t&is
instroc con/i'ures %obile Node comonents as s&own in Ci') 12)2) T&ese
statements use t&e /ollowin' OTcl commands in Table 12)2* to store t&e inut
ar'uments in CCC 1ariables)
!ines 1"H1# and 28H22 create and con/i'ure a tracin' obBect FdrpT5*G w&ic&
traces acket dros accordin' to wireless trace /ormat ?see Sect) 1:)3)3@) !ine 23
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols 3,3
Program %2=6 Instroc addJinter"aces o/ class NodeM%obileNode*
w&ic& con/i'ures %obile Node comonents as s&own in Ci') 12)2
MMUnsMtclMlibMnsJmobilenodeItcl
2 NodeM%obileNode instproc addJinter"ace 7 c(annel pmodel
lltype mactype +type +len i"type anttype topo 8 7
1 Psel" instvar arptable5 ni"s5 neti"5 mac5 i"+5 ll5 III
3 set ns ?Sim!lator instance@
= set t Pni"s5
> incr ni"s5
A set neti"5&Pt' ?ne, Pi"type@ O inter"ace
B set mac5&Pt' ?ne, Pmactype@ O mac layer
/ set i"+5&Pt' ?ne, P+type@ O inter"ace +!e!e
G set ll5&Pt' ?ne, Plltype@ O link layer
20 set ant5&Pt' ?ne, Panttype@ O antanna
22 Pns macJtype Pmactype
21 set n!llA$ent5 ?Pns set n!llA$ent5@
23 set neti" Pneti"5&Pt'
2= set mac Pmac5&Pt'
2> set i"+ Pi"+5&Pt'
2A set ll Pll5&Pt'
2B set arptable5 ?ne, A#PTable Psel" Pmac@
2/ set drpT ?cm!Jtrace Drop HIQH Psel"@
2G Parptable5 dropJtar$et PdrpT
10 Pll arptable Parptable5
12 Pll mac Pmac
11 Pll do,nJtar$et Pi"+
13 Pll !pJtar$et ?Psel" entry@
1= Pi"+ tar$et Pmac
1> Pi"+ set limit5 P+len
1A set drpT ?cm!Jtrace Drop HIQH Psel"@
1B Pi"+ dropJtar$et PdrpT
1/ Pmac neti" Pneti"
1G Pmac !pJtar$et Pll
30 Pmac do,nJtar$et Pneti"
32 set $od5 ?-od instance@
31 i" 7Pmactype :: H%acM/01522H8 7
33 Pmac nodes ?P$od5 n!m5nodes@
3= 8
3> Pneti" c(annel Pc(annel
3A Pneti" !pJtar$et Pmac
3B Pneti" propa$ation Ppmodel O Propa$ation %odel
3/ Pneti" node Psel" O .ind node <JJJK inter"ace
3G Pneti" antenna Pant5&Pt'
=0 Pc(annel addi" Pneti"
=2 Pc(annel addJnode Psel"
=1 Ptopo c(annel Pc(annel
=3 Psel" addi" Pneti"
== 8
3,: 12 6ireless %obile 4d Hoc Networks
sets t&e bu//er siJe o/ t&e inter/ace Dueue) !ine 31 creates a LO. obBect ?see
Sect) 12)8)2@) Cinally* !ines 33H:3 con/i'ure t&e &ysical layer o/ t&e %obile
Node ?see Sect) 12)3@)
%2=2 Network +ayer2 Routing Agents an Routing Protoco#s
4s discussed in Sect) 8)1)1* a routin' rotocol seci/ies &ow routin' in/ormation is
roa'ated to all related nodes) T&is section discusses wireless routin' rotocols
1ia an eAamle< 4d9&oc On9.emand .istance 7ector (outin' ?4O.7@ routin'
rotocol)
12.2.1 Preliinaries for the AO). Ro!ting
Protocol
%2=2=%=% Termino#ogy
+e/ore roceedin' /urt&er* let us de/ine t&e /ollowin'
terminolo'y)
+ctiveAinactive< 4n acti1e route entry o/ a Node is a route entry w&ic& is in use
by t&e node or any o/ its nei'&bors) 4n acti1e at& consists o/ acti1e routin'
entries /rom a source to a destination) Cinally* acti1e nei'&bors are nodes
w&ic& &a1e created or /orwarded one or more ackets to a 'i1en destination
wit&in t&e most recent active timeout eriod)
&reshAstale< T&is terminolo'y is used to comare a air o/ seDuence numbers
and$or route entries) 4 seDuence number in 'reater 1alue is said to be fresh)
4 route entry wit& /res& seDuence number is said to be fresh) It is also said to be
fresh* i/ it &as eDual seDuence number and lower ?better@ number o/ &os to
reac& t&e destination) 4 node s&ould always accet fresh route entries and
discard stale routin' in/ormation)
#oute entries and routing ta'le< 4 route entry contains in/ormation o/ &ow to
reac& a destination) 4 node usually uts to'et&er all routin' entries in a table9
/ormatted database called a routing ta'le)
In 4O.7* eac& route entry contains t&e /ollowin'
/ields<
H .estination address* t&e neAt &o node* and t&e metric ?i)e)* t&e number o/
&os to t&e destination@
H SeDuence number corresondin' to t&e destination w&ic& &els re1ent a so9
called routin' loo roblem
H 4cti1e nei'&bors on t&is route entry
H EAiry time w&ic& indicates t&e duration w&ere t&is route entry is considered
fresh)
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols 3,2
%2=2=%=2 Packet Ty&es
4O.7 de/ines t&ree main tyes o/ ackets<
#oute #ECuest -##EC0< ((EI is ori'inated and broadcasted to e1ery nei'&bor
o/ a source node durin' a route disco1ery rocess) ((EI contains t&e
/ollowin' in/ormation<
H Source address ?src@ H Source seDuence number ?SN
s
@
H .estination address ?dst@ H .estination seDuence number ?SN
d
@
H +roadcast I. ?'I4@ H No) o/ &os to destination ?hop cnt@
#oute #EPly -##EP0< ((EP is a acket relied by a node) It contains routin'
in/ormation /or t&e destination seci/ied in an ((EI) ((EP contains t&e
/ollowin' in/ormation<
H Source address ?src@ H No) o/ &os to destination ?hop cnt@
H .estination address ?dst@ H .estination seDuence number ?SN
d
@
H Time w&ere t&is entry is considered 1alid ?t
eA
@
<E..(< HE!!O is a secial unsolicited ((EP acket) It robes nei'&bors
wit&in locality) HE!!O contains only two ieces o/ in/ormation< address and
seDuence number o/ t&e sender)
12.2.2 The Principles of AO).
4O.7 is a roacti1e routin' rotocol w&ic& disco1ers a route to t&e destination as
needed) It is desi'ned to sol1e t&e network loo roblem* w&ere routin' ackets
circulate inde/initely ?see Ci') 12):@) 4O.7 sol1es t&is roblem by discardin'
ackets wit& stale seDuence number) In articular* e1ery %obile Node maintains
t&ree seDuence number counters /or t&ree tyes o/ ackets< a destination counter
/or ((EP* a broadcast counter /or ((EI* and a nei'&bor9robin' counter /or
HE!!O) 4lt&ou'& used /or di//erent acket tyes* t&ese counters work under t&e
same rincile)
+e/ore creatin' a acket* a %obile Node increases its counter 1alue by one)
T&en it stams t&e acket wit& t&e incremented seDuence number and sends out
t&e acket) 4not&er %obile Node recei1in' t&e acket determines t&e /res&ness
o/ routin' ackets by comarin' t&e seDuence number) 4'ain* a routin' acket
is said to be fresh)
:
In 4O.7* di//erent seDuence numbers are drawn /rom t&ree
di//erent counters* deendin' on w&et&er t&e acket tye is ((EI* ((EP* or
HE!!O)
:
See t&e de/inition o/ F/res&G in Sect) 12)2)1)1)
D D
3,8 12 6ireless %obile 4d Hoc Networks
a /
)e> route
u6date
)e> route
, D
u6date
(1)
,
(1)
-
(1) (1)
0
- 0
, D
(2)
- 0
,
(2)
- 0
(2)
(3)
-
,
(3)
0
4ig= %2=/ 4 distance 1ector /loodin' rotocol< ?a@ Tree toolo'y H a route udate rocess
/inis&es in two stes* ?b@ !oo toolo'y H a route udate rocess continues inde/initely
a /
S S
=e(erse 6ath setu6
.or>ard 6ath setu6
Sendin4 ==+5
Settin4 u6
a route entry
'ransmission
ran4e
Sendin4 ==+P
=oute entry to
the destination
4ig= %2=0 4O.7 route disco1ery< (e1erse at& setu and /orward at&
setu
%2=2=2=% Route -iscovery2 'entifying a Route to the -estination
(oute disco1ery consists o/ two main stes ?see Ci') 12)3@) T&e /irst ste is to
locate t&e node w&ic& contains t&e reDuired routin' in/ormation) It starts w&en a
%obile Node needs routin' in/ormation) In t&is case* t&e %obile Node ?e)')* Node
FSG in Ci') 12)3@ broadcasts an ((EI acket to all its nei'&borin' nodes) 0on
t&e detection* eac& o/ t&e nei'&borin' nodes discards t&e acket i/ it is stale* and
rocesses t&e acket i/ it is /res&)
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols 3,#
Tab#e %2=* 7arious timers* t&eir actions* and t&e tri''erin' e1ents
Timer Timeout action Start$reset by
((EI timer ((EP
timer HE!!O
timer Transmission
timer
(emo1e t&e route entry
(emo1e t&e route entry
Send a HE!!O acket
(eco'niJe a broken link
Insertion o/ a re1erse at& route entry
Insertion o/ a /orward at& route entry
+roadcast HE!!O
Transmission o/ a new acket
Suose t&e acket is /res&) T&e node determines i/ it &as t&e reDuired routin'
in/ormation) I/ not* it will run t&e so9called reverse path setup rocess w&ic&
records &ow to return to t&e source node in its routin' table) T&en* t&e node will
increment t&e metric ?i)e)* t&e number o/ &os@ in t&e ((EI acket by one* and
will rebroadcast t&e ((EI acket) T&is rocess reeats until a node wit& t&e
reDuired routin' in/ormation recei1es t&e ((EI acket* w&ere t&e /irst Ste
comletes)
T&e second ste is to i''yback t&e reDuired routin' in/ormation back to t&e
source node ?e)')* Node FSG in Ci') 12)3@) It be'ins by creatin' an ((EP ?i)e)*
route rely@ acket) T&is ((EP acket is carried back to t&e source node usin' t&e
route identi/ied durin' t&e re1erse at& setu) In t&e literature* t&e second Ste is
re/erred to as forward path setup)
%2=2=2=2 Route an Neighbor Maintenance
%obile Nodes in an ad &oc network are &i'&ly dynamic) 4s t&ey mo1e* t&e list
o/ nei'&bors may c&an'e and t&e links may become broken) To kee u wit& t&e
dynamic* 4O.7 uses timers to re'ularly robe t&e network toolo'y and status)
T&ese timers are s&own in Table 12)3)
12.2." An O#er#ie& of AO). Ipleentation in
%S2
NS2 imlements a routin' rotocol usin' routin' a'ents w&ic& create* transmit*
recei1e* rocess* and destroy routin' ackets) In case o/ 4O.7* NS2 declare a
CCC class AODS as s&own in Pro'ram 12)2) Class AODS deri1es /rom class
A$ent and in&erits t&ree imortant attributes and be&a1iors< ?1@ a ointer
Ftar$et5G w&ic& oints to a link layer obBect ?see Ci') 12)2@* ?2@ a /unction
allocpkt&' w&ic& can be used to create ackets* and ?3@ a acket recetion
/unction recv&p)(') 4mon' t&ese attributes and be&a1iors* only t&e acket
recetion /unction is o1erridden by class AODS)
3
3
T&e details o/ acket recetion /unction will be discussed in Sect) 12)2)8)
3," 12 6ireless %obile 4d Hoc Networks
Program %2=5 .eclaration o/ class AODS
MMUnsMaodvMaodvI(
2 class AODS9 p!blic A$ent 7
1 nsaddr5t inde*; MMIP Address o" t(is node
3 !5int315t se+no; MMSe+!ence N!mber
= int bid; MM.roadcast ID
> aodv5rtable rtable; MM#o!tin$ table
A aodv5ncac(e nb(ead; MMA list o" active nei$(bors
B aodv5bcac(e bi(ead; MMA list o" seen .roadcast IDs
/ .roadcastTimer btimer; MM.roadcast ID timer
G HelloTimer (timer; MMHello timer
20 Nei$(borTimer ntimer; MMNei$(bor timer
22 #o!teCac(eTimer rtimer; MM#o!te e*piration timer
21 Local#epairTimer lrtimer; MMDelay be"ore ro!te "ail!re
declaration
23 aodv5r+!e!e r+!e!e; MMStore data packet d!rin$
ro!te discovery
2= Pri!e!e
N
i"+!e!e; MMA pointer to t(e inter"ace
+!e!e
2> PortClassi"ier
N
dm!*5; MMA pointer to t(e
dem!ltiple*er
2A 8
%2=2=*=% 4i#e an $#ass Structure
%ain CCC Ciles /or 4O.7 Stored in t&e .irectory Tns$aod1$
aodvIcc)( %ain de/inition o/ 4O.7 routin' a'ents
aodv5packetI( Packet &eader o/ 4O.7 routin' a'ents
aodv5rtableIcc)( 4O.7 route entry and routin' table
aodv5r+!e!eIcc)( +u//er w&ic& stores data ackets durin' a route
disco1ery rocess
4O.79(elated CCC Classes
+gent is resonsible /or creatin'* sendin'* recei1in'* rocessin'* and destroyin'
routin' ackets) 4O.7 uses class AODS /or t&ese uroses)
Timer takes care o/ time9dri1en actions) T&ese classes are .roadcastTimer*
HelloTimer* Nei$(borTimer* #o!teCac(eTimer* and Local#epair
Timer)
#outing information is stored in route entries ?classes aodv5rt5entry and
aodv5rtable@ and acket &eader /ormat ?classes (dr5aodv* (dr5aodv
5error* (dr5aodv5re+!est* and (dr5aodv5reply@)
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols 311
T ab # e %2 = / 4 O . 7 co ll ec ti ons and t &e i r C CC im l e m en t a ti o n
Class name 7ariable name 4 member o/ .ata structure Tye o/ entry
aodv5bcac(e
aodv5ncac(e
bi(ead
nb(ead
AODS
AODS
bsd link list
bsd link list
.roadcastID
AODS5Nei$(bor
aodv5prec!rsors
rt5nblist
rt5pclist
aodv5rt5entry
aodv5rt5entry bsd link list AODS5Prec!rsor
aodv5rt(ead
aodv5r+!e!e
nsaddr5t
rt(ead
r+!e!e
!nreac(able5dst?@
aodv5rtable
AODS
(dr5aodv5error
bsd link list
!ink list
4rray
aodv5rt5entry
Packet
N$4
Collections contain items o/ t&e same tye) T&ese collections include seen
broadcast I.s* acti1e nei'&bors* recursors*
8
route entries* ackets bu//ered
durin' a route disco1ery rocess* and I. o/ unreac&able destination nodes) T&e
CCC imlementation o/ t&ese collections are s&own in Table 12):* w&ere t&e
details o/ 'sd link list are 'i1en in 4endiA C)1)
%2=2=*=2 Route "ntries an Packet Heaer
NS2 stores routin' in/ormation in t&e /ollowin' elements< (oute entries ?aodv5rt
5entry@ in routin' tables ?aodv5rtable@* ((EI &eader ?(dr5aodv
5re+!est@* and ((EP &eader ?(dr5aodv5reply@* and route error reortin'
&eader ?(dr5aodv5error@) T&ese elements contain t&e in/ormation /ields s&own
below<
Leneral /ields in route entries ?aodv5rt5entry@<
H rt5dst .estination H rt5ne*t(op NeAt &o node
address
H rt5(ops %etric H rt5se+no SeD) No)
H rt5pclist Precursors H rt5nblist 4cti1e nei'&bors
H rt5re+5timeo!t 6&en I can send anot&er reDuest
H rt5re+5cnt Number o/ broadcasted ((EIs
((EI9related /ields in t&e acket &eader (dr5aodv5re+!est<
H r+5src T&e node w&ic& creates t&is ((EI
H r+5dst T&e node w&ic& t&is ((EI is destined /or
H r+5(op5co!nt Number o/ &os t&is ((EI &as tra1eled
H r+5bcast5id +roadcast I.
8
Precursors are nodes associated wit& a route entry) T&ey are t&e oosite o/ neAt &o nodes)
Precursors o/ a node FnG associated wit& a destination FdstG are t&e nodes w&ic& &a1e asked t&e
node FnG to /orward at least one acket to t&e destination Fdst)G Essentially* t&e route entry /or
t&e destination FdstG o/ t&e recursors indicates t&e neAt &o as t&e node Fn)G
31, 12 6ireless %obile 4d Hoc Networks
Program %2=7 Instroc createJaodvJa$ent o/ class Sim!lator and
OTcl command FstartG o/ class AODS
MMUnsMtclMlibMnsJlibItcl
2 Sim!lator instproc createJaodvJa$ent 7 node 8 7
1 set ra$ent ?ne, A$entMAODS ?Pnode nodeJaddr@@
3 Psel" at 0I0 HPra$ent startH
= Pnode set ra$ent5 Pra$ent
> ret!rn Pra$ent
A 8
MMUnsMaodvMaodvIcc
B int AODS99command&int ar$c) const c(ar
N
const
N
ar$v' 7
/ i"&strncasecmp&ar$v?2@) HstartH) 1' :: 0' 7
G btimerI(andle&&Event
N
' 0';
20 (timerI(andle&&Event
N
' 0';
22 ntimerI(andle&&Event
N
' 0';
21 rtimerI(andle&&Event
N
' 0';
23 ret!rn TCL5OV;
2= 8
2> III
2A ret!rn A$ent99command&ar$c) ar$v';
2B 8
((EP9related /ields in t&e acket &eader (dr5aodv5reply<
H rp5src T&e node w&ic& creates t&is ((EP
H rp5dst T&e node w&ic& t&is ((EP is destined /or
H rp5(op5co!nt Number o/ &os t&is ((EP &as tra1eled
H rp5li"etime .uration between ((EP creation and eAiration
Error /ields in t&e acket &eader (dr5aodv5error<
H DestCo!nt Number o/ unreac&able destinations
H !nreac(able5dst?@ 4ddresses o/ unreac&able destinations
H !nreac(able5dst5se+no?@ SeD) No) o/ unreac&able destinations
Note t&at /ields belon'in' to routin' table* ((EI &eader* and ((EP &eader are
re/iAed wit& Frt*G Fr+*G and Frp*G resecti1ely)
12.2.$ AO). Ro!ting Agent Constr!ction Process
4n 4O.7 routin' a'ent is created by an OTcl statement FcreateJaodv
Ja$ent/node'*G w&ere Pnode is a %obile Node w&ic& contains t&e routin'
a'ent
?e)')* see !ine 8 o/ Pro'ram 12)3@)
Pro'ram 12)" s&ows t&e details o/ instroc createJaodvJa$ent/node')
!ine 2 creates an obBect /rom an OTcl class A$entMAODS w&ic& is bound to
a CCC class AODS) 4s indicated in t&e /ile Tns$aod1$aod1)cc* t&e constructor o/
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols 313
class AODS takes node address as an inut ar'ument) !ine 3 initialiJes t&e AODS
routin' a'ent by eAecutin' its OTcl command Fstart)G In !ines #H12* t&e OTcl
command FstartG initialiJes /our key 4O.7 timers by /orcin' eAiration at t&e
current time) T&e details o/ t&e 4O.7 timers will be discussed later in Sect)
12)2)2) Cinally* !ines : and 3 store t&e created routin' a'ent in t&e inst1ar
Fra$ent5G o/ t&e inut Node obBect and returns t&e created routin' a'ent to t&e
caller)
12.2.+ ,eneral Pac'et 5lo& Mechanis in a 3ireless
%et&or'
Packets can 'enerally be classi/ied into data ackets and routin' ackets) 6&ile t&e
/ormer is created by transort layer a'ents* t&e latter is created by routin' a'ents)
Section 12)1)2 eAlains t&e data acket /low mec&anism* assumin' t&at t&e routin'
a'ent contains a route entry /or t&e destination under interest) I/ t&e routin' a'ent
does not &a1e t&e route entry* it will bu//er t&e acket temorarily* initiate a route
disco1ery rocess* and wait /or t&e routin' in/ormation) Once t&e in/ormation is
a1ailable* it will transmit t&e data ackets bu//ered earlier)
(outin' acket /low mec&anism be'ins /rom wit&in a routin' a'ent durin'
a route disco1ery rocess) 4/ter t&e incetion* a routin' acket is con/i'ured
accordin' to t&e 4O.7 rotocol described in Sect) 12)2)2) T&en* it is assed to
t&e lower9layer obBects /or transmission o1er t&e air) In case o/ 4O.7* routin'
ackets are marked wit& ayload tye PT5AODS) In addition* t&eir &eader tyes
can be AODST[PE5##E /or ((EI ackets* AODST[PE5##EP /or ((EP
ackets* AODST[PE5##E /or route error reortin' ackets* and
AODST[PE5HELLO /or HELLO ackets)
12.2./ Pac'et Reception and Processing 5!nction of
AO).
Cunction recv&p)(' is central to 4O.7 acket /low mec&anism) It is
eAecuted to recei1e bot& data and routin' ackets in bot& uward and downward
directions) Pro'ram 12)# s&ows t&e details o/ t&is /unction) !ine : determines
w&et&er t&e incomin' acket ?
N
p@ is a routin' acket ?i)e)* PT5AODS@) I/ so* !ine
8 rocesses t&e 4O.7 acket by in1okin' t&e /unction recvAODS&p')
Ot&erwise* t&e acket
N
p must be a data acket) In t&is case* !ines #H21 re9rocess t&e data acket
and
!ines 22H23 send o// t&e acket)
T&e re9rocessin' !ines #H21 include addition o/ an IP &eader
2
?!ine 11@*
settin' t&e TT! 1alue ?!ine 13@* and droin' acket i/ it circulates in a network
loo ?!ines 13H18@ or i/ its TT! reac&es Jero ?!ine 1#@) To send a acket* !ine 22
312 12 6ireless %obile 4d Hoc Networks
2
TCP and its 4CK also include IP &eader into t&e acket) 6e do not need to add IP &eader &ere)
Ot&erwise* we would &a1e added t&e IP &eader twice ?See !ine 1,@)
12)2 Network !ayer< (outin' 4'ents and (outin' Protocols 313
Program %2=8 Cunction recv&p)(' class
AODS
MMUnsMaodvMaodvIcc
2 void AODS99recv&Packet
N
p) Handler
N
' 7
1 str!ct (dr5cmn
N
c( : HD#5C%N&p';
3 str!ct (dr5ip
N
i( : HD#5IP&p';
= i"&c(JKptype&' :: PT5AODS' 7
> i(JKttl5 J: 2;
A recvAODS&p';
B ret!rn;
/ 8
G i"&&i(JKsaddr&' :: inde*' FF &c(JKn!m5"or,ards&' :: 0'' 7
20 i" &c(JKptype&' C: PT5TCP FF c(JKptype&' C: PT5ACV'
22 c(JKsi6e&' 4: IP5HD#5LEN;
21 i" & &!5int315t'i(JKdaddr&' C: IP5.#OADCAST'
23 i(JKttl5 : NETWO#V5DIA%ETE#;
2= 8 else i"&i(JKsaddr&' :: inde*' 7
2> drop&p) D#OP5#T#5#ODTE5LOOP';
2A ret!rn;
2B 8 else 7
2/ i"&JJi(JKttl5 :: 0' 7
2G drop&p) D#OP5#T#5TTL'; ret!rn;
10 8
12 8
11 i" & &!5int315t'i(JKdaddr&' C: IP5.#OADCAST'
13 rt5resolve&p';
1= else
1> "or,ard&&aodv5rt5entry
N
' 0) p) NO5DELA[';
1A 8
determines t&e acket tye) I/ t&e acket is a broadcast acket* !ine 23 will call
t&e /unction "or,ard&rt)p)delay' to send t&e acket) Ot&erwise* !ine 23
will call t&e /unction rt5resolve&p' w&ic& in1okes a route disco1ery
rocess and send out t&e acket once t&e routin' in/ormation is a1ailable)
6&en an incomin' acket is an 4O.7 routin' acket* !ine 8 o/ Pro'ram 12)#
in1okes /unction recvAODS&p' t&e details o/ w&ic& are s&own in Pro'ram
12)1,) !ine 3 insects 4O.7 &eader tye o/ t&e incomin' acket* and in1okes
one o/ t&e /ollowin' /unctions< recv#e+!est&p'* recv#eply&p'*
recvError&p'* or recvHello&p') T&ese /unctions er/orm 4O.7
oeration as discussed earlier in Sect) 12)2)2) T&e readers are encoura'ed to see
t&e details o/ t&ese /unctions in t&e /ile Tns$aod1$aod1)cc)
12.2.4 AO). Tie()ri#en
Actions
4not&er imortant art o/ t&e 4O.7 rotocol is to take time9based actions) T&ese
actions are to remo1e outdated in/ormation ?e)')* broadcast I.s* route entries*
acti1e
31: 12 6ireless %obile 4d Hoc Networks
Program %2=%: Cunction recvAODS&p' o/ class AODS
MMUnsMaodvMaodvIcc
2 void AODS99recvAODS&Packet
N
p' 7
1 str!ct (dr5aodv
N
a( : HD#5AODS&p';
3 s,itc(&a(JKa(5type' 7
= case AODST[PE5##E9
> recv#e+!est&p';
A break;
B case AODST[PE5##EP9
/ recv#eply&p';
G break;
20 case AODST[PE5#E##9
22 recvError&p';
21 break;
23 case AODST[PE5HELLO9
2= recvHello&p';
2> break;
2A de"a!lt9
2B "print"&stderr) HInvalid AODS type &E*'TnH) a(JKa(5type';
2/ e*it&2';
2G 8
10 8
Tab#e %2=0 Timers* t&eir class 1ariables* and t&eir eAiration actions
Class name 7ariable name 4'ent actions
.roadcastTimer btimer Call a$entJKid5p!r$e&'* i)e)*
ur'e all eAired broadcast I. /rom t&e list)
HelloTimer (timer Call a$entJKsendHello&'* i)e)*
send out a HELLO messa'e)
Nei$(borTimer ntimer Call a$entJKnb5p!r$e&'* i)e)*
ur'e inacti1e nei'&bors /rom t&e list)
#o!teCac(eTimer rtimer Call a$entJKrt5p!r$e&'* i)e)*
ur'e stale route entries /rom t&e routin' table)
Local#epairTimer lrtimer H I/ t&e route is down* call a$entJKrt5do,n&rt'*
w&ere rt is a route entry w&ose destination is
seci/ied in t&e &eader o/ t&e incomin' acket
N
p


H .

es

t ro

y

t &

e

i nco

m

i n

'

ac

k

et


N
p)
nei'&bors@* and are imlemented usin' /i1e CCC timers in Table 12)3* w&ere
Fa$entG is a ointer to t&e 4O.7 a'ent containin' t&e timer ?see t&e timer
imlementation in Sect) 13)1@)
4ll timers eAcet /or Local#epairTimer are /orced to eAire at t&e node
construction ?see !ines #H12 in Pro'ram 12)"@) 4t t&e eAiration* t&ese timers
take eAiration actions as s&own in Table 12)3 and restart t&emsel1es) T&e Local
#epairTimer obBect* on t&e ot&er &and* is started w&en t&e routin' a'ent
sends out an ((EI acket) I/ t&e corresondin' ##EP acket is recei1ed be/ore
t&e timer eAires* t&e timer will be stoed and not&in' will &aen) I/* on t&e
ot&er &and* t&e
12)3 .ata !ink !ayer< !ink !ayer %odels* 4ddress (esolution Protocols))) 313
route entry is still down by t&e time t&e timer eAires* t&e corresondin'
destination will be declared as unreac&able by eAecutin' Fa$entJ
Krt5do,n&rt')G
%2=* -ata +ink +ayer2 +ink +ayer Moe#s3 Aress Reso#ution
Protoco#s3 an 'nterface ?ueues
T&is section /ocuses on t&e t&ree NS2 modules located at t&e .ata !ink !ayer<
!ink layer* 4ddress (esolution Protocols ?4(P@* and Inter/ace Iueues ?see Ci')
12)2@)
12.".1 Lin' Layer O-8ects
!ink layer obBects model se1eral c&aracteristics at t&e link layer suc& as link band9
widt&* roa'ation delay* and acket /ramin' ?e)')* seDuence number*
acknowled'e number@) It brid'es t&e routin' layer ?i)e)* routin' a'ent@ to t&e %4C
layer)
In NS2* link layer obBects are imlemented usin' a CCC class LL w&ic& is
bound to t&e OTcl class wit& t&e same name) Pro'ram 12)11 s&ows its CCC
class declaration and t&e details o/ its /unction recv&p)(') T&e CCC class LL
deri1es /rom class LinkDelay ?see also Sect) 2)2@) It in&erits bandwidt& and
delay attributes /rom t&e class LinkDelay) It is also resonsible /or link9layer
acket /ramin' ?e)')* embeddin' seDuence number in !ine 3 and acknowled'e
number in !ine : into acket &eaders@) It contains two imortant ointers H
Fmac5G in !ine 2 ointin' to a %edium 4ccess Control ?%4C@ obBect and
Farptable5G in !ine " ointin' to an 4ddress (esolution Protocol ?4(P@
obBect) 4s discussed in Sect) 12)1)3* class LL &as two ointers9
Fdo,ntar$et5G and F!ptar$et5G w&ic& connect to t&e lower and uer layer
obBects* resecti1ely)
!ines 12H2: s&ow t&e details o/ t&e /unction recv&p)(' o/ class LL) T&e
rocess is Duite strai'&t/orward /or downward transmission usin' t&e /unction
sendDo,n&p' ?!ines 22 and 23@) Cor uward transmission* class LL
classi/ies ackets into 4P( ackets and non94(P ackets) !ine 1# sends non9
4(P ackets u t&e &ierarc&y usin' sendDp&p') I/ t&e incomin' acket is an
4(P acket* !ine 12 will ask t&e 4(P obBect to &andle t&e acket by callin' its
/unction arpinp!t&p)t(is')
12.".2 Address Resol!tion Protocol
In ractice* a Node needs to translate an IP address to a &ardware address /rom
time to time) To do so* it looks u t&e so9called 4(P table /or t&e address
translation) I/ t&e reDuired translation entry does not eAist in t&e table* it may ask
/or t&e entry /rom
318 12 6ireless %obile 4d Hoc Networks
Program %2=%% .eclaration and details o/ t&e /unction recv&p)(' o/ class
LL
MMUnsM+!e!eMpri+!e!eI(
2 class LL 9 p!blic LinkDelay 7
1 protected9
3 int se+no5; MM linkJlayer se+!ence n!mber
= int ackno5; MM ACV received so "ar
> int macDA5; MM destination %AC address
A !e!e
N
i"+5; MM inter"ace +!e!e
B %ac
N
mac5; MM %AC object
/ A#PTable
N
arptable5; MM A#P table object
G NsObject
N
do,ntar$et5; MM "or o!t$oin$ packet
20 NsObject
N
!ptar$et5; MM "or incomin$ packet
22 8
MMUnsM+!e!eMpri+!e!eIcc
21 void LL99recv&Packet
N
p) Handler
N
'
23 7
2= (dr5cmn
N
c( : HD#5C%N&p';
2> i"&c(JKdirection&' :: (dr5cmn99DP' 7
2A i"&c(JKptype5 :: PT5A#P'
2B arptable5JKarpinp!t&p) t(is';
2/ else
2G !ptar$et5 Y sendDp&p' 9 drop&p';
10 ret!rn;
12 8
11 c(JKdirection&' : (dr5cmn99DOWN;
13 sendDo,n&p';
1= 8
t&e ot&er nodes) T&e rotocol w&ic& asks /or translation /rom an IP address to an
&ardware address is called an +ddress #esolution Protocol -+#P0* w&ile t&e
re1ersal rotocol /or translatin' &ardware addresses to IP addresses is called
(e1erse 4(P ?(4(P@ M21N)
NS2 imlements 4(Ps usin' two CCC classes) Class A#PEntry models
address translation record* w&ile class A#PTable contains a link list o/
A#PEntry and takes all 4(P9related actions ?see t&e /iles Tns$mac$ar)&*cc@)
T&e address translation rocess roceeds as /ollows)
Suose Node 4 would like to determine a &ardware address o/ a 'i1en IP
address) Node 4 calls /unction arpresolve&dst)p)ll' to ut t&e &ardware
address corresondin' to an IP 4ddress FdstG in t&e acket
N
p) I/ Node 4 does
not contain main' in/ormation /or t&e address Fdst*G it sends an +#P re,uest
acket usin' t&e /unction arpre+!est&src)dst)ll') T&e acket is sent to
t&e air 1ia t&e down9tar'et o/ t&e LL obBect* Fll)G
"
"
T&e rocess byasses t&e LL obBect to a1oid any alteration ?e)')* seDuence number@ at t&e
link9 layer obBect)
12): %edium 4ccess Control !ayer< IEEE ",2)11 312
Suose an 4(P reDuest acket arri1es at Node +) T&e acket is deli1ered
uward until it reac&es t&e LL obBect) In t&is case* t&e acket direction would
be FDPG and t&e ayload tye o/ t&e acket would be FPT5A#P)G In t&is case*
t&e statement Farp5JKarpinp!t&p)t(is'G s&all be eAecuted ?!ine 12 in
Pro'ram 12)11@) I/ t&e acket
N
p is an 4(P reDuest acket and t&e &ardware
address to be translated is stored in t&e /ield Farp5tpa*G t&e A#PTable obBect
will create and transmit a 4(P rely acket) I/* on t&e ot&er &and* t&e incomin'
acket
N
p is an 4(P rely acket* t&e A#PTable obBect will look /or t&e
address main' in/ormation in t&e 4(P rely acket* embed t&e &ardware
address in t&e acket &eader* and transmit t&e constructed acket) T&e details o/
t&e abo1e 4(P oeration can be /ound in Tns$mac$ar)&*cc)
Note t&at class A#PTable de/ines a ointer F(old5G to &old a acket w&ile
waitin' /or an 4(P rely acket) I/ anot&er acket enters t&e A#PTable be/ore
t&e 4(P rely acket returns* t&e earlier bu//ered acket would be droed ?i)e)*
F(old5G will oint to t&e new acket@)
12."." Interface >!e!es
Section 2)3 discusses t&e rinciles o/ Dueue and bu//er mana'ement) In wired
networks* a Dueue is installed in eac& o/ SimpleLink obBects) In a wireless
network* a Dueue is installed in eac& o/ t&e wireless &ysical inter/ace) T&is is t&e
reason NS2 calls a Dueue in a wireless network an interface ,ueue)
T&e most widely used Dueue tye in wireless networks is prioriti"ed ,ueues)
NS2 imlements a rioritiJed Dueue in t&e CCC class Pri!e!e) T&is class
deri1es /rom class DropTail and is bounded to t&e OTcl class w&ose name
is !e!eMDropTailMPri!e!e) PrioritiJed Dueues oerate /airly similar to
dro9tail Dueues discussed in Sect) 2)3) +ut t&ey enDueues &i'&9riority and low9
riority ackets at t&e &ead and at t&e end o/ t&e Dueue* resecti1ely) +y de/ault*
&i'&9riority ackets include routin' ackets w&ose ayload tyes are PT5DS#*
PT5TO#A* PT5AODS* PT5AO%DS* and PT5%DA#T) Packets wit& ot&er ayload
tyes are treated as low9riority ackets) T&e readers are encoura'ed to 'o t&rou'&
t&e details o/ class Pri!e!e in t&e /iles Tns$Dueue$riDueue)&*cc)
%2=/ Meium Access $ontro# +ayer2 '""" 7:2=%%
4 %edium 4ccess Control ?%4C@ rotocol de/ines communications rules to
w&ic& %obile Nodes comly wit& to access a s&ared medium) Lenerally* %4C
rotocol can be classi/ied into random %4C rotocols and deterministic %4C
rotocols) NS2 imlements T.%4 ?Time .i1ision %ultile 4ccess@ %4C
rotocols and IEEE ",2)11 %4C rotocols /or deterministic and random %4C
rotocols* resec9 ti1ely ?see t&e directory Tns$mac@)
31" 12 6ireless %obile 4d Hoc Networks
a
Medium
-usy
D/.S
P/.S
S/.S
-ac1off
Medium
-usy
D/.S
-ac1off
Pac1et
'ransmission
% 4 3
2 1 !
+acko// mec&anism
b
Sender
=ecei(er
D/.S
='S
S/.S
0'S
S/.S
D,',
S/.S
,0P
S/.S
D,',
Hearin4 ='S
),9
*thers
Hearin4 0'S
Hearin4 Data
),9
),9
Collision a1oidance and network allocation 1ector ?N47@ allocation
4ig= %2=6 .istributed coordination /unction in IEEE ",2)11
T&is section eAlains %4C rotocol imlementation 1ia an eAamle* t&e
standard IEEE ",2)119based %4C M3#N* w&ic& is used widely in wireless local
area networks) T&e details /or t&e T.%4 %4C rotocol can be /ound in t&e /iles
Tns$mac$mac9 tdma)&*cc)
12.$.1 )escription of I*** ?D2.11 MAC Protocol
IEEE ",2)11 .CC consists o/ t&ree main mec&anisms< contention window adBust9
ment* back9o// mec&anisms* and collision a1oidance ?C4@) Once a %obile Node is
turned on* it initialiJes a state 1ariable called contention window to its minimum
1alue ?CWmin@) T&e contention window is doubled /or e1ery transmission /ailure
until it reac&es t&e maAimum 1alue ?CWma*@) I/ t&e transmission is success/ul or i/
t&e acket is droed due to t&e retry limit* t&e contention window will be reset to
CWmin)
Ci'ure 12)8a illustrates t&e back9o// mec&anism in t&e IEEE ",2)11 .CC %4C)
4/ter window adBustment* t&e .CC %4C rotocol icks a random back9o// 1alue
uni/ormly distributed between , and C6* w&ere C6 is t&e 1alue o/ t&e current
contention window) T&is back9o// 1alue is t&e number o/ idle time slots w&ere a
%obile Node &as to wait be/ore commencin' a transmission)
4not&er mec&anism o/ IEEE ",2)11 .CC is Collision +voidance ?C4@*
w&ic& uses two mec&anisms< /our9way &ands&ake and InterCrame Sace ?ICS@) In
Ci') 12)8b* t&e /our9way &ands&ake met&od transmits (TS* CTS* .4T4* and
4CK
ackets in seDuence) Here* a sender intendin' to transmit data /irst transmits a
(eady To Send ?(TS@ acket) 0on recei1in' an (TS acket* t&e recei1er
transmits a Clear To Send ?CTS@ acket back to t&e sender) T&en* t&e sender can
start sendin' a .4T4 acket) Cinally* t&e recei1er in/orms t&e sender o/
success/ul .4T4 acket recetion by sendin' back an 4CKnowled'ment ?4CK@
acket) .esite its ability to &andle hidden node$e%posed node roblem M:,N* t&is
&ands&ake mec&anism incurs non9ne'li'ible o1er&ead) IEEE ",2)11 acti1ates t&is
mec&anism /or lar'e ackets only)
InterCrame Sace ?ICS@ is an inacti1ity eriod at w&ic& a %obile Node must
sense be/ore startin'$resumin' its backo// mec&anism) T&e len't& o/ ICS de9
ends on acket tyes) I/ t&e /our9way &ands&ake is acti1ated* it will be .ICS
?.istributed ICS@ /or (TS ackets* and SICS ?S&ort ICS@ /or ot&er ackets) Ot&9
erwise* it will be .ICS and SICS /or .4T4 and 4CK ackets* resecti1ely)
Since SICS is s&orter t&an .ICS* t&e collision occurs w&en sendin' (TS ackets
only)
In IEEE ",2)11* e1ery acket contains a Network +llocation ?ector ?N47@
/ield) 4n N47 /ield contains t&e duration durin' w&ic& t&e %obile Node is
eAected to take o1er t&e c&annel) 0on o1er&earin' any o/ t&ese ackets* all
%obile Nodes* eAcet t&e intended recei1er* re/rain /rom transmittin' any acket
until t&e end o/ eriod seci/ied in t&e N47)
12.$.2 %S2 Classes ac and ac012
33
In NS2* t&e IEEE ",2)11 %4C is imlemented usin' a CCC class %ac/01522
w&ic& deri1es /rom an abstract class %ac) Pro'ram 12)12 s&ows t&e declarations
o/ bot& t&e classes %ac and %ac/01522)
In class %ac* 1ariables Fneti"5*G Fll5*G and Fc(annel5G are t&ree
1ariables w&ic& connect to ot&er obBects in t&e %obile Node arc&itecture ?see Ci')
12)2@) T&e 1ariable Fintr5G is a dummy 1ariable used wit& 1arious timer
obBects) Pointers Fpkt#*5G and FpktT*5G oint to ackets w&ic& s&all be
recei1ed and transmitted later ?see also Sect) 12):)3@)
In t&e deri1ed class ?%ac/01522@* two ot&er ointers H Fpkt#TS5G and
FpktCT#L5G H are also used to store an (TS acket and an CTS acket or an
4CK acket* resecti1ely* be/ore acket transmission ?see !ines 3" and 3#@) T&e
1ariables Fstate5G ?!ine 13@* Fr*5state5G ?!ine 32@* and Ft*5state5G
?!ine 33@ indicate t&e current state o/ t&e %ac obBect* and t&e transmission and
recetion states o/ t&e %ac/01522 obBect* resecti1ely) T&e list o/ ossible
states is s&own below<
%AC5IDLE %AC5POLLIN- %AC5#ECS %AC5SEND %AC5#TS
%AC5.CN %AC5CTS %AC5ACV %AC5COLL %AC5%-%T
w&ere %AC5COLL and %AC5%-%T stand /or collision and
mana'ement)
32, 12 6ireless %obile 4d Hoc Networks
3/ Packet
N
pkt#TS5; MM Cac(ed o!t$oin$ #TS packet
3G Packet
N
pktCT#L5; MM Cac(ed o!t$oin$ nonJ#TS
Program %2=%2 .eclaration o/ classes %ac and %ac/01
22
MMUnsMmacMmacI(
2 class %ac 9 p!blic .iConnector 7
1 p!blic9
3 %ac&';
= inline int addr&' 7 ret!rn inde*5; 8
> protected9
A int inde*5; MM %AC address
B do!ble band,idt(5; MM C(annel bitrate in bps
/ do!ble delay5; MM %AC over(ead
G P(y
N
neti"5; MM Net,ork inter"ace object
20 LL
N
ll5; MM Link layer object
22 C(annel
N
c(annel5; MM C(annel object
21 Event intr5; MM A d!mmy event
23 %acState state5; MM C!rrent state
2= Packet
N
pkt#*5; MM Cac(ed incomin$ packet
2> Packet
N
pktT*5; MM Cac(ed data packet to be TL
2A 8;
MMUnsMmacMmacJ/01522I(
2B class %ac/01522 9 p!blic %ac 7
2/ p!blic9
2G %ac/01522&';
10 protected9
12 PH[5%I. p(ymib5; MMP(ysical layer %I.
11 %AC5%I. macmib5; MM%AC layer %I.
13 private9
1= #*Timer m(#ecv5; MM ItZs time to receive
1> T*Timer m(Send5; MM #eTL timeo!t) i" applicable
1A IQTimer m(IQ5; MM TL complete timer
1B .acko""Timer m(.acko""5; MM .acko"" timer
1/ De"erTimer m(De"er5; MM De"er TL by IQS periods
1G NavTimer m(Nav5; MM Net,ork Allocation Sector
30 do!ble data#ate5; MM Data rate
32 do!ble nav5; MM Time ,(en NAS e*pires
31 %acState r*5state5; MM Incomin$ state
33 %acState t*5state5; MM O!t$oin$ state
3= int t*5active5; MM Is t(e transmitter ACTISEY
3> !5int315t c,5; MM C!rrent contention Windo,
3A !5int315t ssrc5; MM #etry Co!nt "or a s(ort
packet
3B !5int315t slrc5; MM #etry Co!nt "or a lon$
packet
=0 8;
packet
!ines 21 and 22 declare two %ana'ement In/ormation +ase ?%I+@ 1ariables
w&ic& contain t&e basic in/ormation about t&e IEEE ",2)11 module<
Class PH[5%I. de/ines &ysical layer %I+* wit& t&e /ollowin' key
1ariables< ?CW%in*CW%a*@ T&e smallest and t&e lar'est contention
window siJe SlotTime T&e len't& o/ a time slot
SIQSTime T&e len't& o/ an SICS inter1al
Class %AC5%I. de/ines %4C layer %I+* wit& t&e /ollowin' key 1ariables<
#TST(res(old Packets w&ose len't& is 'reater t&an
#TST(res(old bytes are considered as lon' ackets)
S(ort#etryLimit %aA) re9transmissions /or a s&ort acket
Lon$#etryLimit %aA) re9transmissions /or a lon' acket
!ines 2:H2# de/ine t&e /ollowin' siA timers w&ic& &el carry out siA time9
based actions< Packet recetion timer ?m(#ecv5@* (etransmission timer
?m(Send5@* Transmission comlete timer ?m(IQ5@* +acko// timer
?m(.acko""5@* %edium sensin' timer ?m(De"er5@* and N47 timer
?m(Nav5@)
T&e 1ariables Fdata#ate5G and Fnav5G ?!ines 3, and 31@ de/ine &ysical
data rate in bs* and t&e duration in seconds durin' w&ic& t&e node needs to
re/rain /rom transmittin' and$or recei1in') T&e 1ariable Ft*5active5G ?!ine
3:@ indicates w&et&er t&e node is currently en'a'ed in acket transmission) 4
wireless node cannot recei1e any acket w&ile transmittin' due to its sel/
inter/erence) Cinally* t&e 1ariables Fc,5*G Fssrc5*G and Fslrc5G store t&e
current contention window siJe* and t&e retransmission counters /or s&ort and lon'
ackets* resecti1ely ?!ines
33H32@)
12.$." 2asic 5!nctions of %S2 Classes ac and ac012 33
Classi/ied into /i1e cate'ories* t&ese /unctions are s&own below<
5ain functions>
recv&p)('<
(ecei1e a acket
N
p wit& a &andler
N
()
send&p)('<
Send a acket
N
p wit& a &andler
N
( in a downward direction)
transmit&p)timeo!t'<
Send a acket
N
p to t&e Fdo,ntar$et5)G Start t&e retransmission
timer wit& a Ftimeo!tG eriod)
collision&p'<
Called w&en t&e acket
N
p collides wit& t&e acket bein' recei1ed
Fpkt#*5*G t&is /unction takes actions accordin' to Sect) 12):)1)
322 12 6ireless %obile 4d Hoc Networks
Packet preparation functions>
Cunctions send#TS&dst'* sendCTS&dst)d!r'* sendDATA&p'*
and sendACV&dst' reare and store t&e (TS* CTS* .4T4*
and 4CK ackets in 1ariables
N
pkt#TS5*
N
pktCT#L5*
N
pktT*5*
and
N
pktCT#L5* resecti1ely)
Packet transmission functions>
Cunctions c(eck5pktCT#L&'* c(eck5pkt#TS&'* and c(eck
5pktT*&' insect t&e rele1ant cac&ed CTS$4CK$(TS$.4T4
acket*
and in1okes transmit&p)timeo!t' to transmit t&e acket i/ t&e
medium is /ree) Ot&erwise* it starts t&e IEEE ",2)11 backo//
rocess)
Packet retransmission functions>
Cunctions #etransmit#TS&' and #etransmitDATA&' incre9
ment and c&eck w&et&er t&e retransmission counter ?i)e)* Fssrc5G or
Fslrc5G@ eAceeds t&e limit) I/ so* t&ey will dro t&e acket* and reset
t&e counter and contention window siJe) Ot&erwise* it will increment
t&e contention window siJe* and start t&e backo// timer)
Packet reception functions>
Heler /unctions recv#TS&'* recvCTS&'* recvDATA&'* and
recvACV&' are in1oked to take necessary actions w&en one o/ t&e
(TS$CTS$.4T4$4CK ackets is recei1ed)
#esume functions>
t* res!me&'< (esume endin' transmissionO
Case -new transmission0< T&is /unction is in1oked a/ter t&e
c&annel is sensed idle /or a .ICS eriod o/ time) It initiates a
backo// rocess usin' t&e backo// timer)
Case 2 -continuing transmission0< T&is /unction /rom wit&in one o/
t&e abo1e acket recetion /unctions) It starts t&e medium sensin'
timer wit& a arameter SICS)
r* res!me&'< ?Pendin' recetion@
T&is /unction is in1oked w&en t&e acket arri1es) It sets t&e state to
%AC5IDLE* i)e)* t&e %obile Node is ready to recei1e anot&er acket)
Idleness functions>
Cunction is5idle&' will return 1 ?idle@* i/ bot& Fr*5state5G
and Ft*5state5G are %AC5IDLE* and t&e N47 1alue stored in t&e
1ariable Fnav5G is less t&an t&e current time ?i)e)* medium is idle@)
Ot&erwise* it will return , ?'usy@) In NS2 imlementation* idleness
re/ers not only to t&e medium but also to t&e entire %ac/01522
obBect includin' t&e transmittin' as well as t&e recei1in' states)
12): %edium 4ccess Control !ayer< IEEE ",2)11 323
12.$.$ Tier Concepts for Ipleentation of I*** ?D2.11
IEEE ",2)11 imlementation relies &ea1ily on timers) To er/orm an action ?e)')*
send or recei1e a acket@* a %ac/01522 records w&at to do in its 1ariables and
starts rele1ant timers) T&e action will later be er/ormed w&en t&e timer eAires)
4s discussed in Sect) 12):)2* class %ac/01522 uses siA timers) Table 12)8
s&ows t&e imlementation details o/ t&ese timers) Here* t&e /irst column s&ows
t&e class names as well as t&e names o/ t&e %ac/01522 class 1ariables /or eac&
timer) T&e second column s&ows t&e /unctions o/ class %ac/01522 w&ic& starts
eac& timer as well as t&e corresondin' timeout) T&e /inal column s&ows t&e
imlication o/ timer eAiration as well as t&e main eAiration actions) 4t t&e
eAiration* all t&e timers reset t&eir 1ariables and in1oke a /unction associated wit&
t&e attac&ed %ac/01522 obBect) Names o/ t&e /unctions as well as t&e key
actions /or eac& timer are s&own in t&is column)
12.$.+ Pac'et Reception Mechanis of I*** ?D2.11
T&e mec&anism o/ t&e /unction recv&p)(' o/ class %ac/01522 in Pro9
'ram 12)13 roceeds based on t&e /ollowin' t&ree cases<
$ase %2 Transmitting Packet to +ower +ayer ,b1ects 9sing
send)%+h*
In t&is case* t&e %obile Node intends to transmit a acket) T&e acket arri1es t&e
%ac/01522 obBect /rom t&e &i'&er layer) T&e acket direction would be
DOWN ?!ine : o/ Pro'ram 12)13@* and !ine 3 in1okes t&e /unction send&p)('
to send out t&e acket)
In Pro'ram 12)1:* t&e /unction send&p)(' contains instructions /or sendin'
a acket
N
p recei1ed /rom t&e uer layers) T&is imlies t&at t&e acket ?
N
p@ is a
new data acket) .urin' acket rearation rocess* !ine 3 recon/i'ures t&e
acket
N
p and stores it in t&e 1ariable
N
pktT*5* and !ine 8 creates and stores an (TS
acket in t&e 1ariable
N
pkt#TS5) Cinally* !ines 2H13 start t&e backo// timers)
T&e transmission o/ t&e reared acket will be carried out once t&e timer eAires)
In Table 12)8* at t&e eAiration* a backo// timer eAecutes t&e /unction
backo""Handler&' o/ t&e associated %ac/01522 obBect ?see !ines 13H2,
in Pro'ram 12)1:@) 4'ain* at t&e eAiration o/ a backo// timer* t&e %ac/01522
obBect is allowed to transmit eAactly one acket) I/ eit&er CTS or 4CK is waitin'
to be transmitted in
N
pktCT#L5* t&is /unction would do not&in'* since t&eir
transmission can commence a/ter a eriod o/ SICS* wit&out backin' o//)
#
In t&is
#
I/ t&is is t&e case* t&e acket would &a1e been transmitted be/ore t&e timer eAiration)
32: 12 6ireless %obile 4d Hoc Networks
Tab#e %2=6 IEEE ",2)11 timers and t&eir starter /unctions* timeout* and eAiration imlication
and actions
Timer Starter /unction and timeout EAiration imlication
Packet recetion timer<
H Class .
#*Timer
H 7ariable .
m(#ecv
(etransmission timer<
H Class .
T*timer
H 7ariable .
m(Send
Transmission
comletion timer<
H Class .
IQtimer
H 7ariable .
m(IQ
%edium sensin' timer<
H Class .
De"erTimer
H 7ariable .
m(De"er
+acko// timer<
H Class .
.acko""Timer
H 7ariable .
m(.acko""
N47 timer<
H Class .
NavTimer
H 7ariable .
m(Nav
Case 1) collision&p'
Timeout . t&e maA) o/
transmission time o/ two
collidin' ackets)
Case 2) recv&p'
Timeout . Transmission
time o/ acket
N
p<
transmit&p)timeo!t'
Timeout . timeo!t
transmit&p)timeo!t'
Timeout . Transmission time
o/ acket
N
p
t*
res!me&'
Timeout . SICS
Case 1) send&p)('
Case 2) c(eck
pkt#TS&'* Case 3) c(eck
pktT* &' Case :) t*
res!me&'
Case 3) recvACV&p'
Timeout . +acko// 1alue
recv
timer&'
Timeout .
Case 1< EICS ?transmission
error or acket collision@
Case 2< N47 ?normal
acket recetion@
Implication<
T&e last bit o/ t&e acket
&as arri1ed)
+ctions<
H recvHandler&'
W recv timer&'
H Call t&e rele1ant acket
recetion /unction)
Implication<
T&e acket is lost)
+ctions<
H sendHandler&'
Wsend timer&'<
H I/ CTS or 4CK was
transmitted* /ree t&e acket)
Ot&erwise* retransmit t&e
(TS or .4T4 acket usin'
a retransmission /unction)
Implication<
T&e last bit o/ t&e acket is
transmitted)
+ctions<
H tAHandler?@
W Set t* active to ,
Implication<
T&e medium &as been idle
/or a eriod o/ SICS)
+ctions<
H de"erHandler&'
H Try to transmit a acket
usin' one o/ t&e acket
transmission /unctions)
Implication<
+acko// reac&es its Jero 1alue)
+ctions<
H backo""Handler&'
H Try to transmit a acket
usin' one o/ t&e acket
transmission /unctions)
Implication<
T&e medium is idle)
+ctions<
H navHandler&'
H (esume t&e backo// timer)
Program %2=%* Cunction recv&p)(' o/ class %ac/01
22
MMUnsMmacMmacJ/01522Icc
2 void %ac/0152299recv&Packet
N
p) Handler
N
('
1 7
3 str!ct (dr5cmn
N
(dr : HD#5C%N&p';
= i"&(drJKdirection&' :: (dr5cmn99DOWN' 7
> send&p)('; ret!rn;
A 8
B i"&t*5active5 FF (drJKerror&' :: 0'
/ (drJKerror&' : 2;
G i"&r*5state5 :: %AC5IDLE' 7
20 set#*State&%AC5#ECS';
22 pkt#*5 : p;
21 m(#ecv5Istart&t*time&p'';
23 8 else
2= collision&p';
2> 8
Program %2=%/ Cunctions send&p)(' and backo""Handler&' o/ class
%ac/01 22
MMUnsMmacMmacJ/01522Icc
2 void %ac/0152299send&Packet
N
p) Handler
N
('
1 7
3 do!ble rTime;
= str!ct (dr5mac/01522
N
d( : HD#5%AC/01522&p';
> sendDATA&p';
A send#TS&ETHE#5ADD#&d(JKd(5ra'';
B i"&m(.acko""5Ib!sy&' :: 0'
/ i"&is5idle&''
G i" &m(De"er5Ib!sy&' :: 0'
20 m(.acko""5Istart&c,5) is5idle&')
22 p(ymib5I$etDIQS&'';
21 else
23 m(.acko""5Istart&c,5) is5idle&'';
2= 8
2> void %ac/0152299backo""Handler&'
2A 7
2B i"&pktCT#L5' ret!rn;
2/ i"&c(eck5pkt#TS&' :: 0' ret!rn;
2G i"&c(eck5pktT*&' :: 0' ret!rn;
10 8
case* !ine 12 would return &ere) On t&e ot&er &and* i/ t&e %ac/01522 obBect
contains neit&er CTS nor 4CK ackets* !ines 1" and 1# will* in seDuence* c&eck
and try to transmit eit&er an (TS acket or a .4T4 acket* resecti1ely)
328 12 6ireless %obile 4d Hoc Networks
$ase 22 Receiving a Packet from a +ower +ayer
,b1ect
In t&is case* a acket reac&es t&e idle %obile Node /rom t&e air inter/ace) T&e
acket direction would be !p) Crom Pro'ram 12)13* a/ter c&eckin' /or idleness in
!ine #* !ine 1, sets t&e recei1in' states to %AC5#ECS* !ine 11 stores t&e
incomin' acket in t&e 1ariable
N
pkt#*5* and starts t&e acket recetion timer
Fm(#ecv5G wit& t&e timeout bein' acket transmission time ?i)e)* t*ttime&p'
in !ine 12@)
Crom Table 12)8* t&e eAiration action is to eAecute /unction recv5timer&'
w&ose details are s&own in Pro'ram 12)13) !ines 23H3" determine t&e acket tye
and in1oke rele1ant acket recetion /unctions) T&ese /unctions clean u t&e
current transmission 1ariables and reare t&e neAt acket /or transmission* i/ any)
Cinally* !ine :, clears t&e 1ariable Fpkt#*5G and calls t&e /unction
r*5res!me&' w&ic& sets recei1in' state to %AC5IDLE ?!ine ::@)
$ase *2 Se#f.'nterference anEor $o##ision
T&is case is comlementary to Case 2) Packets arri1e /rom t&e air inter/ace but are
unsuccess/ully recei1ed) T&ere are two causes o/ error< Sel/9inter/erence and
acket collision) Consider Pro'ram 12)13) !ines 2 and " mark t&e acket to be in
error due to sel/9inter/erence*
1,
i/ t&e transmitter o/ t&e %ac/01522 obBect is
acti1e* w&ile recei1in' a acket)
Packet collision occurs since t&e %ac/01522 is busy w&ile recei1in' a
acket) Here* a acket
N
p collides wit& t&e acket under recetion
N
pkt#*5)
0nder a noncaturin' model* bot& t&e ackets would be lost) +ut t&e loss would
not be realiJed immediately) It would be realiJed once t&e %ac/01522 obBect
recei1es t&e entire acket and is unable to understand t&e contaminated acket)
Pro'ram 12)18 s&ows t&e details o/ /unction collision&p') In !ines 2H13*
t&is /unction dros t&e s&orter acket* kees t&e lon'er acket in
N
pkt#*5* and
sets Fr*5state5G to %AC5COLL) 4'ain* once t&e acket recetion timer
eAires* t&e /unction recv5timer&' would be eAecuted* and !ines 11H13 o/
Pro'ram 12)13 will dro t&e acket
N
pkt#*5 since t&e recei1in' state was set to
%AC5COLL)
12.$./ Ipleentation of Pac'et Retransission in %S2
Class %ac/01522 uses a retransmission timer* ?i)e)* m(Send5 in Table
12)8@ stored in a class 1ariable Fm(Send5G to control acket retransmission)
T&is timer starts e1ery time a acket is transmitted usin' t&e /unction
transmit &p)timeo!t') It is stoed uon t&e recetion o/ eAected
ackets usin' /unc9 tions recvCTS&p'* recvDATA&p'* and recvACV&p') I/
t&e retransmission
1,
Sel/9inter/erence is a wireless roerty* w&ere t&e transmittin' si'nal inter/eres wit& t&e
12): %edium 4ccess Control !ayer< IEEE ",2)11 322
recei1in' si'nal)
328 12 6ireless %obile 4d Hoc Networks
Program %2=%0 Cunctions recv timer&' and r* res!me&' o/ class
%ac/01 22
MMUnsMmacMmacJ/01522Icc
2 void %ac/0152299recv5timer&'
1 7
3 (dr5cmn
N
c( : HD#5C%N&pkt#*5';
= (dr5mac/01522
N
m( : HD#5%AC/01522&pkt#*5';
> !5int315t dst : ETHE#5ADD#&m(JKd(5ra';
A !5int/5t type : m(JKd(5"cI"c5type;
B !5int/5t s!btype : m(JKd(5"cI"c5s!btype;
/ i"&t*5active5' 7
G Packet99"ree&pkt#*5'; $oto done;
20 8
22 i"&r*5state5 :: %AC5COLL' 7
21 discard&pkt#*5) D#OP5%AC5COLLISION';
23 set5nav&!sec&p(ymib5I$etEIQS&''';
2= $oto done;
2> 8
2A i"& c(JKerror&' ' 7
2B Packet99"ree&pkt#*5';
2/ set5nav&!sec&p(ymib5I$etEIQS&''';
2G $oto done;
10 8
12 i"&dst C: &!5int315t'inde*5'
11 set5nav&m(JKd(5d!ration';
13 s,itc(&type' 7
1= case %AC5Type5Control9
1> s,itc(&s!btype' 7
1A case %AC5S!btype5#TS9
1B recv#TS&pkt#*5';break;
1/ case %AC5S!btype5CTS9
1G recvCTS&pkt#*5';break;
30 case %AC5S!btype5ACV9
32 recvACV&pkt#*5';break;
31 8; break;
33 case %AC5Type5Data9
3= s,itc(&s!btype' 7
3> case %AC5S!btype5Data9
3A recvDATA&pkt#*5';break;
3B 8; break;
3/ 8
3G done9
=0 pkt#*5 : 0;
=2 r*5res!me&';
=1 8
=3 void %ac/0152299r*5res!me&'
== set#*State&%AC5IDLE';
=> 8
12): %edium 4ccess Control !ayer< IEEE ",2)11 32#
Program %2=%6 Cunction collision&' o/ class %ac/01 22
MMUnsMmacMmacJ/01522Icc
2 void %ac/0152299collision&Packet
N
p'
1 7
3 s,itc(&r*5state5' 7
= case %AC5#ECS9
> set#*State&%AC5COLL';
A case %AC5COLL9
B i"&t*time&p' K m(#ecv5Ie*pire&'' 7
/ m(#ecv5Istop&';
G discard&pkt#*5) D#OP5%AC5COLLISION';
20 pkt#*5 : p;
22 m(#ecv5Istart&t*time&pkt#*5'';
21 8
23 else 7
2= discard&p) D#OP5%AC5COLLISION';
2> 8
2A 8
2B 8
Program %2=%5 Cunction send timer&' o/ class %ac/01 22
MMUnsMmacMmacJ/01522Icc
2 void %ac/0152299send5timer&'7
1 s,itc(&t*5state5' 7
3 case %AC5#TS9
= #etransmit#TS&'; break;
> case %AC5CTS9
A Packet99"ree&pktCT#L5';
B pktCT#L5 : 0; break;
/ case %AC5SEND9
G #etransmitDATA&'; break;
20 case %AC5ACV9
22 Packet99"ree&pktCT#L5';
21 pktCT#L5 : 0; break;
23 case %AC5IDLE9
2= break;
2> 8
2A t*5res!me&';
2B 8
is not stoed be/ore its eAiration* /unction send5timer&' will be in1oked to
retransmit t&e acket)
Pro'ram 12)12 s&ows details o/ t&e /unction send5timer&') !ines 2H13
reares a acket to transmit* and !ine 18 calls t&e /unction t*5res!me&' to
resume t&e endin' backo// rocess) T&e details o/ t&e /unction t*5res!me&'
are s&own in Pro'ram 12)1")
Cor t&e acket rearation rocess* !ine 2 determines t&e 1alue stored in
t&e 1ariable Ft*5state5)G I/ t&e 1alue o/ t*5state5 is eit&er %AC5#TS
32" 12 6ireless %obile 4d Hoc Networks
Program %2=%7 Cunction t* res!me&' o/ class %ac/01 22
MMUnsMmacMmacJ/01522Icc
2 void %ac/0152299t*5res!me&'
1 7
3 do!ble rTime;
= i"&pktCT#L5'
> m(De"er5Istart&p(ymib5I$etSIQS&'';
A else i"&pkt#TS5'
B i" &m(.acko""5Ib!sy&' :: 0'
/ m(.acko""5Istart&c,5) is5idle&')
p(ymib5I$etDIQS&'';
G else i"&pktT*5'
20 i" &m(.acko""5Ib!sy&' :: 0' 7
22 (dr5cmn
N
c( : HD#5C%N&pktT*5';
21 str!ct (dr5mac/01522
N
m( : HD#5%AC/01522&pktT*5';
23 i" &&!5int315t' c(JKsi6e&' <
macmib5I$et#TST(res(old&'
XX&!5int315t' ETHE#5ADD#&m(JKd(5ra' ::
%AC5.#OADCAST'
2= m(.acko""5Istart&c,5) is5idle&')
p(ymib5I$etDIQS&'';
2> else
2A m(De"er5Istart&p(ymib5I$etSIQS&'';
2B 8;
2/ setT*State&%AC5IDLE';
2G 8
or %AC5SEND H meanin' eit&er (TS or .4T4 ackets were transmitted
and not acknowled'ed H !ines : and # will in1oke t&e rele1ant /unctions /or
acket retransmission) T&ese two /unctions /irst increment t&e retransmission
counter ?i)e)* eit&er Fssrc5G or Fslrc5G@ by one* c&eck its 1alue a'ainst t&e
retry limit* and retransmit$dro t&e acket) Note t&at CTS and 4CK ackets
reDuire no acknowl9 ed'ment) T&ere/ore* !ines 8H2 and 11H12 simly destroy
t&e acket stored in
N
pktCT#L5)
12.$.4 Ipleentation of Carrier(SensingA 2ac'offA and
%A.
%2=/=5=% Basic $arrier Sensing
NS2 imlements medium sensin' and backo// mec&anism usin' timers stored in
1ariables Fm(De"er5G and Fm(.acko""5*G resecti1ely) Crom Table 12)8*
t&ese two timers can be started /rom wit&in one o/ /i1e /unctions o/ class
%ac/01522) T&e details about /i1e timer9starter /unctions are s&own in Table
12)2)
Carrier sensin' in NS2 takes one o/ t&e /ollowin' t&ree 1alues) Cirst* /or a new
transmission* t&e duration is t&e addition o/ .ICS and t&e current content window
12)3 P&ysical !ayer< P&ysical Network Inter/aces and C&annel 331
Tab#e %2=5 Initiation details /or backo// and medium sensin' timers
Timer duration w&en
t&e %4C layer is
Cunctions w&ere t&e
timer is started Timer tye I.!E +0S;
Cunctions in1oked be/ore
t&e timer is started
send&p)(' m(.acko""5 c,5>.ICS c,5 None
c(eck5pktT*&'
c(eck5pkt#TS&'
m(.acko"" , c, inc c,&'
recvAck&' m(.acko""5 c,5 c,5 rst5c,&'
t*5res!me&'
H CTS$4CK
H (TS
H .4T4 ?s&ort@
H .4T4 ?lon'@
m(De"er5
m(.acko""5
m(.acko""5
m(De"er5
SICS
c,5>.ICS
c,5>.ICS
SICS
SICS
c,5>.ICS
c,5>.ICS
SICS
None
None
None
None
?c,5@) T&is is t&e case /or a transmission o/ (TS or s&ort .4T4 acket w&ere
t&e (TS$CTS &ands&ake is not reDuired be/ore acket transmission) Second*
a/ter t&e /irst acket transmission* t&e %ac/01522 takes o1er t&e medium by
reducin' t&e medium sensin' time /rom .ICS to SICS) T&is is t&e case /or
CTS ackets* 4CK ackets* and lon' .4T4 ackets) Cinally* a/ter a success/ul
acket transmission* an 4CK acket is recei1ed) Here* t&e %ac/01522 resets
t&e contention window usin' t&e /unction rst5c,&'* and starts backin' o// /or
a eriod o/ Fc,5G be/ore bein' able to commence anot&er acket transmission)
T&e eAiration o/ t&e abo1e two timers si'ni/ies t&e end o/ t&e medium sensin'
and backo// eriods) 4t t&e eAiration* t&e %ac/01522 obBect is allowed to
transmit one acket) Crom Table 12)8* at t&e eAiration* backo// and medium
sensin' timers eAecute t&e /unctions backo""Handler&' and
de"erHandler&'* resecti1ely o/ class %ac/01522)
%2=/=5=2 Pausing an Resuming Backoff Timer
IEEE ",2)11 decreases t&e backo// counter /or e1ery idle time slot) T&ere/ore* t&e
CCC class .acko""Timer imlements t&e concet o/ pausing and resuming
as /ollows<
+e/ore backo//< T&e second inut ar'ument o/ /unction start&c,)idle)
d!r' o/ class .acko""Timer indicates w&et&er t&e associated
%ac/01522 is idle) I/ so* t&e backo// rocess would roceed as normal)
Ot&erwise* t&e .acko""Timer would Bust ause t&e timer* but would not
lace a timer eAiration e1ent on t&e simulation time line)
Periodic backo// status c&eck< Class %ac/01522 de/ines a /unction c(eck
.acko""Timer&' w&ic& auses and resumes t&e backo// timer
Fm(.acko""5*G i/ t&e %ac/01522 obBect is busy and idle* resecti1ely)
T&is
33, 12 6ireless %obile 4d Hoc Networks
/unction is called /or e1ery time t&e recei1in' ?i)e)* set#*State&s'@ and
sendin' ?i)e)* setT*State&s'@ states o/ t&e %ac/01522 c&an'e)
11
%2=/=5=* Network A##ocation >ector
Network 4llocation 7ector is t&e duration durin' w&ic& t&e medium is eAected to
be busy) T&is duration takes one o/ t&e two /ollowin' 1alues<
4n ad1ertised N47 1alue< 0on o1er&earin' a acket intended to ot&er nodes*
t&e %ac/01522 obBect can eAtract and use a 1alue in t&e /ield
Fd(5d!rationG as its N47 1alue ?see !ines 21 and 22 in Pro'ram 12)13@)
EICS< I/ t&e recei1ed acket is in error or t&e collision &as occurred* t&e
%ac/01522 cannot eAtract an N47 1alue /rom t&e acket) In t&is case* it
uses EICS as a de/ault N47 1alue ?see !ine 13 and 1" in Pro'ram 12)13@)
Class %ac/01522 de/ines a /unction set5nav&nav' to set its N47 1alue
and to start t&e NavTimer obBect) Once eAired* t&e NavTimer obBect c&ecks
w&et&er t&e %ac/01522 is idle* and resume t&e .acko""Timer* i/ so)
%2=0 Physica# +ayer2 Physica# Network 'nterfaces an $hanne#
!ocated at t&e bottom o/ Ci') 12)2* t&ese two %obile Node comonents reresent
t&e &ysical layer) P&ysical network inter/aces are t&e &ardware ?e)')* radio
modem* antenna@ w&ic& creates and sends out data bits* w&ile c&annels model t&e
medium s&ared by all %obile Nodes)
12.+.1 Physical %et&or' Interface
Pro'ram 12)1# s&ows declaration o/ an abstract class P(y and its deri1ed class*
namely* WirelessP(y) T&ese two classes model transmittin' and recei1in'
&ardware) T&e class P(y transmits$recei1es data /rom a
N
node5 obBect in !ine "
to t&e
N
c(annel5 obBect in !ine 1,* usin' t&e bit rate seci/ied by
Fband,idt(5G in !ine #) .eri1in' /rom class .iConnector* class P(y
contains two ointers F!ptar$et5G and Fdo,ntar$et5)G 6&ile t&e
F!ptar$et5G oints to t&e uer %obile node comonent* Fdo,ntar$et5G is
not in use) Class P(y instead uses its ointer Fc(annelG to re/er to t&e attac&ed
c&annel)
11
T&e state c&an'es /rom wit&in t&e /unctions recv&p)('* collision&p'* r* res!me&'*
t* res!me&'* and all acket transmission /unctions)
12)3 P&ysical !ayer< P&ysical Network Inter/aces and C&annel 333
Program %2=%8 .eclaration o/ classes P(y and
WirelessP(y
MMUnsMmacMp(yI(
2 class P(y 9 p!blic .iConnector 7
1 p!blic9
3 P(y&';
= void recv&Packet
N
p) Handler
N
(';
> virt!al void sendDo,n&Packet
N
p':0;
A virt!al int sendDp&Packet
N
p':0;
B protected9
/ Node
N
node5; MM T(e o,ner o" t(is neti"
G do!ble band,idt(5; MM .it rate in bps
20 C(annel
N
c(annel5; MM T(e c(annel "or o!tp!t
22 8;
MMUnsMmacM,irelessJp(yI(
21 class WirelessP(y 9 p!blic P(y 7
23 p!blic9
2= void sendDo,n&Packet
N
p';
2> int sendDp&Packet
N
p';
2A protected9
2B do!ble Pt5; MM TL si$nal po,er &W'
2/ do!ble "re+5; MM Si$nal "re+!ency
2G do!ble lambda5; MM Si$nal ,avelen$t( &m'
10 do!ble L5; MM System loss "actor
12 do!ble CST(res(5; MM Carrier sense t(res(old &W'
11 do!ble #LT(res(5; MM #eceive po,er t(res(old &W'
13 Antenna
N
ant5; MM Antenna
1= Propa$ation
N
propa$ation5; MM Propa$ation %odel
1> %od!lation
N
mod!lation5; MM %od!lation mod!le
1A 8;
T&e acket recetion /unction recv&p)(' ?!ine :@ is in1oked to recei1e
ackets comin' /rom bot& uer and lower layers) T&e class P(y contains two
ure 1irtual /unctions H sendDo,n&p' and sendDp&p' H w&ic& s&all be
o1erridden by its deri1ed class WirelessP(y ?!ines 3 and 8@)
Class WirelessP(y deri1es /rom class P(y) It o1errides t&e /unctions
send Do,n&p' and sendDp&p'* w&ic& send t&e ackets downward and
uward ?!ines 1: and 13@* resecti1ely) It also de/ines se1eral wireless roerties
suc& as transmission ower ?Pt5@ or transmittin' si'nal /reDuency ?"re+5@ as
s&own in !ines 12 and 1"* resecti1ely)
Class WirelessP(y de/ines two imortant t&res&olds< a carrier9sensin'
t&res&9 old ?CST(res(5 in !ine 21@ and a acket recetion t&res&old
?#LT(res(5 in !ine 22@) I/ t&e recei1ed si'nal is below FCST(res(5*G it is
considered undetectable) I/* on t&e ot&er &and* t&e si'nal is 'reater t&an
FCST(res(5G but still below F#LT(res(5*G it is detectable but t&e recei1ed
acket is considered to be in error) Only w&en t&e si'nal is 'reater t&an
F#LT(res(5G will t&e acket be considered success/ully recei1ed)
332 12 6ireless %obile 4d Hoc Networks
Program %2=2: .eclaration o/ classes C(annel and WirelessC(annel
MMUnsMmacMc(annelI(
2 class C(annel 9 p!blic TclObject 7
1 p!blic9
3 C(annel&void';
= str!ct i"5(ead i"(ead5; MM Listenin$ p(yI neti"I
> virt!al void recv&Packet
N
p) Handler
N
';
A 8;
B class WirelessC(annel 9 p!blic C(annel7
/ p!blic9
G WirelessC(annel&void';
20 private9
22 %obileNode
N
*ListHead5; MMListenin$ nodes
21 int n!mNodes5; MMN!mber o" listenin$ nodes
23 void sendDp&Packet
N
p) P(y
N
t*i"';
2= %obileNode
NN
$etA""ectedNodes&%obileNode
N
mn)
do!ble radi!s) int
N
n!mA""ectedNodes';
2> void addNodeToList&%obileNode
N
mn';
2A void removeNodeQromList&%obileNode
N
mn';
2B 8;
12.+.2 3ireless Channels
CCC class C(annel and its deri1ed class WirelessC(annel model s&are
&ysical medium) 4s s&own in Pro'ram 12)2,* class C(annel &as one
imortant 1ariable Fi"5(eadG ?!ine :@ w&ic& is t&e &ead o/ a link list containin'
all &ysical network inter/ace listenin' on t&is c&annel) It &as one imortant
/unction recv&p')
Class WirelessC(annel recei1es ackets 1ia t&e /unction recv&p)(')
0on recei1in' a acket* it con/i'ures and returns t&e acket to all listenin'
nodes usin' /unction sendDp&p)t*i"'* w&ere
N
t*i" is a wireless
transmittin' &ysical inter/ace obBect ?!ines 13@)
Class WirelessC(annel stores all listenin' nodes in a link list w&ose &ead
is stored in its 1ariable F*ListHead5G ?!ine 11@) T&e total number o/ listenin'
nodes is denoted by t&e 1ariable Fn!mNodes5G ?!ine 12@) Class
WirelessC(annel also ro1ides a ublic /unction
$etA""ectedNodes&mn)radi!s)n!m5an' returns a ointer to a list o/
%obile Node a//ected by transmission o/ a %obile Node
N
mn w&ose transmission ran'e is Fradi!s)G T&e resultin' number o/ a//ected
nodes are stored in
N
n!mA""ectedNodes)
12.+." Sender Operations at the Physical Layer
On t&e sender side* a &i'&er9layer %obile Node comonent ?a %ac obBect in
most cases@ sends a acket to t&e &ysical network inter/ace) T&e network
inter/ace sets u &ysical layer arameters and /orwards t&e acket to t&e c&annel)
T&is oeration be'ins wit& t&e eAecution o/ /unction recv&p)(' o/ t&e Class
P(y)
12)3 P&ysical !ayer< P&ysical Network Inter/aces and C&annel 333
Program %2=2% Cunction recv&p' o/ class P(y* /unction sendDo,n&p' o/
class
WirelessP(y* and /unction recv&p)(' o/ class C&annel
MMUnsMmacMp(yIcc
2 void P(y99recv&Packet
N
p) Handler
N
'
1 7
3 str!ct (dr5cmn
N
(dr : HD#5C%N&p';
= s,itc(&(drJKdirection&'' 7
> case (dr5cmn99DOWN 9
A sendDo,n&p'; ret!rn;
B case (dr5cmn99DP 9
/ i" &sendDp&p' :: 0' 7
G Packet99"ree&p';
20 ret!rn;
22 8 else
21 !ptar$et5JKrecv&p) &Handler
N
' 0';
23 8
2= 8
MMUnsMmacM,irelessJp(yIcc
2> void WirelessP(y99sendDo,n&Packet
N
p'
2A 7
2B pJKt*in"o5Istamp&&%obileNode
N
'node&') ant5JKcopy&')
Pt5) lambda5';
2/ c(annel5JKrecv&p) t(is';
2G 8
MMUnsMmacMc(annelIcc
10 void C(annel99recv&Packet
N
p) Handler
N
('
12 7
11 sendDp&p) &P(y
N
'(';
13 8
Pro'ram 12)21 s&ows t&e details o/ t&e /unction recv&p)(') !ines 3 and :
determine t&e acket direction) Cor downward acket transmission* !ine 8 eA9
ecutes FsendDo,n&p'G and returns) 4s s&own in !ines 13H1#* t&e /unction
sendDo,n&p' embeds 1arious in/ormation H includin' t&e sendin' node*
antenna* transmission ower* and si'nal wa1elen't& H in t&e acket &eader ?!ine
12@* and sends t&e acket to t&e attac&ed Fc(annel5G ?!ine 1"@) 0on recei1in'
a acket* t&e Fc(annel5G starts eAecutin' recei1er oerations)
12.+.$ Recei#er Operations at the Physical Layer
On t&e recei1in' side* t&e rocess starts w&en t&e c&annel recei1es a acket 1ia its
/unction recv&p') Crom !ines 2,H23 o/ Pro'ram 12)21* t&e /unction recv&p'
simly calls /unction sendDp&p)(' o/ class WirelessC(annel to send
t&e acket uward)
33: 12 6ireless %obile 4d Hoc Networks
Program %2=22 Cunction sendDp&p)ti"p' o/ class WirelessC(annel
MMUnsMmacMc(annelIcc
2 void WirelessC(annel99sendDp&Packet
N
p) P(y
N
ti"p'
1 7
3 Sc(ed!ler Fs : Sc(ed!ler99instance&';
= P(y
N
ri"p : i"(ead5Il(5"irst;
> Node
N
tnode : ti"pJKnode&';
A Node
N
rnode : 0;
B Packet
N
ne,p;
/ do!ble propdelay : 0I0;
G str!ct (dr5cmn
N
(dr : HD#5C%N&p';
20 %obileNode
N
mtnode : &%obileNode
N
' tnode;
22 %obileNode
NN
a""ectedNodes;MM
NN
aN;
21 int n!mA""ectedNodes : J2) i;
23 (drJKdirection&' : (dr5cmn99DP;
2= a""ectedNodes : $etA""ectedNodes&mtnode) distCST5 4
>) Fn!mA""ectedNodes';
2> "or &i:0; i < n!mA""ectedNodes; i44' 7
2A rnode : a""ectedNodes?i@;
2B i"&rnode :: tnode'
2/ contin!e;
2G ne,p : pJKcopy&';
10 propdelay : $et5pdelay&tnode) rnode';
12 ri"p : &rnodeJKi"(ead&''Il(5"irst;
11 "or&; ri"p; ri"p : ri"pJKne*tnode&''
13 sIsc(ed!le&ri"p) ne,p) propdelay';
1= 8
1> delete ?@ a""ectedNodes;
1A Packet99"ree&p';
1B 8
S&own in Pro'ram 12)22* t&e /unction sendDp&p)ti"p' sends t&e acket
N
p
to t&e all a//ected nodes) !ine 13 c&an'es t&e acket direction to uward) !ine
1: retrie1es t&e list o/ a//ected nodes and stores t&e &ead ointer in a 1ariable
Fa""ectedNodes)G !ines 13H2: con/i'ure and coy t&e incomin' ackets to all
alicable network inter/aces) Cinally* a/ter sendin' coies o/ t&e incomin' acket
to all t&e a//ected nodes* !ine 28 destroys t&e incomin' acket)
T&e acket coyin' and /orwardin' rocess in !ines 13H2: are eAecuted /or
eac& o/ t&e a//ected nodes) !ines 18H1" ski t&e loo i/ t&e current a//ected node
?rnode@ is t&e node w&ic& sent t&is acket ?tnode@) !ine 1# creates a coy o/
t&e incomin' acket) !ine 2, comutes roa'ation delay /rom t&e sendin' node
to t&e a//ected node) !ines 21H23 send t&e coied acket to all &ysical network
inter/ace o/ t&e a//ected node wit& roa'ation delay FpropdelayG seconds)
!ine 23 does not immediately send out t&e acket) (at&er* it sc&edules a acket
recetion e1ent at t&e WirelessP(ysical obBect at FpropdelayG seconds
in /uture) 6&en t&e acket recetion e1ent is disatc&ed* t&e coied acket is
deli1ered to t&e &ysical network inter/ace 1ia t&e /unction recv&p' de/ined in
t&e class P(y ?see Pro'ram 12)21@)
12)8 4n Introduction to Node %obility 332
Program %2=2* Cunction sendDp&p' o/ class WirelessP(y
MMUnsMmacM,irelessJp(yIcc
2 int WirelessP(y99sendDp&Packet
N
p'
1 7
3 PacketStamp s;
= do!ble Pr; int pkt5recvd : 0;
> Pr : pJKt*in"o5I$etT*Pr&';
A i"&propa$ation5' 7
B sIstamp&&%obileNode
N
'node&') ant5) 0) lambda5';
/ Pr : propa$ation5JKPr&FpJKt*in"o5) Fs) t(is';
G i" &Pr < CST(res(5' 7
20 pkt5recvd : 0;
22 $oto DONE;
21 8
23 i" &Pr < #LT(res(5' 7
2= (dr5cmn
N
(dr : HD#5C%N&p';
2> (drJKerror&' : 2;
2A 8
2B 8
2/ i"&mod!lation5' 7
2G (dr5cmn
N
(dr : HD#5C%N&p';
10 (drJKerror&' : mod!lation5JK.itError&Pr';
12 8
11 pkt5recvd : 2;
13 DONE9
1= ret!rn pkt5recvd;
1> 8
On t&e recei1er side* t&e direction o/ incomin' acket is uward) Crom Pro'ram
12)21* !ine " eAecutes /unction sendDp&p' to reare t&e acket
N
p /or
recetion) T&e /unction sendDp&p' returns t&e number o/ recei1ed ackets
w&ose si'nal is su//iciently stron') I/ t&e number is 'reater t&an Jero* !ine 12 will
deli1er t&e acket to t&e uer layer obBects ?e)')* a %ac obBect@) Ot&erwise* !ines
# and 1, will destroy t&e acket and return)
Pro'ram 12)23 s&ows t&e details o/ /unction sendDp&p' o/ class Wireless
P(y) !ine 3 /irst retrie1es t&e transmission ower /rom t&e acket &eader and
stores t&e retrie1ed ower in a local 1ariable FPr)G I/ t&e roa'ation model eAists*
!ine " comutes t&e recei1ed ower and stores t&e result in a local 1ariable FPr)G
!ines # and 13 c&eck w&et&er t&e recei1ed si'nal ower eAceeds t&e rede/ined
t&res&olds) I/ below t&e carrier sense t&res&old ?i)e)* CST(res(5@* t&e si'nal is
considered undetectable) In t&is case* !ine 1, would set t&e number o/ recei1ed
ackets to be Jero) I/* on t&e ot&er &and* t&e si'nal is detectable but still less t&an
a recei1in' t&res&old ?i)e)* #LT(res(5@* t&e acket will be marked as in error
?!ine 13@) NeAt* i/ t&e modulation sc&eme eAists* !ine 2, will a'ain c&eck
w&et&er t&e assumed modulation sc&eme can tolerate t&e si'nal weakness* and
udate t&e error /la' on t&e acket &eader) I/ detectable* re'ardless o/ w&et&er
t&ey are in error* t&e acket will be deli1ered to and &andled later by uer layer
obBects) In t&is case* t&e 1ariable Fpkt5recvdG is set to 1)
338 12 6ireless %obile 4d Hoc Networks
Program %2=2/ %obility con/i'uration o/ mobile nodes
MMUnsMtclMe*MsimpleJ,irelessItcl
2 set topo ?ne, Topo$rap(y@
1 Ptopo load5"lat$rid >00 >00
3 createJ$od Pval&nn'
= "or 7set i 08 7Pi < Pval&nn' 8 7incr i8 7
> set node5&Pi' ?Pns5 node@
A Pnode5&Pi' randomJmotion 0;O disable random
motion
B 8
/ Pnode5&0' set L5 >I0
G Pnode5&0' set [5 1I0
20 Pnode5&0' set \5 0I0
22 Pnode5&2' set L5 3G0I0
21 Pnode5&2' set [5 3/>I0
23 Pnode5&2' set \5 0I0
2= Pns5 at >0I0 HPnode5&2' setdest 1>I0 10I0 2>I0H
2> Pns5 at 20I0 HPnode5&0' setdest 10I0 2/I0 2I0H
2A Pns5 at 200I0 HPnode5&2' setdest =G0I0 =/0I0 2>I0H
%2=6 An 'ntrouction to Noe Mobi#ity
Introduced earlier in Sect) 12)1)1* class %obileNode de/ines se1eral attributes
to suort mobility) In Pro'ram 12)1* t&e 1ariables FL5*G F[5*G and F\5G ?!ines
:@ reresent t&e current node coordinate) T&e 1ariable Fspeed5G ?!ine 3@ is
t&e node seed in meters er second) T&ese /our 1ariables are bound to t&e
inst1ars in t&e OTcl domain wit& t&e same name) +y de/ault* a %obile Node
udates its osition /or e1ery inter1al o/ Fposition5!pdate5interval5G
seconds ?!ine 1,@) !ine 1: de/ines a ointer FT5G to a Topo$rap(y obBect
w&ic& de/ines t&e area w&ere t&e node is mo1in') Cinally* !ine 13 stores t&e
&ead ointer Flink5G o/ a 'lobal link list w&ic& contains ointers to all ac9
ti1e %obile Nodes) Note t&at alt&ou'& de/ined* t&e FSG dimension is not used
in NS2)
12./.1 2asic Mo-ility Config!ration
4s s&own in Pro'ram 12)2:* t&e basic mobility con/i'uration consists o/ /our main
stes<
Step ! Topology creation< !ine 1 creates a Topolo$y obBect and !ine 2
identi/ies t&e area w&ere t&e %obile Node will mo1e durin' t&e simulation)
12)8 4n Introduction to Node %obility 33#
Step 2 ! D(4 configuration< !ine 3 creates a LO. obBect* and in/orms t&e
LO.
obBect t&at t&e simulation contains Pval&nn'
nodes)
12
Step $ ! .ocation initiali"ation< !ines "H13 seci/y node location in all t&ree
dimensions)
Step / ! 5o'ility pattern specification< !ine 8 indicates t&at t&e mobility model
in t&is simulation will be deterministic) !ines 1:H18 seci/y &ow t&e %obile
Nodes mo1e usin' t&e instroc setdest/III' o/ t&e OTcl class
%obileNode w&ose syntaA is as /ollows<
Pnode setdest <dest5*K <dest5yK <speedK
T&is OTcl command tells t&e %obile Node Pnode to mo1e toward t&e des9
tination ?<dest5*K*<dest5yK@ wit& seed F<speedKG meters er second*
by settin' t&e 1ariables FdestL5*G Fdest[5*G and Fspeed5G o/ t&e CCC
%obileNode obBect* resecti1ely)
12./.2 ,eneral Operation )irector
LO. stands /or Leneral Oeration .irector ?LO.@ is an omniscient entity w&ic&
knows all t&e en1ironmental in/ormation* esecially t&at w&ic& s&ould not made
a1ailable to simulation obBects) LO. &els simli/y system analysis in some case
w&ere we assume er/ect in/ormation ?e)')* er/ect c&annel state in/ormation
?CSI@@)
In mobile networkin'* LO. recomutes t&e mo1ement o/ all t&e nodes and
t&e distance ?in &os@ between two nodes be/ore simulation) 4t run9time*
simulation obBects reDuest t&e distance between a air o/ nodes* only w&en
necessary) T&is reduces t&e need to simulate node mo1ement in real9time* t&ereby
'reatly decreasin' t&e usa'e o/ simulation resource ?e)')* CP0 time and
memory@) .esite its use/ulness* ro'rammers s&ould be cautious* not to make
in/ormation a1ailable to simulation obBects) Cor eAamle* %obile Nodes s&ould
not retrie1e t&e network toolo'y ma /rom LO.) (at&er* t&ey s&ould use t&e
underlyin' routin' rotocol /or t&is urose)
4'ain* LO. is con/i'ured usin' t&e /ollowin' 'lobal rocedure<
createJ$od <n!m5nodesK
w&ere <n!m5nodesK is t&e number o/ mobile nodes in a simulation ?see t&e
details in !ines 1H" Pro'ram 12)23@)
!ines #H1# in Pro'ram 12)23 s&ow a art o/ class -od declaration) Crom !ine
18* t&e 1ariable Finstance5G is declared as static to 'uarantee t&e
uniDueness
o/ t&e one and only one LO. obBect in a simulation) T&e 1ariable Fn!m5nodesG
12
See LO. descrition in Sect) 12)8)2)
33" 12 6ireless %obile 4d Hoc Networks
Program %2=20 T&e 'lobal rocedure createJ$od and t&e declaration o/ a
CCC
class -od
MMUnsMtclMmobilityMcomItcl
2 proc createJ$od 7 nodes 8 7
1 set $od ?-od in"o instances@
3 i" 7 P$od :: HH 8 7
= set $od ?ne, -od@
> 8
A P$od n!m5nodes Pnodes
B ret!rn P$od
/ 8
MMUnsMmobileM$odI(
G class -od 9 p!blic .iConnector 7
20 p!blic9
22 int (ops&int i) int j'7
21 ret!rn min5(ops?i
N
n!m5nodes 4 j@;
23 8;
2= int nodes&' 7 ret!rn n!m5nodes; 8
2> private9
2A static -od
N
instance5;
2B int n!m5nodes;
2/ int
N
min5(ops; MM"or i
N
n!m5nodes4j
2G 8;
?!ine 12@ stores t&e number o/ %obile Nodes in a simulation) T&e number o/ &os
between nodes FiG and FjG is stored in t&e )i n!m5nodes$Cj
t &
element o/ t&e
array Fmin5(opG ?!ine 12@)
Class -od contains two imortant ublic /unctions) One is /unction nodes&'
w&ic& returns t&e number o/ %obile Nodes in t&e simulation ?!ine 1:@) 4not&er
is /unction (op&i)j' w&ic& returns t&e distance ?in &os@ between node FiG
and node FjG ?!ines 11H13@) 4t run9time* NS2 may in1oke t&ese two /unctions
as needed)
It is imortant to know* t&at desite not in use* LO. is a mandatory obBect
/or simulation o/ a mobile network) .urin' t&e Network Con/i'uration P&ase* an
%4C obBect reads t&e number o/ nodes /rom t&e LO. obBect ?see !ine 33 in
Pro'ram 12)8@) I/ t&e LO. obBect is not initialiJed* a run9time error messa'e will
aear on t&e screen)
12./." Rando Mo-ility
NS2 suorts deterministic and random mobility) Section 12)8)1 s&ows &ow deter9
ministic mobility can be set u usin' an OTcl command setdest/III' o/ class
%obileNode) T&is section /ocuses on t&e ot&er aroac&< (andom mobility)
12)8 4n Introduction to Node %obility 3:1
Program %2=26 Enablin' random motion< Cunction start&' o/ class
%obileNode and /unction (andle&e' o/ class PositionHandler
MMUnsMcommonMmobileJnodeIcc
2 void %obileNode99start&'
1 7
3 Sc(ed!lerF s : Sc(ed!ler99instance&';
= random5position&';
> random5destination&';
A sIsc(ed!le&Fpos5(andle5)Fpos5intr5)
position5!pdate5interval5';
B 8
/ void PositionHandler99(andle&Event
N
'
G 7
20 Sc(ed!lerF s : Sc(ed!ler99instance&';
22 nodeJK!pdate5position&';
21 nodeJKrandom5destination&';
23 sIsc(ed!le&FnodeJKpos5(andle5) FnodeJKpos5intr5)
nodeJKposition5!pdate5interval5';
2= 8
(andom mobility can be deacti1ated$acti1ated usin' t&e /ollowin' two OTcl
commands o/ class %obileNode<
Pnode randomJmotion <"la$K
Pnode start
T&e uer OTcl command stores <"la$K in t&e 1ariable Frandom5motion5G
o/ class %obileNode) T&e lower in1okes t&e /unction start&' o/
t&e %obileNode obBect* w&ose details are s&own in Pro'ram 12)28)
Crom wit&in t&e /unction start&'* !ines : and 3 in1oke /unctions
random5position&' and random5destination&'* resecti1ely) T&ese
two /unctions randomiJe t&e current location and t&e destination* resecti1ely* o/
t&e %obile Node) !ine 8 sets t&e osition &andler Fpos5(andle5G ?see also
!ine 11 in Pro'ram 12)1@ to eAire a/ter a eriod o/
Fposition5!pdate5interval5)G 4t t&e eAiration* t&e rocess reeats by
udatin' node osition* comutin' a randomiJed destination* and settin' t&e
osition &andler to eAire a/ter t&e same inter1al ?!ines "H1:@)
12./.$ Mo-ility and Traffic ,enerators9 Standalone 7elper
0tility
T&e bene/its o/ deterministic mobility is t&at ro'rammers &a1e /ull control o1er
w&ere and &ow t&e %obile Nodes mo1e durin' simulation) +ut as t&e number o/
%obile Nodes increases* it becomes increasin'ly tedious to seci/y destinations
/or all t&e nodes) 4lt&ou'& random mobility could sol1e t&is roblem* it does not
allow ro'rammers to re1iew or control &ow t&e %obile Nodes mo1e)
2
O
s
.
3:, 12 6ireless %obile 4d Hoc Networks
%2=6=/=% Mobi#ity ;eneration 9ti#ity GsetdestH
NS2 ro1ides a FsetdestG s&ell utility
13
w&ic& creates deterministic mobility
statements* w&ic& can be inserted into a Tcl simulation scrit)
6ritten in CCC* t&e eAecutable FsetdestG is located in t&e directory
Tns$inde9 utils$cmu9sen9'en$setdest) NS2 ro1ides two 1ersions o/ t&e utility<
7ersion 1 ?de1eloed by Carne'ie %ellon 0ni1ersity@<
KKIMsetdest Jv <versionK Jn <n!m5nodesK Jt <sim5timeK
J% <ma*5speedK Jp <pa!se5timeK
J* <ma*5*K Jy <ma*5yK
7ersion 2 ?de1eloed by 0ni1ersity o/ %ic&i'an@
KKIMsetdest Jv <versionK Jn <n!m5nodesK Jt <sim5timeK
Js <speed5typeK Jm <min5speedK J% <ma*5speedK
JP <pa!se5typeK Jp <pa!se5timeK
J* <ma*5*K Jy <ma*5yK
H Seed< Here <speed5typeK can be eit&er F!ni"ormG or Fnormal*G
/or uni/orm or normal distributions* resecti1ely) In case o/ Fnormal*G t&e
randomiJed seed 1alues are taken /rom a truncated normal distribution wit&
mean s and standard de1iation
s
* w&ere
s .
ma* spee dC ma* speed
ma* speed ma* speed
:
H Pause time< Here <pa!se5typeK can be FconstantG or F!ni"orm)G
T&ese two cases set t&e ause time to be a constant 1alue o/ pa!se5time
and t&e 1alue uni/ormly distributed wit&in Q,Opa!se5time * resecti1ely)
E%ample 2*2* Consider t&e /ollowin' s&ell statement<
KKIMsetdest Jn 1 Jp 20 J% 20 Jt 2000 J* >00 Jy >00
O nodes9 1) pa!se9 20I00) ma* speed9 20I00)
ma* *9 >00I00) ma* y9 >00I00
O
Pnode5&0' set L5 1B/IA21G=2/=2=BB
Pnode5&0' set [5 13AIB233G3=23>>1
Pnode5&0' set \5 0I000000000000
Pnode5&2' set L5 1BGI0>001G00G10G
Pnode5&2' set [5 =>/IG31/1A=0123/
Pnode5&2' set \5 0I000000000000
P$od5 setJdist 0 2 2
Pns5 at 20I00 HPnode5&0' setdest 2B3I=>0 13=IBA >I03H
Pns5 at 20I00 HPnode5&2' setdest 23I/> GGI31 GI//H
13
T&is utility &as t&e same name as t&e OTcl command setdest/III' o/ class
NodeM%obileNode)
3:2 12 6ireless %obile 4d Hoc Networks
Pns5 at 30I/B HPnode5&0' setdest 2B3I=> 13=IBA 0I00H
III
Pns5 at GG1I=G HPnode5&0' setdest 2A0IGA 2A2I/2 0I00H
w&ere t&e /irst line is ro1ided by t&e user* and t&e subseDuent lines are t&e
mobility9 related NS2 statements created by t&e utility Fsetdest)G
T&is statement creates mobility statements /or two %obile Nodes wit& ause
time
o/ 1, s ?constant@) T&e maAimum seed is 1, m er second* and t&e simulation
time is 1*,,, s) T&e toolo'y ran'es /rom , to 3,, ?in meter@ on bot& t&e E 9aAis
and t&e ; 9aAis)
%2=6=/=2 Traffic ;eneration 9ti#ity
Gcbrgen4tclH
NS2 also ro1ides anot&er indeendent utility Fcbr$enItcl*G written in Tcl* to
create tra//ic9related OTcl statements<
KKns cbr$enItcl Jtype <cbrXtcpK Jnn <n!m5nodesK
Jseed <seedK Jmc <ma*5connK Jr <rateK
0nlike t&e mobility 'eneration utility* t&is utility Fcbr$enItclG is an NS
scrit and needs to be in1oked t&rou'& t&e interreter* w&ic&* in t&is case* is t&e
eAecutable Fns)G .esite its name* t&is utility can create bot& TCP and C+(
tra//ic by seci/yin' eit&er FcbrG or FtcpG a/ter t&e otion Jtype) Ot&er otions
include t&e number o/ %obile Nodes in t&e simulation ?<n!m5nodesK@* seed
?<seedK@* t&e maAimum o/ connections t&at will be 'enerated ?<ma*5connK@*
and t&e data rate in bs /or C+( tra//ic ?<rateK@) 4n eAamle use o/ t&is utility is
s&own below)
E%ample 2*$* Consider t&e /ollowin' s&ell statement<
KKns cbr$enItcl Jtype cbr Jnn 20 Jseed 2I0 Jmc =>
Jrate =I0
O nodes9 20) ma* conn9 =>) send rate9 0I1>) seed9 2I0
O 2 connectin$ to 1 at time 1I>>A/3//B/A/GB1=>
set !dp5&0' ?ne, A$entMDDP@
Pns5 attac(Ja$ent Pnode5&2' P!dp5&0'
set n!ll5&0' ?ne, A$entMN!ll@
Pns5 attac(Ja$ent Pnode5&1' Pn!ll5&0'
set cbr5&0' ?ne, ApplicationMTra""icMC.#@
Pcbr5&0' set packetSi6e5 >21
Pcbr5&0' set interval5 0I1>
Pcbr5&0' set random5 2
Pcbr5&0' set ma*pkts5 20000
Pcbr5&0' attac(Ja$ent P!dp5&0'
Pns5 connect P!dp5&0' Pn!ll5&0'
Pns5 at 1I>>A/3//B/A/GB1=> HPcbr5&0' startH
O
O = connectin$ to > at time >AI33322/G2B>B>A31
12)2 C&ater Summary 3:3
set !dp5&2' ?ne, A$entMDDP@
III
Pns5 connect P!dp5&/' Pn!ll5&/'
Pns5 at 32I=A=G=>A//>G=>B> HPcbr5&/' startH
O
OTotal so!rcesMconnections9 AMG
w&ere* a'ain* t&e /irst and t&e subseDuent lines are sulied by t&e users and t&e
resultin' tra//ic9related NS2 statements are created by t&e utility Fcbr$enItcl)G
T&e /irst statement seci/ies C+( tra//ic /or ten %obile Nodes) T&e seed is set to
2I0) T&e maAimum number o/ connections is =>) T&e C+( rate is =I0 bs)
%2=6=/=* Working with Scenario 4i#es
6&ile t&e abo1e two standalone utilities are use/ul* it is Duite &ard to use t&em
because t&e results are dislayed on t&e screen) It is more con1enient to redirect
t&e outut to a scenario /ile usin' FKG or FKKG instructions ?see Sect) 4)3)3@) Cor
eAamle* t&e /ollowin' two s&ell statements can be eAecuted /rom t&e directory
Tns$inde9utils$cmu9sen9'en$setdest)
KKIMsetdest Jn 1 Jp 20 J% 20 Jt 2000 J* >00 Jy >00 K
my"ile
KKns cbr$enItcl Jtype cbr Jnn 1 Jseed 2I0 Jmc =
Jrate =I0 K my"ile
T&ese two statements create and store NS2 mobility and tra//ic statements in
scenario /iles w&ose name is Fmy"ile)G EAamles o/ built9in scenario /iles can
be /ound in t&e directory Tns$tcl$mobility$scene)
6e conclude t&is section wit& t&e summary o/ &ow to con/i'ure
mobility$tra//ic usin' scenario /iles)
Ste& %2 (un t&e stand9alone utilities to creates scenario /iles ?e)')*
my"ile@)
Ste& 22 Con/i'ure a Tcl Simulation Scrit as usual)
Ste& *2 Source t&e created scenario /iles into t&e Tcl Simulation Scrit usin' t&e
rocedure Fso!rceG ?e)')* Fso!rce my"ile*G see also Sect) 3)2@)
1:
%2=5 $ha&ter Summary
T&is c&ater co1ers anot&er network simulation domain< wireless networkin')
Central to t&is domain are %obile Nodes c&aracteriJed by acket /orwardin'
mec&anism usin' wireless c&annels and node mobility) In t&e OTcl domain*
1:
Caution< It is imortant to 1alidate t&e at& to t&e scenario /iles) Cailin' to do will result in a
F/ile not /oundG error)
3:: 12 6ireless %obile 4d Hoc Networks
a %obile Node ?class NodeM%obileNode@ is a comosite obBect H consistin'
o/ t&e /ollowin' key obBects< routin' ?e)')* 4O.7@* link layer* inter/ace Dueue
?e)')* rioritiJe Dueues@* %edium 4ccess Control ?%4C@ rotocol ?e)')* IEEE
",2)11@* &ysical network inter/ace* and s&ared c&annel obBects) NS2 suorts
bot& deterministic and random mobility) NS2 also ro1ides two standalone utility
H namely setdest and cbr$enItcl H to /acilitate t&e network
con/i'uration rocess)
%2=7 "<ercises
1) Consider (e'ular Nodes and %obile Nodes) 6&at are t&eir di//erencesR
6&ere do %obile Nodes imlement wireless links and mobilityR .raw
network dia'rams to suort your answer)
2) EAlain t&e acket /low in a wireless
network)
a) 6&en and w&o is resonsible /or acket creation$destructionR
b) EAlain t&e seDuence o/ obBects w&ic& recei1e and /orward t&e
ackets) c) 6&at &aens w&en t&e acket reac&es a wireless c&annelR
d) 6&at do t&e source node* t&e destination node* and t&e intermediate nodes
doR
3) 6&at are t&e two key stes to create a %obile NodeR 6&at are t&e uroses o/
t&ese two key stesR
:) 6&at is a routin' loo roblemR 6&y is it a roblemR Su''est a way to sol1e
t&is roblem)
3) EAlain /orward at& setu and backward at& setu in
4O.7)
8) How does NS2 determine transmission ower* recei1ed ower* and w&et&er
t&e recei1ed ackets are in errorR S&ow t&e related OTcl$CCC statements)
2) 6&at are t&e roles o/ timers in t&e NS2 IEEE ",2)11 moduleR
") 6&at are t&e uroses o/ t&e 1ariables Fpkt#*5G and FpktT*5G o/ class
%ac
and t&e 1ariables Fpkt#TS5G and FpktCT#L5G o/ class %ac/01522)
#) How does NS2 imlement sel/9inter/erence in t&e IEEE ",2)11 %4C
rotocolR
1,) S&ow /ew eAamles o/ OTcl statements w&ic& set u deterministic$random
mobility /or a 'i1en %obile Node Pn2) EAlain t&e OTcl statements you
ro1ide)
11) 0se t&e NS2 indeendent utilities to create t&e /ollowin' OTcl statements<
a) Ci1e %obile Nodes* eac& wit& seed uni/ormly distributed between 1, and
2, m s
1
* and constant ause time o/ 2, s) T&e 'eo'ra&ical area is set to be
2,, on bot& E 9aAis and ; 9aAis)
b) Cor t&e abo1e settin's* create at most /our TCP
connections) Test your OTcl statements by runnin' simulation)
$ha&ter %*
-eve#o&ing New Mou#es for NS2
So /ar* we &a1e eAlained t&e details o/ t&e basic comonents o/ NS2 includin'
t&eir /unctionalities* internal mec&anisms* and con/i'uration met&ods) In t&is
c&ater* we demonstrate &ow new NS2 modules are created* con/i'ured* and
incororated t&rou'& two /ollowin' eAamles) One is an 4utomatic (eeat
reIuest ?4(I@ rotocol* w&ic& is a mec&anism to imro1e transmission reliability
o/ a communi9 cation link by means o/ acket retransmission) 4not&er is a acket
sc&eduler w&ic& arran'es t&e transmission seDuence o/ ackets /rom multile
incomin' data /lows)
%*=% Automatic Re&eat re?uest
4(I is a met&od o/ &andlin' communication errors by acket retransmission) 4n
4(I transmitter ?i)e)* a transmittin' node w&ic& imlements an 4(I rotocol@ is
resonsible /or transmittin' data ackets and retransmittin' t&e lost ackets) 4n
4(I recei1er ?i)e)* a recei1in' node w&ic& imlements an 4(I rotocol@* on t&e
ot&er &and* is resonsible /or recei1in' ackets and ?imlicitly or eAlicitly@
in/orm9 in' t&e transmitter o/ t&e transmission result) It returns an 4CK
?acknowled'ment@ messa'e and$or a N4CK ?ne'ati1e acknowled'ment@
messa'e to t&e transmitter i/ a acket is success/ully or unsuccess/ully
?resecti1ely@ recei1ed) +ased on t&e recei1ed 4CK$N4CK attern* t&e 4(I
transmitter decides w&et&er to retransmit t&e lost acket or to transmit a new
acket)
T&is section /ocuses on a limited9ersistence sto9and9wait 4(I rotocol)
T&is tye o/ 4(I rotocols is c&aracteriJed by t&e two /ollowin' roerties)
6it& limited9ersistence* an 4(I transmitter 'i1es u t&e retransmission i/ t&e
transmission /ails consecuti1ely /or a certain number o/ times) 4not&er roerty
is Fsto9and9wait)G Here* an 4(I transmitter transmits a acket and waits /or an
acknowled'ment /rom t&e corresondin' 4(I recei1er be/ore commencin'
anot&er ?lost or new@ acket transmission)
In t&e /ollowin'* we /irst desi'n t&e NS2 modules /or a limited9ersistence
sto9 and9wait 4(I rotocol wit& an error9/ree and delay9/ree ?i)e)* immediate@
/eedback
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 13* = Srin'er Science>+usiness %edia* !!C 2,12
3:3
3:8 13 .e1eloin' New %odules /or NS2
Program %*=% +indin' codes /or 4(I transmitters* 4(I 4CK transmitter* and
4(I N4CK transmitter
MM ar+Icc
2 Oincl!de Har+I(H
1 static class A#T*Class9 p!blic TclClass 7
3 p!blic9
= A#T*Class&' 9 TclClass&HA#T*H' 78
> TclObject
N
create&int) const c(ar
N
const
N
' 7
A ret!rn &ne, A#T*';
B 8
/ 8 class5ar+5t*;
G static class A#AckerClass9 p!blic TclClass 7
20 p!blic9
22 A#AckerClass&' 9 TclClass&HA#AckerH' 78
21 TclObject
N
create&int) const c(ar
N
const
N
' 7
23 ret!rn &ne, A#Acker';
2= 8
2> 8 class5ar+5acker;
2A static class A#NackerClass9 p!blic TclClass 7
2B p!blic9
2/ A#NackerClass&' 9 TclClass&HA#NackerH' 78
2G TclObject
N
create&int) const c(ar
N
const
N
' 7
10 ret!rn &ne, A#Nacker';
12 8
11 8 class5ar+5nacker;
c&annel in Sect) 13)1)1) Sections 13)1)2 and 13)1)3 demonstrate t&e CCC and
OTcl imlementations* resecti1ely) Cinally* in Sect) 13)1):* we eAtend t&e 4(I
modules /or an error9/ree /eedback c&annel wit& nonJero rocessin' and
roa'ation delay) Imlementation o/ an 4(I rotocol wit& an error rone
/eedback c&annel is le/t as an eAercise /or t&e readers)
1".1.1 The )esign
%*=%=%=% Architecture
4(I aims at imro1in' transmission reliability on a lossy link) In t&is section*
we s&all build 4(I modules on to o/ a lossy link de/ined in Sect) 13)3 ?see also
Ci') 13)2@) In articular* we s&all incororate t&ree /ollowin' 4(I modules ?see
class bindin' codes in Pro'ram 13)1@ into a SimpleLink obBect as s&own in
Ci') 13)1)
AR? Transmitter (tAR(5)< Kees track o/ transmission result ?by waitin' /or
messa'es /rom 4(I 4CK$N4CK transmitter@ and retransmit t&e lost acket i/
necessary) 4(I transmitters are de/ined in CCC class A#T* bound to t&e
OTcl class wit& t&e same name)
13)1 4utomatic (eeat reIuest 3:2
4ig= %*=% 4rc&itecture o/ a SimpleLink obBect wit& 4(I9related
modules
AR? A$D transmitter (acker5)< Sends an 4CK messa'e to t&e 4(I
transmitter i/ t&e acket is success/ully transmitted) 4(I 4CK transmitters are
de/ined in CCC class A#Acker bound to t&e OTcl class wit& t&e same
name)
AR? NA$D transmitter (nacker5)< Sends a N4CK messa'e to t&e 4(I
transmitter i/ t&e acket is not success/ully transmitted) 4(I N4CK transmitters
are de/ined in CCC class A#Nacker bound to t&e OTcl class wit& t&e same
name)
%*=%=%=2 Packet 4orwaring Mechanism
Consider Ci') 13)1) 6&en FtA#5G recei1es a acket /rom F+!e!e5*G it asses
t&e acket to its downstream obBects) 6&en Flink5errmod!le5G recei1es t&e
acket* it simulates acket error) I/ t&e acket is in error* it will be /orwarded to
Fnacker5)G Ot&erwise* it will be /orwarded to Facker5)G
0on recei1in' a acket* Facker5G sends an 4CK messa'e to t&e 4(I
transmitter* and /orwards t&e acket to its downstream obBect* Fttl5)G On t&e
ot&er &and* Fnacker5*G uon recei1in' a acket* sends an N4CK messa'e to t&e
4(I transmitter) To simli/y imlementation* we let t&e Fnacker5G send t&e
acket ?w&ic& was simulated to be in error@ back to t&e 4(I transmitter)
6&en t&e 4(I transmitter recei1es an 4CK messa'e or an N4CK messa'e* it
reares a new acket /or ?re@transmission) I/ an 4CK messa'e is recei1ed* it will
/etc& anot&er acket /rom F+!e!e5)G On t&e ot&er &and* i/ an N4CK messa'e is
recei1ed* it will decide w&et&er to retransmit or dro t&e acket) In t&e latter case*
a new acket will be /etc&ed /rom t&e F+!e!e5)G 4/ter t&e rearation is
comlete* t&e acket /orwardin' mec&anism roceeds as discussed abo1e)
%*=%=%=* $a##back Mechanism
In Sect) 2)3)3* we discuss t&e callback mec&anism o/ a SimpleLink obBect) T&e
LinkDelay obBect Flink5G asks t&e Sc&eduler to transmit a callback messa'e
to F+!e!e5G w&en t&e acket dearture rocess is comlete)
3:" 13 .e1eloin' New %odules /or NS2
Program %*=2 .eclaration o/ classes A#T* and A#Handler
MM ar+I(
13 Oincl!de HconnectorI(H
1= Class A#T*;
1> en!m A#Stat!s 7IDLE)SENT)ACVED)#TL)D#OP8;
1A class A#Handler 9 p!blic Handler 7
1B p!blic9
1/ A#Handler&A#T*F ar+' 9 ar+5t*5&ar+' 78;
1G void (andle&Event
N
';
30 private9
32 A#T*F ar+5t*5;
31 8;
33 class A#T* 9 p!blic Connector 7
3= p!blic9
3> A#T*&';
3A void recv&Packet
N
) Handler
N
';
3B void nack&Packet
N
';
3/ void ack&';
3G void res!me&';
=0 protected9
=2 A#Handler ar+(5;
=1 Handler
N
(andler5;
=3 Packet
N
pkt5;
== A#Stat!s stat!s5;
=> int blocked5;
=A int retry5limit5;
=B int n!m5rt*s5;
=/ 8;
6it& t&e introduction o/ 4(I modules* we will &a1e Flink5G call back
to FtA#5G rat&er t&an F+!e!e5)G In t&is case* a callback si'nal resumes t&e
endin' retransmission rocess* rat&er t&an t&e acket dearture rocess) 6&en
t&e retransmission comletes* FtA#5G /etc&es anot&er acket /rom F+!e!e5*G
and continues t&e re'ular acket transmission rocess)
1".1.2 CCC Ipleentation
6e imlement t&e 4(I mec&anism usin' /i1e CCC classes) 4art /rom t&ree
main classes H A#T** A#Acker* and A#Nacker H introduced in t&e
re1ious section* two &eler classes include
Class A#Handler< 4 &andle /or callback mec&anism)
Class A##*< T&e base class /or classes A#Acker and
A#Nacker)
T&e declaration o/ all /i1e classes are s&own in Pro'rams 13)2 and 13)3)
13)1 4utomatic (eeat reIuest 3:#
Program %*=* .eclaration o/ classes A##** A#Acker* and A#Nacker
MM ar+I(
=G class A##* 9 p!blic Connector 7
>0 p!blic9
>2 A##*&' 7ar+5t*5:0; 8;
>1 int command&int ar$c) const c(ar
N
const
N
ar$v';
>3 protected9
>= A#T*
N
ar+5t*5;
>> 8;
>A class A#Acker 9 p!blic A##* 7
>B p!blic9
>/ A#Acker&' 78;
>G virt!al void recv&Packet
N
) Handler
N
';
A0 8;
A2 class A#Nacker 9 p!blic A##* 7
A1 p!blic9
A3 A#Nacker&' 78;
A= virt!al void recv&Packet
N
) Handler
N
';
A> 8;
%*=%=2=% $#ass AR(T,s
Class A#T* reresents 4(I transmitters) .eri1ed /rom class Connector* it
can be used to connect two NsObBects)
1
T&e main CCC 1ariables o/ class A#T*
are s&own below<
n!m5rt*s5 Current number o/ acket retransmissionsO It is
increased by one /or e1ery transmission /ailure* and is
reset to Jero w&en a new acket arri1es ?e)')* due to a
acket dro or a transmission success@)
retry5limit5 T&e retry limitO T&e 4(I rotocol will retransmit t&e
lost acket as lon' as n!m5rt*s5<:retry5limit5)
blocked5 Indicates w&et&er t&e A#T* obBect is blocked) I/
blocked* t&e A#T* obBect will not transmit any acket)
ar+(5 4 &andler w&ic& is assed to t&e downstream obBect
(andler5 4 &andler o/ an ustream obBect ?w&ic& is a
!e!eHandler obBect in our case@
stat!s5 Current status o/ t&e A#T* obBect de/ined in !ine 23
o/
Pro'ram 13)2
pkt5 4 ointer to t&e acket w&ic& is bein' transmitted)
Class A#T* de/ines t&e /our /ollowin'
/unctions<
1
In Ci') 13)1* we use an A#T* obBect FtA# G to connect a !e!e obBect F+!e!e G wit&
a
LinkDelay obBect Flink )G
33, 13 .e1eloin' New %odules /or NS2
recv&p)(' (ecei1e acket
N
p /rom an ustream obBect)
ack&' Process an 4CK messa'eO T&is /unction in1oked by an
A#Acker obBect)
nack&p' Process a N4CK messa'eO T&is /unction in1oked by an
A#Nacker obBect)
res!me&' (esume t&e oeration /rom t&e FblockedG stateO T&is
/unction is called by t&e downstream LinkDelay
obBect w&en t&e endin' acket transmission is
comlete)
%*=%=2=2 $#ass AR(Handler
T&is &eler class /acilitates t&e callback mec&anism) Crom !ine 31 in Pro'ram
13)2* it &as only one 1ariable Far+5t*5G w&ic& is t&e re/erence to t&e A#T*
obBect) .urin' t&e callback rocess* an A#Handler obBect uses t&is re/erence
to tell t&e A#T* obBect to resume t&e endin' retransmission rocess)
%*=%=2=* $#asses AR(R,3 AR(Acker3 an AR(Nacker
4not&er art o/ 4(I imlementation is an 4(I recei1er* w&ic& is resonsible /or
reactin' to t&e 4(I transmitter) (eresented by a CCC class A##** an 4(I
recei1er contains a ointer Far+5t*5G ?see !ine 3: in Pro'ram 13)3@ to an 4(I
transmitter ?i)e)* an A#T* obBect@) T&is ointer is initialiJed to Jero at t&e obBect
construction ?!ine 31@* and is associated wit& an 4(I transmitter by t&e OTcl
command attac(JA#T* ?Pro'ram 13)8@)
T&ere are two classes deri1ed /rom class A##*< classes A#Acker and
A#Nacker) T&ese two classes are resonsible /or sendin' 4CK and N4CK
messa'es* resecti1ely* to t&e associated 4(I
transmitter)
%*=%=2=/ $a##back Mechanism
Consider t&e ro'ram related to a callback rocess in Pro'ram 13):) T&e rocess
be'ins w&en a !e!e obBect sends a acket to an A#T* obBect 1ia
/unction recv&p)(' ?!ines 22H28@) T&e A#T* obBect stores t&e &andler F(G
in t&e class 1ariable F(andler5)G T&is &andler will be used to /etc& anot&er
acket /rom t&e !e!e obBect w&en t&e retransmission rocess comletes)
NeAt* t&e A#T* obBect sends t&e acket as well as its own &andler Far+(5G
to its downstream LinkDelay obBect) 4'ain* t&e LinkDelay obBect will
ut t&is &andler Far+(5G on t&e simulation timeline at t&e time w&en t&e acket
transmission comletes) 4t t&e /irin' time* t&e Sc&eduler calls t&e de/ault action
?i)e)* t&e /unction (andle&e'@ o/ t&e &andler Far+(5)G Crom !ines 1,2H1,3*
t&e A#Handler obBect in1okes /unction res!me&' o/ t&e associated A#T*
obBect
13)1 4utomatic (eeat reIuest 331
Program %*=/ Cunctions o/ classes A#T* and
A#Handler
MM ar+Icc
AA A#T*99A#T*&' 9 ar+(5&
N
t(is'
AB 7
A/ n!m5rt*s5 : 0; retry5limit5 : 0; (andler5 : 0;
AG pkt5 : 0; stat!s5 : IDLE; blocked5 : 0;
B0 bind&Hretry5limit5H) Fretry5limit5';
B2 8
B1 void A#T*99recv&Packet
N
p) Handler
N
('
B3 7
B= (andler5 : (; stat!s5 : SENT; blocked5 : 2;
B> send&p)Far+(5';
BA 8
BB void A#T*99ack&'
B/ 7
BG n!m5rt*s5 : 0; stat!s5 : ACVED;
/0 8
/2 void A#T*99nack&Packet
N
p'
/1 7
/3 n!m5rt*s544; pkt5:p;
/= i"& n!m5rt*s5 <: retry5limit5'
/> stat!s5 : #TL;
/A else
/B stat!s5 : D#OP;
// 8
/G void A#T*99res!me&'
G0 7
G2 blocked5 : 0;
G1 i" & stat!s5 :: ACVED ' 7
G3 stat!s5 : IDLE; (andler5JK(andle&0';
G= 8 else i" & stat!s5 :: #TL ' 7
G> stat!s5 : SENT; blocked5 : 2;
GA send&pkt5)Far+(5';
GB 8 else i" & stat!s5 :: D#OP ' 7
G/ stat!s5 : IDLE; drop&pkt5';
GG (andler5JK(andle&0';
200 8
202 8
201 void A#Handler99(andle&Event
N
e'
203 7
20= ar+5t*5Ires!me&';
20> 8
?i)e)* 4(I transmitter@ Far+5t*5)G 6&en t&e /unction res!me&' is in1oked*
t&e A#T* obBect c&ecks t&e retransmission status) I/ t&e 4CK messa'e is
recei1ed ?i)e)* ACVED in !ine #2@ or t&e limit on t&e number o/ allowable
retransmissions is eAceeded ?i)e)* D#OP in !ine #2@* t&e A#T* obBect will
/etc& anot&er acket
332 13 .e1eloin' New %odules /or NS2
Program %*=0 Cunctions o/ classes A##** A#Acker* and A#Nacker
MM ar+Icc
20A void A#Acker99recv&Packet
N
p) Handler
N
('
20B 7
20/ ar+5t*5JKack&';
20G send&p)(';
220 8
222 void A#Nacker99recv&Packet
N
p) Handler
N
('
221 7
223 ar+5t*5JKnack&p';
22= 8
by eAecutin' (andler5JK(andle&0' ?!ines #3 and ##@)
2
Ot&erwise* it will
retransmit t&e acket by eAecutin' send&pkt5)Far+(5' ?!ine #8@)
%*=%=2=0 Packet 4orwaring Mechanism
Consider Ci') 13)1) T&e main acket /orwardin' mec&anism is to ass t&e acket
/rom F+!e!e5*G to FtA#5*G to Flink5*G and to Flink5errmod!le5*G re9
secti1ely) T&en* i/ t&e acket is simulated to be and not to be in error* it will
be /orwarded to nacker5 and acker5 w&ose classes are A#Nacker
and A#Acker* resecti1ely)
Consider Pro'ram 13)3) T&at an A#Acker obBect recei1es a acket im9
lies success/ul acket transmission) In t&is case* t&e A#Acker obBect sends
an 4CK messa'e to t&e associated A#T* obBect Far+5t*5G ?by eAecutin'
ar+5t*5JKack&' in !ine 1,"@) T&en* it /orwards t&e acket to its
downstream
obBect ?by eAecutin' send&p)(' in !ine
1,#@)
On t&e ot&er &and* t&at an A#Nacker obBect recei1es a acket imlies a
acket
loss) In t&is case* t&e Nacker obBect sends a N4CK messa'e to t&e associated
A#T* obBect Far+5t*5G ?by eAecutin' ar+5t*5JKnack&p' in !ine
113@*
assin' t&e acket in error FpG as an inut ar'ument) In t&e neAt section* we s&all
see
w&at an A#T* would do w&en recei1in' an 4CK messa'e or a N4CK
messa'e)
%*=%=2=6 Processing A$D an NA$D Messages
Ci'ure 13)2 and Pro'ram 13): s&ow details o/ &ow an 4(I transmitter rocesses
4CK$N4CK messa'es) 0on recei1in' an 4CK messa'e ?1ia /unction ack&'
in !ines 22H",@* t&e A#T* obBect resets t&e retransmission limit Fn!m5rt*s5G
to Jero and sets t&e status to ACV) I/ an N4CK messa'e is recei1ed ?1ia
/unction
13)1 4utomatic (eeat reIuest 333
2
T&e 1ariable F(andle G stores t&e !e!eHandler obBect associated wit& t&e ustream
!e!e
obBect)
332 13 .e1eloin' New %odules /or NS2
Program %*=6 .e/intion o/ t&e OTcl command attac(JA#T*
22> int A##*99command&int ar$c) const c(ar
N
const
N
ar$v'
22A 7
22B TclF tcl : Tcl99instance&';
22/ i" &ar$c :: 3' 7
22/ i" &strcmp&ar$v?2@) Hattac(JA#T*H' :: 0' 7
22G i" &
N
ar$v?1@ :: Z0Z' 7
210 tclIres!lt"&HCannot attac( NDLL A#T*TnH';
212 ret!rn&TCL5E##O#';
211 8
213 ar+5t*5 : &A#T*
N
'TclObject99look!p&ar$v?1@';
21= ret!rn&TCL5OV';
21> 8
21A
21B 8 ret!rn Connector99command&ar$c) ar$v';
21/ 8
4ig= %*=2 Clowc&arts o/ /unctions ?a@ ack&' and ?b@ nack&p' o/ class
A#T*
nack&p' in !ines "1H""@* t&e A#T* obBect increments t&e number o/
retrans9 missions ?i)e)* Fn!m5rt*s5G@ attemted so /ar) I/ t&e number o/
retransmissions is wit&in t&e limit* it will set its status to #TL) Ot&erwise* t&e
status will be set to D#OP) In bot& t&e cases* a ointer to t&e acket FpG simulated
to be in error is stored in t&e class 1ariable Fpkt5G /or /uture use)
13)1 4utomatic (eeat reIuest 333
4ig= %*=* Clowc&art o/ t&e
/unction res!me&' o/
class A#T*
resume()
bloc1edC@!E
statusC
D=*P
,0P+D ='#
dro6(61tC)E
statusC @ /DL+E
handlerC$Qhandle(!)E
statusC @ S+)'E
bloc1edC @ 1E
send(61tCDJar3hC)E
return
%*=%=2=5 Actions an Status of AR? Transmitters
0on recei1in' 4CK$N4CK messa'es* t&e A#T* obBect does not
immediately transmit* retransmit* or dro t&e acket* since t&ere mi'&t be ackets
in transit) 4t t&e moment* it records t&e transmission result in t&e class 1ariable
Fstat!s5*G and waits /or a callback si'nal /rom t&e LinkDelay obBect be/ore
takin' /urt&er actions)
Ci'ure 13)3 s&ows t&ree ossibilities taken /rom wit&in t&e /unction
res!me&'* w&en a callback si'nal is recei1ed ?see !ines "#H1,1 in Pro'ram
13):@)
I/ t&e Fstat!s5G was set to #TL* t&e lost acket is retransmitted &ere)
3
I/
t&e Fstat!s5G was set to D#OP* t&e acket Fpkt5G is destroyed &ere) I/ t&e
Fstat!s5G was set to eit&er ACV or D#OP* t&e A#T* will /etc& anot&er
acket /rom t&e !e!e obBect by eAecutin' (andler5JK(andle&0')
:
1".1." OTcl Ipleentation
In t&e OTcl domain* we need to create A#T** A#Acker* and A#Nack
obBectsHFtA#5G* Facker5*G and Fnacker5*G resecti1ely* and insert t&em into
a SimpleLink obBect as s&own in Ci') 13)1) Pro'ram 13)2 s&ows two OTcl
instrocs de1eloed /or t&is urose)
3
T&e acket in error was earlier stored in t&e class 1ariable Fpkt G ?see !ine "3 in Pro'ram 13):@)
:
4'ain* t&e 1ariable F(andle G stores a ointer to t&e !e!eHandler obBect associated
wit& t&e ustream !e!e obBect)
Program %*=5 OTcl Instrocs /or an 4(I %odule
MMUnsMtclMlibMnsJlinkItcl
2 SimpleLink instproc linkJar+ 7 limit 8 7
1 Psel" instvar link5 link5errmod!le5 +!e!e5 drop(ead5
3 Psel" instvar tA#5 acker5 nacker5
= set tA#5 ?ne, A#T*@
> set acker5 ?ne, A#Acker@
A set nacker5 ?ne, A#Nacker@
B PtA#5 set retry5limit5 Plimit
/ Packer5 attac(JA#T* PtA#5
G Pnacker5 attac(JA#T* PtA#5
20 P+!e!e5 tar$et PtA#5
22 PtA#5 tar$et Plink5errmod!le5
21 Plink5errmod!le5 tar$et Packer5
23 Packer5 tar$et Plink5
2= PtA#5 dropJtar$et Pdrop(ead5
2> Plink5errmod!le5 dropJtar$et Pnacker5
2A 8
MMUnsMtclMlibMnsJlibItcl
2B Sim!lator instproc linkJar+ 7limit "rom to8 7
2/ set link ?Psel" link P"rom Pto@
2G Plink linkJar+ Plimit
10 8
%*=%=*=% 'nst&roc &im%le'ink66link#ar-/limit'
T&is instroc creates t&e 4(I9related obBects and con/i'ures t&e SimpleLink
obBect as s&own in Ci') 13)1) !ines :H8 create inst1ars FtA#5*G Facker5*G
and Fnacker5)G !ine 2 stores t&e inut ar'ument FlimitG in t&e inst1ar
Fretry5limit5G o/ FtA#5)G Crom !ine 2, in Pro'ram 13):* t&e inst1ar
Fretry5limit5G is bound to t&e CCC class 1ariable wit& t&e same name) T&is
1ariable indicates t&e maAimum number o/ retransmissions /or an erroneous
acket)
!ines " and # associate Facker5G and Fnacker5*G resecti1ely* wit&
FtA#5*G usin' t&e OTcl command attac(JA#T*) .e/ined in CCC class
A##** t&is OTcl command stores t&e inut ar'ument ?i)e)* FtA#5G in our case@
in t&e CCC class 1ariable Far+5t*5G ?see Pro'ram 13)8@) Cinally* !ines 1,H13
con/i'ure t&e rest o/ t&e comonents as s&own in Ci') 13)1)
%*=%=*=2 'nst&roc &imulator66link#ar-/limit from to'
Crom t&e Tcl simulation scrit* t&e Sim!lator obBect is readily accessible*
w&ile SimpleLink obBects are not) 4ctin' as a ro'rammin' inter/ace /rom
t&e Tcl simulation scrit* t&is instroc ?!ines 12H2,@ in1okes t&e instroc linkJ
ar+/III'
13)1 4utomatic (eeat reIuest 332
o/ t&e SimpleLink obBect) In articular* it creates and con/i'ures 4(I
modules o/ t&e link connectin' Node F"romG to Node Fto)G T&e inut ar'ument
FlimitG &ere is used as t&e retry limit o/ t&e 4(I module)
E%ample $** 6e now setu an eAeriment to s&ow t&e imact o/ a limited9
ersistence sto9and9wait 4(I rotocol on TCP t&rou'&ut) Our eAeriment is
based on Sect) 1,)1) 6e insert an error module wit& ,)3 error robability in t&e
link connectin' Node n2 to Node n3* imlement a limited9ersistence 4(I o1er
t&is lossy link* 1ary t&e retry limit /rom , to 3* and lot TCP t&rou'&ut 1ersus t&e
retry limit)
Tcl Simulation Script
6e insert t&e /ollowin' codes in t&e Tcl simulation scrit /ile FtcpItclG in
Sect) 1,)1<
MMtcpItcl
2 set em ?ne, Error%odel@
1 Pem set rate5 0I3
3 Pem !nit pkt
= Pem ranvar ?ne, #andomSariableMDni"orm@
> Pem dropJtar$et ?ne, A$entMN!ll@
A Pns linkJlossmodel Pem Pn2 Pn3
B Pns linkJar+ 3 Pn2 Pn3
/ proc s(o,5tcp5se+no 78 7
G $lobal tcp
20 p!ts HT(e "inal tcp se+!ence n!mber is
?Ptcp set t5se+no5@H
22 8
21 Pns at 0I0 HP"tp startH
23 Pns at 200I0 Hs(o,5tcp5se+noH
2= Pns at 200I2 HPns (altH
2> Pns r!n
Here* !ines 1H8 create an error module wit& acket error robability ,)3* and
insert t&e created error module immediately a/ter t&e inst1ar Flink5G o/ t&e
SimpleLink obBect connectin' Node n2 and Node n3) !ine 2 creates and
con/i'ures 4(I9related comonents wit& retry limit o/ 3) 6e run t&e simulation
/or 1,,)1 s and collect t&e results w&en t&e simulation time is 1,,), s) 4/ter
runnin' t&e scrit /ile FtcpItclG abo1e* t&e /ollowin' result aears on t&e
screen<
KK ns tcpItcl
KK T(e "inal tcp se+!ence n!mber is 3B>/B
'
0
P

t
h
r
o
u
4
h
6
u
t

(
6
a
c
1
e
t
s

s
e
c
o
n
d
s
)
338 13 .e1eloin' New %odules /or NS2
4ig= %*=/ Imact o/ t&e retry
4!!
limit o/ a limited ersistent
4(I rotocol on TCP
3%!
t&rou'&ut
3!!
2%!
2!!
1%!
1!!
%!
!
! 1 2 3
=etry limit
TCP t&rou'&ut in ackets er second is comuted as t&e /inal TCP seDuence
number di1ided by t&e simulation time) 6e 1ary t&e retry limit ?in !ine 2 abo1e@
to /,O 1O 2O 3'* and lot TCP t&rou'&ut in Ci') 13):) Clearly* increasin' retry
limit increases link reliability and t&ere/ore increases TCP t&rou'&ut)
1".1.$ AR> 0nder a )elayed B*rror(5reeC 5eed-ac'
Channel
6e &a1e de1eloed an NS2 module /or an 4(I rotocol wit& an immediate and
error9/ree /eedback) T&is section eAtends t&e modules de1eloed earlier /or a non)
immediate error9/ree /eedback c&annel) T&e eAtension /or a non9immediate and
error)prone /eedback c&annel is le/t /or t&e reader as an eAercise)
6e modi/y t&e 4(I modules in Sects) 13)1)2H13)1)3 usin' t&e Sc&eduler) T&e
idea is to delay t&e transmission o/ 4CK$N4CK messa'es /or a certain amount o/
time) T&e modi/ication is s&own in Pro'ram 13)")
%*=%=/=% 4unction recv)%+h* of AR?
Receivers
6e mo1e t&e /unction recv&p)(' /rom classes A#Acker and A#Nacker
to t&eir base class A##*) T&e new /unction recv&p)(' is de/ined in !ines 1H
")
T&e delay is imlemented by sc&edulin' acket recetion e1ents on t&e sim9
ulation timeline a/ter Fdelay5G seconds ?see Sect) :)3 /or details about t&e
/unction sc(ed!le&III'@) 4t t&e /irin' time* t&e Sc&eduler will in1oke
/unction (andle&e' associated wit& t&e /irst inut ar'ument o/ t&e
/unction sc(ed!le&III'* i)e)* t&e ointer Ft(isG ?see !ine 3@) Here* t&e
ointer Ft(isG oints to eit&er an A#Acker obBect or an A#Nacker obBect*
w&ose details are
13)2 Packet Sc&edulin' /or %ulti9Clow .ata Transmission 33#
Program %*=7 %odi/ication in /ile ar+Icc /or 4(I wit& error9/ree delay
/eedback c&annels
MMar+Icc
2 void A##*99recv&Packet
N
p) Handler
N
('
1 7
3 pkt5 : p; (andler5 : (;
= i" &delay5 K 0'
> Sc(ed!ler99instance&'Isc(ed!le&t(is) Fevent5)
delay5';
A else
B (andle&Fevent5';
/ 8
G void A#Acker99(andle&Event
N
e'
20 7
22 ar+5t*5JKack&';
21 send&pkt5)(andler5';
23 8
2= void A#Nacker99(andle&Event
N
e'
2> 7
2A ar+5t*5JKnack&pkt5';
2B 8
2/ A##*99A##*&'
2G 7
10 pkt5 : 0; (andler5 : 0; delay5 : 0;
12 bind&Hdelay5H) Fdelay5';
11 8
s&own in !ines #H13 and 1:H12* resecti1ely) T&ese two /unctions er/orm t&e
same actions as t&ose in t&e /unction recv&p)(' in Sect) 13)1)2)
%*=%=/=2 Bining >ariab#e dela$
In t&e constructor* we bind t&e 1ariable Fdelay5G to t&e OTcl inst1ar wit& t&e
same name ?see !ines 1"H22@)
%*=%=/=* $onfiguration in the ,Tc# -omain
In t&e OTcl domain* we also need to include t&e two /ollowin' lines into t&e
instroc
linkJar+/limit' o/ class SimpleLink ?e)')* a/ter !ine 8 in Pro'ram 13)2@<
Packer5 set delay5 ?Psel" delay@
Pnacker5 set delay5 ?Psel" delay@
Here* t&e link delay in t&e /orward direction ?returned /rom Psel" delay@
is used as t&e 4(I /eedback delay /or bot& 4CK and N4CK 'enerators ?i)e)*
Facker5G and Fnacker5*G resecti1ely@)
E%ample $*2* Comare t&e TCP t&rou'&uts /or t&e cases wit& an immediate
/eedback c&annel and a delayed /eedback c&annel in t&e link layer 4(I rotocols)
33" 13 .e1eloin' New %odules /or NS2
Here* we use t&e results in EAamle 13)1 as a benc&mark) 6&en rerunnin' t&e Tcl
simulation scrit in EAamle 13)1 under t&e 4(I rotocol wit& a delayed
/eedback c&annel* t&e /ollowin' result s&ould aear on t&e screen<
KK ns tcpItcl
KK T(e "inal tcp se+!ence n!mber is 10>GA
w&ic& is less t&an 323"2 in EAamle 13)1) T&e readers are encoura'ed to
eAeriment wit& di//erent inut arameters ?e)')* /eedback delay or retry limit@
to 'ain more insi'&ts into t&e imact o/ link layer 4(I rotocols on TCP
er/ormance)
%*=2 Packet Scheu#ing for Mu#ti.4#ow -ata Transmission
Packet sc&edulin' is a mec&anism to arran'e transmission seDuence o/ incomin'
ackets) Cor eAamle* a round)ro'in ?((@ acket sc&eduler transmits ackets /rom
di//erent /lows in seDuence) T&is section s&ows t&e imlementation o/ a round9
robin acket sc&eduler in NS2)
1".2.1 The )esign
6e modi/y t&e acket sc&eduler by addin' /ew comonents into a SimpleLink
obBect as s&own in Ci') 13)3)
%*=2=%=% Architecture of a &im%le'ink with a Packet
Scheu#er
T&e key modi/ications are as /ollows<
Source traffic< 6e assume t&at eac& tra//ic source ta's ackets wit& its uniDue
/low I.)
&low classifiers< Packets /rom di//erent sources are miAed as t&ey enter a
SimpleLink obBect) T&ese unclassi/ied ackets 'et classi/ied by a /low clas9
si/ier) Packets wit& t&e same /low I. are transmitted to t&e same lace)
+ ,ueue array< 4 dedicated Dueue is ro1ided /or ackets w&ose /low I.s are
t&e same ?i)e)* 'enerated /rom t&e same source@)
The packet scheduler< T&e acket sc&eduler /etc&es and transmits ackets /rom
t&e Dueue array) It selects t&e Dueue to /etc& a acket based on t&e underlyin'
sc&edulin' olicy)
13)2 Packet Sc&edulin' /or %ulti9Clow .ata Transmission 381
'raffic
source !
'raffic
source 1
6ac1et
fidC @ !
SimpleLink
3ueuesC
headC
slot ! 3ueuesCU!V
tar4etC tar4etC tar4etC
fidC @ 1
6ac1et
tar4etC
flo>CclsfrC slot 1
3ueuesCU1V
schC lin1C ttlC
slot TnumC3ueuesC
3ueuesC
UnumC3ueuesCV
tar4etC
flo>CclsfrC for>ards
6ac1ets >ith flo> /D
i to 3ueueCUiV
dro6C
dro6C
dro6headC
4ig= %*=0 4rc&itecture o/ a LinkSc(
obBect
%*=2=%=2 Packet 4orwaring an $a##back Mechanism
T&e rocess be'ins w&en unclassi/ied ackets enters t&e SimpleLink obBect
and roceeds as /ollows<
1) T&e /low classi/ier /orwards ackets wit& t&e same /low I. to t&e same
Dueue)
2) 6&en not blocked* a Dueue sends a acket to its downstream acket
sc&eduler)
3) T&e acket sc&eduler selects a /low* transmits a acket /rom t&e selected /low*
and /etc&es anot&er acket /rom t&e Dueue corresondin' to t&e selected /low)
:) 4/ter a transmission* t&e acket sc&eduler blocks itsel/ until it recei1es a
callback messa'e* indicatin' t&at t&e endin' acket transmission is comlete)
3) 6&en recei1in' a acket* a LinkDelay sc&edules a transmission o/ a
callback messa'e to t&e ustream acket sc&eduler w&en t&e acket
transmission rocess is comlete)
8) 4t t&e /irin' time* t&e rocess 'oes back to ste
?3@)
1".2.2 CCC Ipleentation
6e de1elo t&ree /ollowin' CCC classes< Qlo,Classi"ier*
PktSc(ed!ler* and ##Sc(ed!ler
%*=2=2=% $#ass 7lo.Classifier
Class Qlo,Classi"ier reresents /low classi/iers discussed earlier) T&e CCC
code /or t&is class is s&own in Pro'ram 13)#) Crom !ines 1,H18* t&is class is
bound to t&e OTcl class Classi"ierMQlo,) 4'ain* /low classi/iers are
resonsible /or classi/yin' ackets based on /low I.* as imlemented in !ines 12H
21)
P r ogram %*=8 C CC Im le m e n tati o n o / class Qlo,Classi"ier
MM classi"ierJ"lo,I(
2 Oincl!de HpacketI(H
1 Oincl!de HipI(H
3 Oincl!de Hclassi"ierI(H
= class Qlo,Classi"ier 9 p!blic Classi"ier 7
> protected9
A int classi"y&Packet
N
p';
B 8;
MM classi"ierJ"lo,Icc
/ Oincl!de Hclassi"ierJ"lo,I(H
G Oincl!de HipI(H
20 static class Qlo,Classi"ierClass 9 p!blic TclClass 7
22 p!blic9
21 Qlo,Classi"ierClass&' 9 TclClass&HClassi"ierMQlo,H' 78
23 TclObject
N
create&int) const c(ar
N
const
N
' 7
2= ret!rn &ne, Qlo,Classi"ier&'';
2> 8
2A 8 class5"lo,5classi"ier;
2B int Qlo,Classi"ier99classi"y&Packet
N
p'
2/ 7
2G int "lo, : (dr5ip99access&p'JK"lo,id&';
10 ret!rn "lo,;
12 8
%*=2=2=2 $#ass Pkt&cheduler
T&e main resonsibility o/ a acket sc&eduler is to determine transmission
seDuence o/ t&e attac&ed ustream !e!e obBects) In t&is section* we assume
t&at eac& !e!e obBect &olds ackets o/ t&e same /low I. and t&e acket
sc&eduler determines t&e transmission seDuence based on t&e /low I. only)
Pro'rams 13)1, and 13)11 s&ow t&e declaration and imlementation*
resecti1ely* o/ CCC class PktSc(ed!ler) Crom Pro'ram 13)1,* class
PktSc(ed!ler &as one constant and t&ree key 1ariables<
%AL5QLOW T&e maAimum number o/ Dueues w&ic& can be
attac&ed to t&e acket sc&eduler)
blocked5 Set to F1G i/ t&e acket sc&eduler is transmittin' a
acket* and set to F,G ot&erwise)
pkt5?i@ T&e acket /rom /low FiG waitin' to be transmit9
ted
(andler5?i@ T&e !e!eHandler obBect o/ t&e Dueue corre9
sondin' to /low FiG
Pro'ram 13)11 s&ows /unction imlementation o/ class PktSc(ed!ler) In
!ines 3"H::* t&e /unction recv&p)(' determines and stores t&e /low I. o/ t&e
incomin' acket in a local 1ariable Fpid)G !ine :1 stores t&e acket as well as t&e
inut &andler in its class 1ariables pkt5?pid@ and +(5?pid@* resecti1ely) I/
not
13)2 Packet Sc&edulin' /or %ulti9Clow .ata Transmission 383
P r ogram %*=%: .eclaration o / C CC cla s s PktSc(ed!ler
MM pktJsc(edI(
2 Oincl!de HconnectorI(H
1 Oincl!de HipI(H
3 Ode"ine %AL5QLOWS 20
= class PktSc(ed!ler 9 p!blic Connector 7
> p!blic9
A PktSc(ed!ler&';
B virt!al void (andle&Event
N
';
/ virt!al void recv&Packet
N
) Handler
N
';
G protected9
20 void sendNe*tPkt&';
22 int $etPktID&Packet
N
p' 7 ret!rn (dr5ip99access&p'JK
"lo,id&'; 8
21 virt!al int ne*tID&':0;
23 Handler
N
+(5?%AL5QLOWS@;
2= Packet
N
pkt5?%AL5QLOWS@;
2> int blocked5;
2A 8;
P r ogram %*=%% C unc ti ons o/ C CC cla s s PktSc(ed!ler
MM pktJsc(edIcc
2B Oincl!de HpktJsc(edI(H
2/ PktSc(ed!ler99PktSc(ed!ler&'
2G 7
10 "or &int i:0;i<%AL5QLOWS;i44'7
12 pkt5?i@ : 0; +(5?i@:0;
11 8
13 blocked5 : 0;
1= 8
1> void PktSc(ed!ler99(andle&Event
N
'
1A 7
1B blocked5 : 0; sendNe*tPkt&';
1/ 8
1G void PktSc(ed!ler99sendNe*tPkt&'
30 7
32 int nid : ne*tID&';
31 i" &nid K:0' 7
33 send&pkt5?nid@)t(is';
3= blocked5 : 2; pkt5?nid@ : 0;
3> +(5?nid@JK(andle&0';
3A 8
3B 8
3/ void PktSc(ed!ler99recv&Packet
N
p) Handler
N
('
3G 7
=0 int pid : $etPktID&p';
=2 pkt5?pid@ : p; +(5?pid@ : (;
=1 i" &Cblocked5'
=3 sendNe*tPkt&';
== 8
382 13 .e1eloin' New %odules /or NS2
blocked ?i)e)* no endin' acket transmission@* t&e acket transmitter will select
and send out one acket to its downstream obBect* usin' /unction
sendNe*tPkt&')
In !ines 2#H32* t&e /unction sendNe*tPkt&' /irst determines t&e neAt
/low w&ic& will be allowed to transmit a acket usin' /unction ne*tID&')
+ein' ure 1irtual* t&e /unction ne*tID&' /orces t&e deri1ed classes o/ class
PktSc(ed!ler to ro1ide &ow t&e neAt /low is selected based on underlyin'
sc&edulin' olicy) T&is /unction returns t&e /low I. o/ t&e neAt /low* or F91G i/ all
t&e /lows do not &a1e ackets to
transmit)
Suose t&ere is at least one /low w&ic& &as ackets to transmit) T&e acket
sc&eduler sends out t&e acket ?!ine 33@* blocks itsel/ ?!ine 3:@* resets t&e
1ariable pkt5?nid@ ?!ine 3:@* and /etc&es a new acket /rom t&e ustream
!e!e obBect ?!ine 33@)
T&is eAamle s&ows anot&er tye o/ callback mec&anism w&ic& does not use a
&andler dedicated to t&e acket sc&eduler) Crom !ine 33* t&e acket sc&eduler
sends t&e ointer to itsel/ ?i)e)* Ft(isG@ alon' wit& t&e acket to its downstream
obBect) 6&en t&is ointer reac&es a LinkDelay obBect* it is laced on t&e
simulation timeline) 4t t&e /irin' time* t&e /unction (andle&e' o/ t&e acket
sc&eduler is eAecuted at t&e /irin' time)
%*=2=2=* $#ass RR&cheduler
Pro'ram 13)12 s&ows t&e details o/ class ##Sc(ed!ler) 6e deri1e a CCC class
##Sc(ed!ler /rom class PktSc(ed!ler* and bind t&is class to an OTcl class
PktSc(ed!lerM## ?!ines 32H3"@) Class ##Sc(ed!ler contains only one
1ariable Fc!rrent5id5G w&ic& stores t&e I. o/ t&e /low w&ose &ead o/ t&e line
acket is bein' transmitted)
Class ##Sc(ed!ler o1errides t&e ure 1irtual /unction ne*tID&' de/ined
in its base class) T&is /unction returns t&e neAt I. w&ic& &as a acket to transmit*
and returns 1 i/ all /lows &a1e no acket to transmit ?!ines 83H23@)
1".2." OTcl Ipleentation
In t&e OTcl domain* we insert t&ree /ollowin' comonents into class
SimpleLink* as s&own in Ci') 13)3<
sc(5 4 round9robin sc&eduler w&ose class is
PktSc(ed!lerM##
"lo,5cls"r5 4 /low classi/ier
+!e!es5 4 Dueue array w&ic& stores ackets /rom
di//erent /lows classi/ied by t&e /low clas9
si/ier
Crom Pro'ram 13)13* we de1elo two instrocs to con/i'ure acket sc&edulers
in t&e OTcl domain<
13)2 Packet Sc&edulin' /or %ulti9Clow .ata Transmission 383
P r ogram %*=%2 C CC im le m e n tati o n o / C CC Cl a s s ##Sc(ed!ler
MM pktJsc(edI(
=> class ##Sc(ed!ler 9 p!blic PktSc(ed!ler 7
=A p!blic9
=B ##Sc(ed!ler&' ;
=/ private9
=G virt!al int ne*tID&';
>0 int c!rrent5id5;
>2 8;
MM pktJsc(edIcc
>1 static class ##Sc(ed!lerClass9 p!blic TclClass 7
>3 p!blic9
>= ##Sc(ed!lerClass&' 9 TclClass&HPktSc(ed!lerM##H' 78
>> TclObject
N
create&int) const c(ar
N
const
N
' 7
>A ret!rn &ne, ##Sc(ed!ler&'';
>B 8
>/ 8 class5rr5sc(ed!ler;
>G ##Sc(ed!ler99##Sc(ed!ler&'
A0 7
A2 c!rrent5id5 : J2;
A1 8
A3 int ##Sc(ed!ler99ne*tID&'
A= 7
A> int co!nt : 0;
AA c!rrent5id5 : &c!rrent5id5 4 2 ' E %AL5QLOWS;
AB ,(ile& &pkt5?c!rrent5id5@ :: 0' FF &co!nt<%AL5QLOWS' ' 7
A/ c!rrent5id5 : &c!rrent5id5 4 2 ' E %AL5QLOWS;
AG co!nt44;
B0 8
B2 i" &co!nt :: %AL5QLOWS'
B1 ret!rn J2;
B3 else
B= ret!rn c!rrent5id5;
B> 8
%*=2=*=% 'nst&roc insert#sched /num -ueues' of c#ass &im%le'ink
T&is instroc inserts acket9sc&eduler9related comonents into a SimpleLink
obBect) !ines : and 3 create a /low classi/ier F"lo,5cls"r5G and a acket
sc&ed9 uler Fsc(5*G resecti1ely) !ines 8H12 create a Dueue array wit&
Fn!m5+!e!esG comonents to store ackets /rom di//erent /lows) T&e it&
Dueue is created and installed in t&e it& slot o/ t&e /low classi/ier ?!ines 2 and "@)
T&e tar'et and dro9 tar'et o/ e1ery Dueue are directed to t&e acket sc&eduler
and t&e droin' oint ?i)e)* Fdrop(ead5G@* resecti1ely ?!ines # and 1,@) T&e
Dueue is t&en initialiJed by its instroc reset) Cinally* !ines 13H13 insert t&e
abo1e comonents between F(ead5G and Flink5)G
38: 13 .e1eloin' New %odules /or NS2
Program %*=%* OTcl imlementation o/ a link wit& a round9robin acket sc&eduler
MMUpktJsc(edItcl
2 SimpleLink instproc insertJsc(ed 7n!m5+!e!es8 7
1 Psel" instvar link5 +!e!es5 (ead5 drop(ead5
3 Psel" instvar sc(5 "lo,5cls"r5
= set "lo,5cls"r5 ?ne, Classi"ierMQlo,@
> set sc(5 ?ne, PktSc(ed!lerM##@
A "or 7set i 08 7Pi < Pn!m5+!e!es8 7incr i8 7
B set +!e!es5&Pi' ?ne, !e!eMDropTail@
/ P"lo,5cls"r5 install Pi P+!e!es5&Pi'
G P+!e!es5&Pi' tar$et Psc(5
20 P+!e!es5&Pi' dropJtar$et Pdrop(ead5
22 P+!e!es5&Pi' reset
21 8
23 P(ead5 tar$et P"lo,5cls"r5
2= Psc(5 tar$et Plink5
2> Psc(5 dropJtar$et Pdrop(ead5
2A 8
2B Sim!lator instproc insertJsc(edJtoJSL 7"rom to n!m5+!e!es8 7
2/ set link ?Psel" link P"rom Pto@
2G Plink insertJsc(ed Pn!m5+!e!es
10 8
%*=2=*=2 'nst&roc insert#sched#to#&'/from to num -ueues'
of c#ass &imulator
(eadily accessible to t&e Tcl simulation scrit* t&is instroc con/i'ures t&e link
connectin' Node F"romG and Node Fto*G as s&own in Ci') 13)3) In EAamle 13)3*
we s&all use t&is instroc to insert acket9sc&eduler9related comonents into a
SimpleLink obBect)
E%ample $*$* Consider Sect) 1,)1 and Ci') #)3) (elace t&e TCP /low wit&
Fn!m5+!e!esG TCP /lows w&ose /low I. are ,* 1* 2* and so on) 4ly a round9
robin acket sc&edulin' disciline to t&e link connectin' t&e Node n2 and t&e
Node n3)
Tcl Simulation Script
MMpktJsc(edItcl
12 set n!m5+!e!es ?linde* Par$v 0@
11 set ns ?ne, Sim!lator@
13 set n2 ?Pns node@
1= set n1 ?Pns node@
1> set n3 ?Pns node@
1A Pns d!ple*Jlink Pn2 Pn1 >%b 1ms DropTail
13)3 C&ater Summary 382
1B Pns d!ple*Jlink Pn1 Pn3 >%b 1ms DropTail
1/ Pns d!ple*Jlink Pn2 Pn3 >%b 1ms DropTail
1G Pns insertJsc(edJtoJSL Pn2 Pn3 Pn!m5+!e!es
30 "or 7set i 08 7Pi < Pn!m5+!e!es8 7incr i8 7
32 set tcp&Pi' ?ne, A$entMTCP@
31 set sink&Pi' ?ne, A$entMTCPSink@
33 set "tp&Pi' ?ne, ApplicationMQTP@
3= Ptcp&Pi' set "id5 Pi
3> Pns attac(Ja$ent Pn2 Ptcp&Pi'
3A Pns attac(Ja$ent Pn3 Psink&Pi'
3B P"tp&Pi' attac(Ja$ent Ptcp&Pi'
3/ Pns connect Ptcp&Pi' Psink&Pi'
3G Pns at 0I0 HP"tp&Pi' startH
=0 8
=2 Pns at 200I2 HPns (altH
=1 Pns r!n
T&e abo1e Tcl simulation scrit FpktJsc(edItclG takes t&e number o/ TCP
/lows as an inut ar'ument* and simulates t&e transmission o/ t&ese TCP /lows
under a round9robin acket sc&eduler)
!ine 21 takes an inut ar'ument /rom t&e s&ell and stores it in a local
1ariable Fn!m5+!e!esG ?see t&e syntaA /or inuttin' arameters in Tcl in a local
Sect) 4)1)1@) !ine 2# inserts comonents related to a acket sc&eduler into t&e
SimpleLink obBect connectin' Node Pn2 and Node Pn3) T&e F"orG loo
in !ines 3,H:, creates and con/i'ures TCP /lows* w&ere ackets created by t&e
Fit&G element o/ FtcpG are ta''ed wit& /low I. FiG ?by !ine 3:@)
+y runnin' t&e simulation /or 1 TCP /low and 3 TCP /lows* t&e /ollowin'
results
are s&own on t&e screen)
KK ns pktJsc(edItcl 2
T(e "inal tcp&0' se+!ence n!mber is A0220
KK ns pktJsc(edItcl 3
T(e "inal tcp&0' se+!ence n!mber is 100>1
T(e "inal tcp&2' se+!ence n!mber is 100>2
T(e "inal tcp&1' se+!ence n!mber is 100>2
T&e TCP t&rou'&ut is comuted by t&e /inal seDuence number di1ided by t&e
simulation time) Since t&e simulation time &ere is 1,, s ?see !ine 2"@* t&e
t&rou'&ut o/ TCP /low F0G is 81,)1 ackets$s and 2,,)32 ackets$s w&en t&e
number o/ TCP /lows is 1 and 3* resecti1ely)
6it& a round9robin sc&eduler* eac& element o/ t&e array F+!e!e5G &as eDual
c&ance to transmit ackets) In rincile* e1ery TCP /low s&ould &a1e t&e same
t&rou'&ut er/ormance ?as s&own abo1e@) 4lso* t&e er9/low t&rou'&ut in case
o/ n TCP /lows s&ould be aroAimately n times less t&an t&at in t&e case o/ sin'le
TCP /low)
P
e
r
X
f
l
o
>

a
(
e
r
a
4
e

'
0
P

t
h
r
o
u
4
h
6
u
t
(
6
a
c
1
e
t
s

6
e
r

s
e
c
o
n
d
)
388 13 .e1eloin' New %odules /or NS2
A!!
&!!
.air share
,(era4e throu4h6ut
%!!
4!!
3!!
2!!
1!!
!
1 2 3 4 % & A B 1!
)umber of '0P flo>s
4ig= %*=6 Imact o/ number o/ TCP /lows on er9/low t&rou'&ut under round9robin acket
sc&edulin'
Crom t&e results s&own abo1e* t&e er9/low TCP t&rou'&ut o/ all t&e /lows
1aries 1ery little /rom eac& ot&er) 4lso* t&e t&rou'&ut is aroAimately one9t&ird
o/ TCP t&rou'&ut in case o/ sin'le TCP /low ?i)e)* ?8,11,$1,,@$3 U 8,1)1,$3 U
2,,)32@)
NeAt* we run t&e abo1e Tcl simulation scrit /or 1H1, TCP /lows) 6e comare
t&e a1era'e TCP t&rou'&ut and t&e fair share TCP t&rou'&ut in Ci') 13)8) Here*
we de/ine t&e fair share TCP t&rou'&ut /or n TCP /lows as Un* w&ere is t&e
TCP t&rou'&ut in t&e case o/ sin'le TCP /low) 6e obser1e t&at bot& a1era'e
and /air s&are t&rou'&ut are almost inline wit& eac& ot&er) 6e also obser1e t&at
TCP t&rou'&ut /or eac& /low is 1ery similar to eac& ot&er) T&ese two
obser1ations 1alidate t&e round9robin oeration* w&ic& treats e1ery TCP /low
eDually)
%*=* $ha&ter Summary
T&is c&ater demonstrates &ow new modules are created* con/i'ured* and incor9
orated into NS2) Two eAamles are ro1ided &ere on 4utomatic (eeat reIuest
?4(I@9based error reco1ery modules and acket sc&edulin' modules) In most o/
t&e cases* we need to de1elo NS2 ro'ram in bot& CCC and OTcl domains) In
t&e CCC domain* t&e main task is to de/ine t&e internal mec&anisms o/ t&e new
NS2 comonents) T&e main tasks in t&e OTcl domain* on t&e ot&er &and* are to
inte'rate t&e de1eloed NS2 comonents into t&e eAistin' NS2 modules* and to
instantiate and con/i'ure t&e newly de1eloed modules /rom a Tcl simulation
scrit)
38" 13 .e1eloin' New %odules /or NS2
%*=/ "<ercises
1) T&e imlementation o/ a delayed /eedback c&annel makes use o/ t&e /unction
sc(ed!le&III' o/ class Sc(ed!ler) Can we use class TimerHandler
/or t&e imlementation insteadR .iscuss t&e ros and cons)
2) Consider t&e CCC classes A#T* and PktSc(ed!ler in Sects) 13)1)2 and
13)2)2) .o we need t&e class 1ariable Fblocked5GR 6&y or w&y notR
3) In Sect) 13)1):* we s&ow &ow t&e /ile ar+Icc can be modi/ied to incororate
/eedback delay)
a) %odi/y t&e /ile ar+I( and re'enerate t&e results)
b) .o we need 1ariables Fpkt5*G F(andler5*G Fevent5*G Fdelay5GR 6&y
or w&y notR
:) Consider t&e 4(I modules de1eloed in t&is c&ater)
a) Can you remo1e class A#HandlerR 6&y and w&y notR
b) (e'enerate t&e result o/ EAamle 13)2 wit& t&e retry limit bein' ,* 1* 2* and
3) Plot t&e result on Ci') 13)8) .iscuss t&e imact o/ t&e delay on t&e
/eedback c&annel)
c) .e1elo a module /or an 4(I rotocol wit& an error prone delayed
/eedback c&annel)
d) %odi/y t&e 4(I to be timer9based retransmission mec&anism< 4 acket is
assumed to be lost unless an 4CK messa'e is recei1ed wit&in a timeout
eriod)
e) T&e de1eloed 4(I modules are associated wit& a SimpleLink obBect)
(edesi'n t&e modules suc& t&at it aear as a comonent in a Node) Test your
module in bot& wired and wireless networks)
/) T&is c&ater imlements 4(I at t&e link le1el) (edesi'n t&e modules to
oerate at connection le1el ?i)e)* end9to9end@) Incororate your modules wit&
0.P to test your modules)
3) .esi'n a link wit& a round9robin acket sc&eduler and an 4(I9based error
control mec&anism)
8) (edesi'n t&e acket sc&edulers de1eloed in t&is c&ater) Imlement t&e acket
sc&eduler as a comonent in a node) Test your imlementation wit& wired and
wireless networks)
2) 4 6ei'&ted Cair Iueue ?6CI@ acket sc&eduler 'i1es /air access to e1ery data
/low) 0nder a 6CI acket sc&eduler* eac& data /low 'ains c&annel access in
roortion to its wei'&t) T&e al'orit&m /or 6CI9based acket sc&edulin' can
be /ound in M2"N) .e1elo a module /or a 6CI acket sc&eduler) 7alidate t&e
module by lottin' t&e results in a 'ra&)
$ha&ter %/
Postsimu#ation Processing2 -ebugging3
Tracing3 an Resu#t $om&i#ation
4 tyical NS2 simulation consists o/ t&ree main stes< ?1@ simulation desi'n* ?2@
con/i'urin' and runnin' simulation* and ?3@ ostsimulation rocessin' ?see Ci')
2)3 in Sect) 2)3)2@) T&e /ormer two asects were discussed eAtensi1ely in t&e
re1ious c&aters* w&ile t&e last asect will be discussed in t&is c&ater)
Postsimulation rocessin' encomasses de'ugging* tracing* and compilation
of simulation results) .ebu''in' is a rocess o/ remo1in' ro'rammin' errors)
7ariable tracin' tracks c&an'es in 1ariables under consideration) Packet tracin'
records t&e details o/ ackets assin' t&rou'& network c&eckoints) Simulation
result comilation collects in/ormation and comutes rele1ant er/ormance mea9
sures /rom t&e simulation) T&is c&ater discusses t&e details o/ debu''in'*
1ariable tracin'* acket tracin'* and result comilation in Sects) 1:)1* 1:)2* 1:)3*
and 1:):* resecti1ely) Cinally* t&e c&ater summary is 'i1en in Sect) 1:)3)
%/=% -ebugging2 A Process to Remove Programming "rrors
4 ro'rammin' error is usually re/erred to as a 'ug) T&e rocess o/ locatin' and
/iAin' t&e error is usually called de'ugging) T&is section discusses two tyes o/
ro'rammin' errors ?i)e)* bu's@ and ro1ides 'uidelines /or debu''in' in NS2)
1$.1.1 Types of Prograing *rrors
+ased on t&e NS2 arc&itecture* ro'rammin' errors can be classi/ied into comila9
tion errors and runtime errors)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 1:* = Srin'er Science>+usiness %edia* !!C 2,12
38#
1:)1 .ebu''in'< 4 Process to (emo1e Pro'rammin' Errors 321
%/=%=%=% $om&i#ation "rrors ($CC ,n#y)
T&is tye o/ errors occurs durin' a comilation rocess* w&ic& consists o/ two
&ases) T&e /irst &ase con1erts CCC /iles ?wit& eAtension FIcc)(G@ into obBect
/iles ?wit& eAtension FIoG@) In t&is &ase* errors may occur i/ t&e comiler does
not understand t&e CCC codes) In t&is case* t&e comiler will s&ow error
messa'es on t&e screen* indicatin' t&e location and t&e reason o/ t&e errors)
EAamles o/ CCC comilation errors include<
Incorrect CCC syntaA
0sin' unde/ined 1ariables and$or /unctions)
In t&e second &ase* t&e comiler links t&e created obBect /iles and creates an
eAecutable FnsG /ile) 4n error in t&is &ase is caused by imroer linka'e o/ CCC
/iles) EAamles o/ CCC linkin' errors include<
Instantiate an o'3ect from an a'stract class< .urin' a linkin' rocess* an error
will occur i/ an obBect is instantiated /rom an abstract class* w&ic& lea1es at
least one ure 1irtual /unction unimlemented)
4 roer solution to t&is error is to ro1ide imlementation /or t&e ure
1irtual /unction) Howe1er* /or simlicity ?but not /or aroriateness@* a user
may ro1ide emty imlementation /or t&e ure 1irtual /unction to remo1e t&e
error)
5odifying a 'ase class without creating the o'3ect files of the child classes<
T&is error usually occurs w&en t&e deendency in t&e F%ake"ileG is not
roerly de/ined) 6&en a certain class is modi/ied* t&e comiler does not
recreate obBect /iles o/ t&e c&ild classes) T&e solution is to de/ine t&e
deendency in t&e F%ake"ileG roerly* or to remo1e all related obBect /iles
be/ore comilin' t&e codes)
Note t&at OTcl is a scritin' lan'ua'e) T&ere is no need to comile OTcl
ro'ram be/ore t&e eAecution) T&ere/ore* comilation errors do not occur in t&e
OTcl domain)
%/=%=%=2 Runtime "rrors
T&is tye o/ errors occurs durin' NS2 simulation) It is caused by imroer OTcl
and$or CCC ro'rammin') Since t&e OTcl domain imlements error messa'e
tra9 in' mec&anism* an OTcl error messa'e contains detailed and use/ul
in/ormation) Eac& error messa'e indicates w&ere and w&y t&e error occurred) T&e
CCC domain* on t&e ot&er &and* does not imlement error train') Lenerally t&e
error messa'es in t&is case ?e)')* se'mentation /ault@ are /airly s&ort and do not
contain muc& in/ormation) EAamles o/ OTcl runtime errors include
Incorrect OTcl syntaA
(e/errin' to inst1ars* instrocs* or commands w&ic& do not
eAist)
32, 1: Processin' an NS2 Simulation
EAamles o/ CCC runtime errors include
Segmentation fault< T&is is usually caused by an in1alid access to a memory
content) Cor eAamle* tryin' to access Fa?A@G would cause a se'mentation
/ault i/ FaG was declared as Fint a?3@;)G
Not implementing a mandatory -non)pure virtual0 function< 4art /rom usin'
a ure 1irtual /unction* NS2 ro1ides anot&er way to /orce a c&ild class to
imlement a mandatory /unction) Here* NS2 may imlement error9like actions
?e)')* rint out an error messa'e@ in t&e base class) I/ a c&ild class does not
imlement t&is mandatory /unction* t&e /unction o/ t&e base class will be
in1oked and t&e error9like actions will be taken) EAamles o/ t&is tye o/
errors are t&e imlementation o/ /unctions sendms$&III' and
sendto&III' o/ class A$ent in t&e /ile Tns$common$a'ent)cc)
1$.1.2 )e-!gging ,!idelines
4/ter identi/yin' tyes o/ ro'rammin' errors ?i)e)* bu's@* t&e neAt stes are to
locate t&e ro'rammin' codes w&ic& cause t&e errors and to /iA t&e errors) T&is
section ro1ides 'uidelines w&ic& /acilitate t&e debu''in' rocess)
In 'eneral* two use/ul debu''in' tools are breakoints and 1ariable 1iewers)
4 breakoint is a lace w&ere a ro'ram is intentionally stoed durin' an
eAecution) +y strate'ically lacin' breakoints in a ro'ram* ro'rammers can
easily /ind out t&e statement?s@ resonsible /or an error) 4 1ariable 1iewer* on t&e
ot&er &and* allows t&e ro'rammers to determine t&e 1alues o/ 1ariables and
analyJe t&e cause o/ an error)
T&ere are two debu''in' met&ods in NS2) T&e /irst met&od is to use debu''in'
tools) Cor Tcl* NS2 suorts .on !ibs5 debu''er M28N* w&ile t&e standard LN0
debu''er M22N can be used to debu' t&e CCC codes) T&e second met&od is to
manually debu' t&e ro'ram) Table 1:)1 s&ows a list o/ OTcl and CCC
commands w&ic& can be used /or manual debu''in')
E%ample /** To debu' NS2 codes* it is usually use/ul to identi/y ob9
Bects and$or t&e tyes o/ obBects) Consider two OTcl commands H namely
s(o,Jtar$etJclass and s(o,Jtar$etJaddress in Pro'ram 1:)1)
T&ese two OTcl commands s&ow t&e class and address* resecti1ely* o/ t&e tar'et
o/ a TcpA$ent obBect)
In EAamle 1,)1 w&ic& imlements t&e network in Ci') #)3* insert t&e /ollowin'
lines immediately be/ore !ine 13<
2 p!ts HT(e re"erence strin$ "or Ptcp is PtcpH
1 p!ts HPress #ETD#N to start t(e sim!lationCCH
3 $ets stdin
= Pns at 3I2 HPtcp s(o,Jtar$etJclassH
> Pns at >I2 HPtcp s(o,Jtar$etJaddressH
A Pns at 20I2 HPns (altH
B Pns r!n
1:)1 .ebu''in'< 4 Process to (emo1e Pro'rammin' Errors 323
T ab # e %/ = % .e b u'' i n' co mm ands i n O T cl and C CC do m a i ns
T oo l s O Tcl C CC
+reakoints F$ets stdinG F$etc(ar&'*GFcinG
7ariable 1iewer Fp!tsG
Fprint"&III'*GFco!tG
Simulation time FSim!lator99no,G FSc(ed!ler99clock&'G
Cross9domain /unction
in1ocation
Cross9domain 1ariable
retrie1al
Tcl$OTcl Commands FTcl99eval"&III'G
+ound 1ariables +ound 1ariables
Simulator obBect retrie1al FSim!lator99 FSim!lator99instance&'G
instanceG
Sc&eduler obBect retrie1al N$4 FSc(ed!ler99instance&'G
Passin' an OTcl 1alue to
t&e CCC domain
CCC to OTcl 1ariable
con1ersion
OTcl to CCC 1ariable
con1ersion
N$4 FTclObject99res!lt&III'G
N$4 FTclObject99name&'G
N$4 FTclObject99look!p&III'G
KKns tcpJdb$Itcl
T(e re"erence strin$ "or Ptcp is 5o>>
Press #ETD#N to start t(e sim!lationCC
<#ETD#NK
3I2 OTcl class o" TcpA$ent99tar$et is Classi"ierM
Has(MDest
Press #ETD#N to contin!eCC
<#ETD#NK
>I2 ?Ptcp tar$et@ ret!rns OTcl re"erence strin$ 5o21
and C44
address 0*dA>>c0
>I2 Sariable TcpA$ent99tar$et5 corresponds to OTcl
re"erence strin$ 5o21 and C44 address 0*dA>>c0
Press #ETD#N to contin!eCC
<#ETD#NK
Here* t&e lines wit& <#ETD#NK are actually blank lines* w&ere t&e ro'ram is
aused and waits /or a <#ETD#NK keystroke)
!ines 3H11 in Pro'ram 1:)1 s&ow t&e details o/ OTcl commands s(o,J
tar$et
Jclass/') !ine 8 retrie1es t&e Sim!lator obBect and stores it in a 1ariable
Fsim)G In !ine 2* t&e /unction eval"&III' o/ class Tcl e1aluates t&e Tcl
statement in t&e same manner as print"&III' ?see also Ci') 1:)1@) It uts t&e
1alues stored in tar$et5JKname&' and simJKname&' as t&e /irst and
second
Program %/=% T&e OTcl commands s(o,Jtar$etJclass and s(o,J
tar$etJaddress o/ C>> class TcpA$ent
MMUMnsMtcpMtcpIcc
2 int TcpA$ent99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 III
= TclF tcl : Tcl99instance&';
> i" &strcmp&ar$v?2@) Hs(o,Jtar$etJclassH' :: 0' 7
A Sim!latorF sim : Sim!lator99instance&';
B tclIeval"&Hp!ts ?"ormat THE2I2" OTcl class o"
TcpA$ent99tar$et is ?Es in"o class@TH ?Es no,@ @H)
tar$et5JKname&')simIname&'';
/ co!t<<HPress #ETD#N to contin!eCCTnTnH;
G $etc(ar&';
20 ret!rn &TCL5OV';
22 8
21 i" &strcmp&ar$v?2@) Hs(o,Jtar$etJaddressH' :: 0' 7
23 Sc(ed!lerF sc( : Sc(ed!ler99instance&';
2= tclIeval"&HEs tar$etH)t(isJKname&'';
2> Connector
N
conn:&Connector
N
'TclObject99look!p
&tclIres!lt&'';
2A co!t<<sc(Iclock&'<<H ?Ptcp tar$et@ ret!rns OTcl
re"erence strin$ H<<tclIres!lt&'<<H and C44 address
H<<conn <<HTnH;
2B co!t<<sc(Iclock&'<<H Sariable TcpA$ent99tar$et5
corresponds to OTcl re"erence strin$ H<<tar$et5JK
name&' <<H and C44 address H<<tar$et5<<HTnH;
2/ co!t<<HPress #ETD#N to contin!eCCTnTnH;
2G $etc(ar&';
10 ret!rn &TCL5OV';
12 8
11 III
13 8
tar4etC$Qname()
sim:name()
088
*'cl
e(alf(^6uts Uformat YZ""1:1f *'cl class of 'c6,4ent;;tar4et is U"s info classVYZ U"s no>V V_)
6uts U format ^"1:1f *'cl class of 'c6,4ent;;tar4et is U Co12 info classVZ U Co3 no>V V
4ig= %/=% .etails o/ !ine 2 in Pro'ram 1:)1
1:)2 7ariable Tracin' 323
ar'uments* resecti1ely* and asses t&e entire statement to t&e Tcl interreter)
Here* t&e /unction name&' de/ined in class TclObject is used to translate t&e
CCC 1ariables Ftar$et5G and FsimG to t&e OTcl re/erence strin's)
!ines 12H21 in Pro'ram 3)1 s&ow t&e details o/ t&e OTcl command
s(o,Jtar$etJaddress/') !ine 13 /irst retrie1es t&e Sc(ed!ler obBect and
stores it in a 1ariable Fsc()G !ine 1: asks t&e Tcl to interret F5o>> tar$et*G
w&ere 5o>> is t&e OTcl re/erence strin' corresondin' to t&e current TCP
obBect) !ine 13 uses /unction res!lt&' to obtain an OTcl re/erence strin' o/ t&e
tar'et o/ t&e TcpA$ent obBect) It retrie1es a ointer to t&e CCC obBect
corresondin' to a 'i1en strin' usin' t&e /unction look!p&III') T&e retrie1ed
ointer to t&e CCC obBect is t&en cast to a ointer to a Connector obBect and
stored in a local 1ariable Fconn)G Cinally* !ines 18 and 12 dislay t&e tar'et
in/ormation on t&e screen)
%/=2 >ariab#e Tracing
7ariable tracin' records c&an'es in inst1ars o/ TclObBects under
consideration)
1$.2.1 Acti#ation Process for .aria-le
Tracing
7ariable tracin' can be acti1ated in t&e OTcl domain usin' t&e /ollowin' t&ree
stes<
Step > Create a trace /ile w&ose name is <"ilenameK and attac& t&e /ile to a
Tcl /ile c&annel 1ariable w&ose name is <"c(K* usin' t&e /ollowin' syntaA ?see
t&e detail /or Tcl /ile c&annels in Sect) 4)1)2@<
set <"c(K ?open H<"ilenameKH ,@
Step 2> Seci/y t&e inst1ar to be traced usin' t&e /ollowin'
syntaA<
<objK trace <var5nameK ?<tracerK@
w&ere <objK and <var5nameK re/er to an OTcl obBect and t&e name o/
its inst1ar w&ic& needs to be traced) Otionally* ro'rammers can ro1ide
a dedicated tracer obBect* as indicated by <tracerK* w&ic& kees track o/
c&an'es in t&e inst1ar P<var5nameK) I/ a tracer is not 'i1en* NS2 will use
<objK as a tracer
obBect)
Step $> 4ttac& t&e created Tcl /ile c&annel to t&e tracer usin' t&e /ollowin'
syntaA)
<objK attac( P<"c(K* or
<tracerK attac( P<"c(K
w&ere t&e uer line is used w&en no tracer is seci/ied* and t&e lower line is
32: 1: Processin' an NS2 Simulation
used w&en a dedicated tracer is eAlicitly seci/ied)
1:)2 7ariable Tracin' 323
'ime
Source
/P ,ddress
Source
Port
Destination
/P ,ddress
Destination
Port
/nst(arWs
)ame
9alue
1 2 3 4
% & A
4ig= %/=2 Trace /ormat de/ined in class TcpA$ent
E%ample /*2* Suose we would like to trace t&e 1ariable Ft5se+no5G o/ a
TcpA$ent obBect Ptcp in EAamle 1,)1* and store t&e trace strin's in a
/ile FtraceIt*t)G 6e may include t&e /ollowin' statements into t&e Tcl
simulation scrit<
2 Ptcp trace t5se+no5
1 set trace5c( ?open HtraceIt*tH ,@
3 Ptcp attac( Ptrace5c(
Here* !ine 1 tells t&e A$entMTCP obBect Ptcp to trace its inst1ar
Ft5se+no5)G !ine 2 creates a trace /ile FtraceIt*t)G !ine 3 tells t&e tracer
?i)e)* Ptcp@ to send all its tracin' in/ormation to t&e Tcl /ile c&annel Ptrace5c(
attac&ed to t&e created traced /ile) T&ese t&ree lines in/orm NS2 to record
all t&e c&an'es in t&e inst1ar Ft5se+no5G associated wit& Ptcp in t&e /ile
FtraceIt*t)G 4/ter simulation* t&e /ollowin' trace /ile w&ose /ormat comlies
wit& Ci') 1:)2 is created<
III
=I0A/10 0 0 1 0 t5se+no5 2=
=I0AG/A 0 0 1 0 t5se+no5 2>
=I0B2>3 0 0 1 0 t5se+no5 G
=I0B2>3 0 0 1 0 t5se+no5 20
=I0/=A/ 0 0 1 0 t5se+no5 2=
III
1$.2.2 Tracea-le
.aria-le
7ariable tracin' is alicable to tracea'le 1ariables only) Traceable 1ariables are
t&e members o/ classes deri1ed /rom class TracedSar H namely classes
TracedInt and TracedDo!ble)
Traceable 1ariables can be used as i/ t&ey are re'ular int or do!ble
1ariables)
Howe1er* i/ tracin' is acti1ated* all t&eir c&an'es will be recorded in a 'i1en trace
/ile) T&e mec&anism to track c&an'es will be discussed later in t&e neAt
section)
Pro'ram 1:)2 s&ows eAamles o/ traceable and non9traceable 1ariables o/ class
TcpA$ent) T&e 1ariables Ft5se+no5G ?!ine 3@ and Fc,nd5G ?!ine :@ are
member o/ class TracedInt and TracedDo!ble* resecti1ely) T&ere/ore*
t&ey are traceable) T&e 1ariable Flast5ackG ?!ine 3@* on t&e ot&er &and* is o/
tye do!ble* and t&ere/ore not traceable)
328 1: Processin' an NS2 Simulation
Inst1ar
nextC
nameC
traced(arC
Program %/=2 EAamle o/ traceable 1ariables< t se+no and c,nd
MMUMnsMtcpMtcpI(
2 class TcpA$ent 9 p!blic A$ent 7
1 protected9
3 TracedInt t5se+no5;
= TracedDo!ble c,nd5;
> int last5ack5;
A 8
TclO/2ect
(and 'racer)
inst(arC
Inst1ar
nextC
nameC
traced(arC !
:::
Inst1ar
nextC !
nameC
traced(arC
Trace1ar
Trace1ar
traced(arC
(alC nextC
tracerC
(alC nextC
!
tracerC
'racer 'racer
channelC
Trace File
channelC
4ig= %/=* 4n arc&itecture o/ comonents in1ol1in' in 1ariable tracin'
1$.2." Coponents and Architect!re for .aria-le Tracing
7ariable tracin' consists o/ /i1e main comonents* w&ere t&eir relations&i is
s&own in Ci') 1:)3<
1) 4 TclObBect< 4n obBect t&at contains traceable 1ariables)
2) 4 traceable 1ariable< 4 1ariable t&at needs to be traced) Its tracin' caability
is de/ined in a CCC class TracedSar* w&ile its OTcl linka'e is de/ined in a
CCC class InstSar)
3) 4 tracer< 4n obBect t&at records c&an'es in t&e traceable 1ariable)
:) 4 Tcl c&annel< 4n obBect t&at attac&es to a tracer to a trace /ile)
3) 4 trace /ile< 4 /ile t&at records trace strin's)
%/=2=*=% Tc#,b1ects
Pro'ram 1:)3 s&ows t&e declaration o/ class TclObject) In 'eneral* a TclObBect
may consist o/ se1eral 1ariables w&ic& are bound to instvars in t&e OTcl
domain)
Program %/=* .eclaration o/ classes TclObject and IntsSar
MMUMtclclMtclclI(
2 class TclObject 7
1 p!blic9
3 IIII
= virt!al void trace &TracedSar
N
';
> protected9
A int traceSar&const c(ar
N
varName) TclObject
N
tracer';
B InstSar
N
instvar5;
/ TracedSar
N
tracedvar5
G 8
MMUMtclclMTclIcc
20 class InstSar 7
22 protected9
21 InstSar&const c(ar
N
name';
23 const c(ar
N
name5;
2= TracedSar
N
tracedvar5;
2> p!blic9
2A InstSar
N
ne*t5;
2B inline const c(ar
N
name&' 7 ret!rn name5; 8
2/ inline TracedSar
N
tracedvar&' 7 ret!rn tracedvar5; 8
2G inline void tracedvar&TracedSar
N
v' 7 tracedvar5 : v; 8
10 8;
T&ese 1ariables are modeled by class Inst7ar) T&ey to'et&er /orm a link list* and
let t&e TclObBect maintains only t&e ointer Finstvar5G ?!ine 2@ to t&e &ead o/
t&e link ed9list)
CCC class TracedSar ro1ides a traceable 1ariable wit& tracin' caability)
Crom Ci') 1:)3* eac& traceable 1ariable is associated wit& a TracedSar obBect)
T&ese TracedSar obBects /orm a link list* w&ose &ead ?tracedvar5 in !ine
"@ is maintained by t&e associated TclObBect) In summary* a TclObBect maintains
two ointers to two &eads o/ link lists w&ic& model OTcl linka'e ?instvar5@
and traceablility ?tracedvar5@)
%/=2=*=2 Traceab#e >ariab#es2 ,Tc#
+inkage
S&own in !ines 1,H2, o/ Pro'ram 1:)3* class InstSar binds a CCC class
1ariable to an OTcl inst1ar) Class InstSar &as t&ree main 1ariables< Fne*t5*G
Fname5*G and Ftracedvar5)G T&e ointer Fne*t5G ro1ides a suort to
create a link list) T&e 1ariable Fname5G contains t&e OTcl inst1ar name) T&e
ointer Ftracedvar5G oints to a TracedSar obBect* resonsible /or trackin'
c&an'es) Class Inst7ar &as t&ree main /unctions< name&'* tracedvar&'* and
tracedvar&v') T&ese /unctions are used to con/i'ure t&e class 1ariables
FnameG and Ftracedvar5G ?!ines 12H1#@)
32" 1: Processin' an NS2 Simulation
6e note &ere t&at not all OTcl inst1ars need to be traceable) 4s a result* not
all InstSar obBect &as it ointer Ftracedvar5G con/i'ured) Crom Ci') 1:)3*
t&e second InstSar obBect in t&e link list does not &a1e its ointer oint to a
TracedSar obBect* and t&ere/ore not traceable)
%/=2=*=* Traceab#e >ariab#es2 Tracing
$a&abi#ity
Class TracedSar ro1ides tracin' caability to traceable 1ariables) It o1erloads
basic oerators H includin' F4*G FJ*G F
N
*G and FM)G 6&en a TracedSar obBect
eA9 ecutes one o/ t&ese oerators* its o1erloadin' oerator eAecutes t&e basic
oeration and reorts t&e c&an'e in 1alue to a tracer)
NS2 imlements TracedSar obBects t&rou'& an abstract class TracedSar)
In Pro'ram 1:):* class TracedSar &as /our main 1ariables<
ne*t5 4 ointer to t&e neAt TracedSar obBect ?!ine 12@
name5 OTcl name o/ t&e inst1ar associated wit& t&is
TracedSar obBect ?!ine 13@
o,ner5 4 ointer to a TclObBect w&ic& contains t&is
TracedSar obBect ?!ine 18@
tracer5 4 ointer to t&e TclObBect resonsible /or keein' track
o/ t&e 1alue c&an'es ?!ine 12@
Class TracedSar &as one ure 1irtual /unction and siA re'ular /unctions)
T&e ure 1irtual /unction val!e&III' returns t&e 1alue o/ t&e TracedSar
obBect
1
?!ine 3@) T&e ot&er siA /unctions act as inter/ace /unctions to set and
retrie1e 1ariables o/ class TracedSar ?!ines 8H11@)
Class TracedInt declares an int 1ariable Fval5G ?!ine 2"@ to store its
current 1alue) It also de/ines a 1alue assi'nment /unction* assi$n&ne,val'*
in !ines 3,H32) T&is /unction stores t&e inut ar'ument Fne,valG in t&e class
1ariable Fval5G ?!ine 3:@* and asks t&e associated tracer to track t&e 1alue
c&an'e
?!ine 38@) +y /orcin' all 1alue assi'nment H includin' all o1erloadin' oerators H
to
use t&is /unction* class TracedInt ensures t&at all t&e c&an'es would be
reorted to t&e tracer)
%/=2=*=/ Tracers
4 tracer is a TclObBect resonsible /or recordin' c&an'es in 1alue o/ traceable
1ariables) Pro'ram 1:)3 s&ows t&e details o/ /unction trace&v') T&e imlemen9
tation o/ t&is /unction at t&e base class aims at error reortin') Crom !ines 1H:*
t&e error messa'es would be s&own on t&e screen* i/ t&e /unction trace&v' is
1
Since t&e base class TracedSar does not de/ine a 1ariable to store t&e 1alue* t&e /unction
val!e&III' must be declared as ure 1irtual)
1:)2 7ariable Tracin' 32#
Program %/=/ .eclaration o/ classes TracedSar and TracedInt* and t&e
/unction assi$n o/ class TracedInt
MMUMtclclMtracedvarI(
2 class TracedSar 7
1 p!blic9
3 TracedSar&';
= virt!al UTracedSar&' 78
> virt!al c(ar
N
val!e&c(ar
N
b!") int b!"len' : 0;
A inline const c(ar
N
name&' 7 ret!rn &name5'; 8
B inline void name&const c(ar
N
name' 7 name5 : name; 8
/ inline TclObject
N
o,ner&' 7 ret!rn o,ner5; 8
G inline void o,ner&TclObject
N
o' 7 o,ner5 : o; 8
20 inline TclObject
N
tracer&' 7 ret!rn tracer5; 8
22 inline void tracer&TclObject
N
o' 7 tracer5 : o; 8
21 TracedSar
N
ne*t5;
23 protected9
2= TracedSar&const c(ar
N
name';
2> const c(ar
N
name5;
2A TclObject
N
o,ner5;
2B TclObject
N
tracer5;
2/ 8;
2G class TracedInt 9 p!blic TracedSar 7
10 p!blic9
12 TracedInt&' 9 TracedSar&' 78
11 TracedInt&int v' 9 TracedSar&') val5&v' 78
13 virt!al UTracedInt&' 78
1= inline int operator44&' 7 assi$n&val5 4 2'; ret!rn
val5; 8
1> inline int operator:&int v' 7 assi$n&v'; ret!rn val5; 8
1A protected9
1B virt!al void assi$n&const int ne,val';
1/ int val5;
1G 8;
MMUMtclclMtracedvarIcc
30 void TracedInt99assi$n&int ne,val'
32 7
31 i" &val5 :: ne,val'
33 ret!rn;
3= val5 : ne,val;
3> i" &tracer5'
3A tracer5JKtrace&t(is';
3B 8
3", 1: Processin' an NS2 Simulation
in1oked) T&is imlementation /orces all t&e deri1ed classes to o1erride t&e
/unction trace&v') Ot&erwise* an error messa'e will be s&own on t&e screen at
runtime w&en t&e /unction trace&v' o/ class TclObject is eAecuted)
2
Program %/=0 T&e Cunctions trace o/ classes TclObject and TcpA$ent*
and t&e /unction traceSar o/ class TcpA$ent
MMUMtclclMTclIcc
2 void TclObject99trace&TracedSar
N
'
1 7
3 "print"&stderr) HSplitObject99trace called in
t(e base class o" EsTnH)name5';
= 8
MMUMnsMtcpMtcpIcc
> void TcpA$ent99trace&TracedSar
N
v'
A 7
B traceSar&v';
/ 8
G void TcpA$ent99traceSar&TracedSar
N
v'
20 7
22 Sc(ed!lerF s : Sc(ed!ler99instance&';
21 c(ar ,rk?TCP5W#V5SI\E@;
23 do!ble c!rtime : Fs Y sIclock&' 9 0;
2= i" &v :: Fc,nd5'
2> III
2A else i" &v :: Ft5rtt5'
2B III
2/ else
2G snprint"&,rk) TCP5W#V5SI\E)
HEJ/I>" EJ1d EJ1d EJ1d EJ1d Es EdTnH)
c!rtime) addr&') port&') daddr&') dport&')
vJKname&') int&
N
&&TracedInt
N
' v''';
10 &void'Tcl5Write&c(annel5) ,rk) J2';
12 8
Consider class TcpA$ent in !ines 3H21 o/ Pro'ram 1:)3* as an eAam9
le) Class TcpA$ent o1errides t&e /unction trace&v' by in1okin' its
own /unction traceSar&v' in !ine 2) T&e /unction traceSar&v'
creates and stores a trace strin' in a local 1ariable F,rkG ?!ine 1#@* and in1okes
/unction Tcl5Write&III' to write t&e strin' F,rkG to t&e trace c&annel
Fc(annel5G w&ose class is Tcl5C(annel ?!ine 2,@)
2
T&is is one o/ t&e common errors mentioned in Sect) 1:)1)1)
1:)2 7ariable Tracin' 3"1
%/=2=*=0 Trace $hanne#s
4 trace c&annel is a Tcl c&annel
3
used seci/ically to transort trace strin's to a
trace /ile) In most case* it is attac&ed to a trace /ile and sends all recei1ed trace
stin's to t&e attac&ed trace /ile) Cor eAamle* !ine 2, in Pro'ram 1:)3 simly
rints t&e trace strin' to t&e attac&ed trace /ile 1ia t&e statement
FTcl5Write&c(annel5) ,rk)J2')G
%/=2=*=6 Trace 4i#es an Trace
4ormat
4 trace /ile is a teAt /ile w&ic& collects all trace strin's t&rou'&out t&e simulation)
T&e /ormat o/ trace strin's is usually de/ined by t&e tracer under t&e /unction
trace&v' Cor eAamle* Ci') 1:)2 s&ows t&e /ormat de/ined by a tracer w&ose
class is TcpA$ent) T&e trace /ormat o/ class TcpA$ent is de/ined in its
/unction trace&v'* w&ic& in turn in1okes /unction TraceSar&v' to rint
out a trace strin' as s&own in !ine 1# o/ Pro'ram 1:)3)
1$.2.$ Tracing in Action9 An *1aple of Class Tc%Agent
T&is section demonstrates 1ia an eAamle &ow 1ariable tracin' actually takes lace
at runtime) Consider a CCC statement Ft5se+no544G in1oked /rom wit&in t&e
class TcpA$ent) T&e key rocedures are s&own in Ci') 1:):)
Cirst* t&e oerator F44G o/ a TracedSar obBect is o1erloaded by a
/unction operator44&' de/ined in !ine 2: o/ Pro'ram 1:):) T&e /unction
operator44&' eAecutes Fassi$n&val542'G to increment t&e 1alue
stored in t&e 1ariable Fval5G by 1 and record t&e c&an'e) Crom wit&in
t&e /unction assi$n&ne,val'* a TracedInt Ft5se+no5G eAecutes
Ftracer5JKtrace&t(is'G* w&ere Ftracer5G and Ft(isG are t&e
associated
tracer and t&e address o/ t&e TracedSar obBect* resecti1ely ?!ine 38 in
Pro'ram 1:):@) Since* in t&is case* t&e 1ariable Ftracer5G is a TcpA$ent
obBect* t&e /unction trace&v' in !ines 3H" o/ Pro'ram 1:)3 is in1oked* and a
trace strin' is rinted to t&e trace /ile accordin' to t&e /ormat seci/ied in !ine 1#
o/ Pro'ram 1:)3)
1$.2.+ Setting 0p .aria-le
Tracing
4s we &a1e seen* in Sect) 1:)2)1* t&at an acti1ation o/ 1ariable tracin' &as t&ree
maBor stes< ?1@ creatin' a trace /ile* ?2@ seci/yin' traceable 1ariables* and ?3@
attac&in' t&e trace /ile to a tracer) Since Ste 1 is discussed in Sect) 4)1)2* t&is
section /ocuses on t&e latter two stes)
3
See t&e details o/ Tcl c&annel in Sect) 4)1)2)
3"2 1: Processin' an NS2 Simulation
D
e
r
i
(
e
/n(o1e LtCse3noC88M
Trace1ar TclO/2ect
tracerC
(alC
trace('raced9arI) F
sho> error
H
o6erator88()
F assi4n((alC81
)E return (alCE
H
assi4n(ne>(al) F
(alC@ne>(alE
tracer$Qtrace(this)E
H
TcpA%ent
trace('raced9arI ) F
record the chan4e in
the 'raced9ar
tCse3noC
H
4ig= %/=/ T&e mec&anism o/ /unction operator44&' o/ class TcpA$ent
%/=2=0=% S&ecifying Traceab#e >ariab#es
4'ain* NS2 seci/ies an acti1e traceable 1ariable w&ose name is <var5nameK
1ia t&e /ollowin' OTcl statement<
Pobj trace <var5nameK ?Ptracer@
w&ere Pobj is a TclObBect* and t&e otional Ptracer is a tracer) I/ t&e
ar'ument
Ptracer is not resent* t&e TclObBect Pobj will be used as a tracer)
4s s&own in Pro'ram 1:)8* t&e OTcl command trace/III' in/orms a TclOb9
Bect ?i)e)* Pobj@ to trace its inst1ar <var5nameK) !ine 2 stores t&e t&ird inut
ar'ument ?i)e)* ar$v?3@@* i/ any* in a local 1ariable Ftracer)G T&en* !ine "
/eeds
t&e second inut ar'ument ?e)')* <var5nameK@ as well as t&e 1ariable FtracerG
to t&e /unction traceSar&III') I/ t&e caller did not ro1ide t&e t&ird inut
ar'ument* t&e ointer Ft(isG would instead be used ?!ine 3@)
T&e details o/ /unction traceSar&varName)tracer' are s&own in !ines
13H2: o/ Pro'ram 1:)8)
:
T&is /unction creates a connection /rom a TracedSar
obBect w&ose OTcl inst1ar name is FvarNameG to a ointer w&ic& oints to a
tracer obBect Ftracer)G !ines 13 and 18 locate an entry o/ t&e InstSar link
list w&ose 1ariable Fname5G matc&es wit& t&e strin' FvarName)G 6&en t&e
:
T&is /unction is di//erent /rom t&e /unction TraceSar&v' o/ class TcpA$ent in Pro'ram
1:)3* since t&e number and tyes o/ inut ar'uments are di//erent)
Program %/=6 OTcl command trace and t&e /unction TraceSar o/ class
TclObject
MMUMtclclMTclIcc
2 int TclObject99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 i" &ar$c K 1' 7
= i" &strcmp&ar$v?2@) HtraceH' :: 0' 7
> TclObject
N
tracer : t(is;
A i" &ar$c K 3'
B tracer : TclObject99look!p&ar$v?3@';
/ ret!rn traceSar&ar$v?1@) tracer';
G 8
20 8
22 ret!rn &TCL5E##O#';
21 8
23 int TclObject99traceSar&const c(ar
N
varName) TclObject
N
tracer'
2= 7
2> "or &InstSar
N
p : instvar5; p C: 0; p : pJKne*t5' 7
2A i" &strcmp&pJKname&') varName' :: 0' 7
2B i" &pJKtracedvar&'' 7
2/ pJKtracedvar&'JKtracer&tracer';
2G tracerJKtrace&pJKtracedvar&'';
10 ret!rn TCL5OV;
12 8
11 8
13 8
1= 8
entry is /ound* !ine 12 ensures t&at t&e matc&in' inst1ar contains a re/erence
to a TracedSar obBect) T&en* !ine 1" in/orms t&e matc&in' inst1ar to use t&e
inut tracer obBect
N
tracer as its tracer ?see !ine 11 in Pro'ram 1:):@) !ine 1#
in/orms t&e FtracerG ?i)e)* t&e inut ar'ument@ to create a trace strin' /or t&e
matc&ed inst1ar and write t&e strin' in t&e attac&ed traced /ile 1ia t&e trace c&annel*
Fc(annel5G ?see !ines 3H2, in Pro'ram 1:)3@)
%/=2=0=2 Attaching a Trace 4i#e to a
Tracer
NS2 attac&es a trace /ile w&ose associated Tcl /ile c&annel is P"c( to a tracer
Ptracer t&rou'& t&e /ollowin' OTcl
statement<
Ptracer attac( P"c(
T&e tracin' c&annel 1ariable Fc(annel5G w&ose class is Tcl5C(annel is
de/ined in class A$ent ?!ine : in Pro'ram 1:)2@) Curt&ermore* t&e OTcl
command attac( is de/ined in t&e class TcpA$ent w&ose details are s&own in
!ines 1,H1#
3": 1: Processin' an NS2 Simulation
Program %/=5 .eclaration o/ class A$ent and its OTcl command attac(
MMUMnsMcommonMa$entI(
2 class A$ent 9 p!blic Connector 7
1 III
3 protected9
= Tcl5C(annel c(annel5;
> III
A 8
MMUMnsMtcpMtcpIcc
B int TcpA$ent99command&int ar$c) const c(ar
N
const
N
ar$v'
/ 7
G III
20 i" &strcmp&ar$v?2@) Hattac(H' :: 0' 7
22 int mode;
21 const c(ar
N
id : ar$v?1@;
23 c(annel5 : Tcl5-etC(annel&tclIinterp&') &c(ar
N
'id)
Fmode';
2= i" &c(annel5 :: 0' 7
2> tclIres!lt"&Htrace9 canZt attac( Es "or
,ritin$H) id';
2A ret!rn &TCL5E##O#';
2B 8
2/ ret!rn &TCL5OV';
2G 8
10 III
12 8
in Pro'ram 1:)2) Here* !ine 12 con1erts t&e inut /ile name to a strin' FidG) !ine
13 retrie1es a Tcl /ile c&annel corresondin' to FidG* and stores it in t&e 1ariable
Fc(annel5G) 4/ter t&is oint* a connection to a trace /ile is created /rom wit&in a
tracer* and t&e tracer is able to write trace strin's to t&e attac&ed trace /ile t&rou'&
its 1ariable Fc(annel5G)
%/=* Packet Tracing
Packet tracin' records t&e details w&en ackets ass t&rou'& network c&eckoints*
w&ere Trace obBects are installed) Packet tracin' can be acti1ated usin' t&e
/ollowin' OTcl statement<
Pns traceJall P"ile
w&ere Pns and P"ile are t&e Sim!lator obBect and a Tcl /ile c&annel*
resecti1ely)
1:)3 Packet Tracin' 3"3
E%ample /*$* Consider EAamle #)1) Insert t&e /ollowin' OTcl statements a/ter
!ine 2 in EAamle #)1<
set " ?open o!tItr ,@
Pns traceJall P"
w&ere t&e uer line creates a Tcl /ile c&annel attac&ed to a /ile Fo!tItrG and
stores it in a 1ariable F")G T&e lower line in/orms NS2 to acti1ate t&e acket
tracin' mec&anism and to record trace strin's to t&e trace /ile Fo!tItrG 1ia t&e
Tcl /ile c&annel P")
4/ter addin' t&e /ollowin' statements at t&e end o/ t&e Tcl scritin' /ile and
runnin' t&e simulation<
Pns at 0I0 HPcbr startH
Pns at 20I0 HPns (altH
Pns r!n
t&e trace result will be stored in t&e /ile Fo!tItr)G T&e /ollowin' lines are a art
o/ t&e /ile Fo!tItrG<
MMo!tItr
4 0 0 1 cbr 120 JJJJJJJ 0 0I0 1I0 0 0
J 0 0 1 cbr 120 JJJJJJJ 0 0I0 1I0 0 0
r 0I00133A 0 1 cbr 120 JJJJJJJ 0 0I0 1I0 0 0
4 0I003B> 0 1 cbr 120 JJJJJJJ 0 0I0 1I0 2 2
J 0I003B> 0 1 cbr 120 JJJJJJJ 0 0I0 1I0 2 2
III

In t&e /ollowin'* Sects) 1:)3)1 and 1:)3)2 discuss t&e OTcl con/i'uration
met&od and CCC internal mec&anism imlementation* resecti1ely* o/ acket
tracin') Sections 1:)3)3 discusses t&e details o/ t&e acket tracin' &eler class
.aseTrace) 7arious tyes o/ acket tracin' obBects are resented in Sect)
1:)3):) Cinally* t&e acket trace /ormats are s&own in Sect) 1:)3)3)
1$.".1 OTcl Config!ration Interfaces
T&is section demonstrates &ow NS2 sets u acket tracin' usin' t&e instroc
traceJall/') Cor bre1ity* t&e /ollowin' discussion will be based mainly on a
simleA9link wit& a drotail Dueue only) T&e readers are encoura'ed to look
t&rou'& t&e NS2 ro'ram and /ind out more about acket tracin') 4s s&own in
Ci') 1:)3* acket tracin' can be set u in two main stes<
3"8 1: Processin' an NS2 Simulation
4ig= %/=0 T&e acket tracin'
con/i'uration rocess o/ a
SimpleLink obBect
STEP 3* Packet Tracin% Acti,ation
Tns trace$all Tfile
Class Simulator
4ns trace+all -45ile.
set tracea,ll.ileC Tfile
STEP 2* TclO/2ect Creation
Tns sim6lex$lin1 Tn1 Tn2 Ttrace,ll.ileC
/n(o1ed only
>hen
trace,ll.ileC
is non$em6ty
Class Simulator
Instproc simple0+link -n3 n2 /' ela6 7t6pe.
Tself trace$3ueue Tn1 Tn2 Ttrace,ll.ileC
Instproc trace+7ueue -n3 n2 5ile.
Tlin1C(UTn1 idV;UTn2 idV) trace Tself Tfile
Class SimpleLink
Instproc trace -ns 5.
set en3'C UTns create$trace +n3ue Tfile Tfrom)odeC Tto)odeCV
:::
R6ac1et tracin4 ob7ect confi4urationQ
Program %/=7 T&e instroc traceJall o/ class Sim!lator
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc traceJall "ile 7
1 Psel" instvar traceAllQile5
3 set traceAllQile5 P"ile
= 8
Ste& %2 Packet Tracing Activation The
'nst&roc trace#all/file' of $#ass &imulator
4'ain* acket tracin' can be acti1ated usin' t&e instroc traceJall/"ile'
o/ class Sim!lator w&ose details are s&own in Pro'ram 1:)") T&is instroc
stores t&e Tcl /ile c&annel F"ileG in a /la' inst1ar FtraceAllQile5G
?!ine 2@* w&ic& indicates t&at acket tracin' is enabled) 6&en a TclObBect is
created* acket tracin' obBects are inserted i/ t&e inst1ar FtraceAllQile5G is
nonemty)
Program %/=8 T&e instrocs simple*Jlink and traceJ+!e!e o/ class
Sim!lator
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc simple*Jlink 7 n2 n1 b, delay +type ar$s 8
7
1 Psel" instvar link5
3 set sid ?Pn2 id@
= set did ?Pn1 id@
> III
A set + ?ne, !e!eMP+type@
B set link5&Psid9Pdid' ?ne, SimpleLink Pn2 Pn1 Pb,
Pdelay P+@
/ III
G set trace ?Psel" $etJnsJtraceall@
20 i" 7Ptrace C: HH8 7
22 Psel" traceJ+!e!e Pn2 Pn1 Ptrace
21 8
23 8
2= Sim!lator instproc traceJ+!e!e 7 n2 n1 7"ile HH8 8 7
2> Psel" instvar link5 traceAllQile5
2A Plink5&?Pn2 id@9?Pn1 id@' trace Psel" P"ile
2B 8
Ste& 22 Tc#,b1ect $reation
Ste& 2=%2 The inst&roc sim%le,# link/444' of $#ass
Simu#ator
T&e instroc simple*Jlink/III' o/ class Sim!lator creates a link between
two nodes) Pro'ram 1:)# s&ows a art o/ t&e instroc simple*Jlink/III'
related to acket tracin') !ines 8 and 2 create a SimpleLink obBect connectin'
node n2 to node n1) !ine # stores t&e inst1ar traceAllQile5 in a local
1ariable trace* and !ines 1,H12 eAecute FPsel" traceJ+!e!e/n2 n1
trace'G* i/ acket tracin' was acti1ated earlier)
Ste& 2=22 The inst&roc trace#-ueue/n3 n2 file' of $#ass Simu#ator
!ines 1:H12 in Pro'ram 1:)# s&ow t&e details o/ /unction traceJ+!e!e/n2
n1 "ile') 4'ain* class Sim!lator &as an inst1ar Flink5GH an associati1e
array t&at contains t&e instances o/ all links in a simulation) T&e indeA o/ t&e
inst1ar Flink5G is o/ /ormat Fsid9did*G w&ere FsidG and FdidG are I.s o/
t&e be'innin' and endin' nodes o/ t&e instance FPlink5?sid9did@)G
T&e instroc traceJ+!e!e/n2 n1 "ile' in1okes t&e instroc trace/ns
"ile' associated wit& t&e SimpleLink obBect link5&?Pn2 id@9?Pn1
id@' ?see !ine 18@* to create and con/i'ure acket tracin' comonents o/ t&e
SimpleLink obBect)
3"" 1: Processin' an NS2 Simulation
Program %/=%: T&e instroc trace o/ class SimpleLink and t&e instroc
createJtrace o/ class Sim!lator
MMUMnsMtclMlibMnsJlinkItcl
2 SimpleLink instproc trace 7 ns " 7op HH8 8 7
1 Psel" instvar en+T5 de+T5 drpT5 +!e!e5 link5 "romNode5
toNode5
3 Psel" instvar rcvT5 ttl5 trace5
= Psel" instvar drop(ead5
> set trace5 P"
A set en+T5 ?Pns createJtrace En+!e P" P"romNode5
PtoNode5 Pop@
B set de+T5 ?Pns createJtrace De+!e P" P"romNode5
PtoNode5 Pop@
/ set drpT5 ?Pns createJtrace Drop P" P"romNode5
PtoNode5 Pop@
G set rcvT5 ?Pns createJtrace #ecv P" P"romNode5
PtoNode5 Pop@
20 Psel" instvar drpT5 drop(ead5
22 set n*t ?Pdrop(ead5 tar$et@
21 Pdrop(ead5 tar$et PdrpT5
23 PdrpT5 tar$et Pn*t
2= P+!e!e5 dropJtar$et Pdrop(ead5
2> Pde+T5 tar$et ?P+!e!e5 tar$et@
2A P+!e!e5 tar$et Pde+T5
2B Psel" addJtoJ(ead Pen+T5
2/ PrcvT5 tar$et ?Pttl5 tar$et@
2G Pttl5 tar$et PrcvT5
10 8
MMUMnsMtclMlibMnsJlibItcl
12 Sim!lator instproc createJtrace 7 type "ile src dst
7op HH8 8 7
11 Psel" instvar alltrace5
13 set p ?ne, TraceMPtype@
1= Pp set src5 ?Psrc id@
1> Pp set dst5 ?Pdst id@
1A lappend alltrace5 Pp
1B i" 7P"ile C: HH8 7
1/ Pp attac( P"ile
1G 8
30 ret!rn Pp
32 8
Ste& 2=*2 The inst&roc trace/ns f' of $#ass Sim&#e+ink
4s s&own in Pro'ram 1:)1,* t&e instroc trace/ns "' o/ class SimpleLink
takes two inut ar'uments< t&e Simulator FnsG and a Tcl /ile c&annel F")G !ine 3
stores t&e inut Tcl /ile c&annel P" in t&e inst1ar Ftrace5)G !ines 8H# create
acket tracin' obBects Fen+T5*G Fde+T5*G FdrpT5*G and FrcvT5*G usin' t&e
instroc createJtrace/III' associated wit& t&e inut Sim!lator obBect
Fns)G !ines
11H1# con/i'ure t&e created acket tracin' obBects as indicated in Ci')
2)1)
1:)3 Packet Tracin' 3"#
Ste& 2=/2 The inst&roc create#trace/t$%e file src dst' of $#ass
Simu#ator
Crom !ines 21H31 in Pro'ram 1:)1,* t&e instroc createJtrace/type "ile
src dst' creates and con/i'ures a acket tracin' obBect w&ose tye is Ftype)G
!ine 23 /irst creates a acket tracin' obBect wit& tye seci/ied in Ftype)G !ines
2: and 23 con/i'ure t&e member 1ariables Fsrc5G and Fdst5*G resecti1ely* o/
t&e created acket tracin' obBect Fp)G !ine 28 stores t&e created acket tracin'
obBect in an inst1ar Falltrace5G o/ t&e Simulator) !ines 22H2# attac& a Tcl /ile
c&annel F"ileG to t&e created acket tracin' obBect) Cinally* !ine 3, returns t&e
created acket tracin' obBect to t&e caller)
1$.".2 CCC Main Pac'et Tracing Class Trace
In CCC* acket tracin' obBects are imlemented usin' class Trace declared in
Pro'ram 1:)11* w&ic& is bound to an OTcl class wit& t&e same name
?see !ines 13H23@) Crom !ine 1* class Trace deri1es /rom class Connector
and can be inserted between two NsObBects to record t&e details o/ tra1ersin'
ackets) 4s a connector* a acket tracin' obBect recei1es a acket F
N
pG by &a1in'
its ustream obBect in1oke its /unction recv&p)(') 0on recei1in' a acket*
it records t&e details o/ t&e acket in a trace /ile and /orwards t&e acket to its
downstream obBect)
%/=*=2=% Main $CC >ariab#e of $#ass Trace
Class Trace consists o/ /our main 1ariables< Fsrc5*G Fdst5*G Ftype5*G
and Fpt5)G T&e 1ariables Fsrc5G ?!ine 3@ and Fdst5G ?!ine :@ store addresses
o/ t&e ustream and downstream nodes* resecti1ely* o/ t&is Trace obBect) T&e
1ariable Ftype5G in !ine 1, indicates t&e tye o/ t&e Trace obBect) .esite its
int tye* t&e true meanin' o/ t&is 1ariable is c(ar eDui1alent) Cor eAamle*
t&e tyes o/ obBects w&ic& trace acket enDuin' and deDuin' are F4G and FJ*G
w&ic& corresond to decimal 1alues o/ :3 and :3* resecti1ely) Cinally* t&e
ointer Fpt5G in !ine # is a re/erence to a .aseTrace obBect* w&ic& ro1ides
t&e basic /unctionalities /or acket tracin') 6e s&all discuss t&e details o/
class .aseTrace later in Sect) 1:)3)3)
%/=*=2=2 Main $CC 4unctions of $#ass Trace
Class Trace &as t&ree /ollowin' main /unctions< t&e constructor* /unction
recv&p)('* and /unction "ormat&tt)s)d)p')
3#, 1: Processin' an NS2 Simulation
Program %/=%% .eclaration o/ class Trace and t&eir constructors
MMUMnsMtraceMtraceI(
2 class Trace 9 p!blic Connector 7
1 protected9
3 nsaddr5t src5;
= nsaddr5t dst5;
> virt!al void "ormat&int tt) int s) int d) Packet
N
p';
A p!blic9
B Trace&int type';
/ UTrace&';
G .aseTrace
N
pt5;
20 int type5;
22 int command&int ar$c) const c(ar
N
const
N
ar$v';
21 static int $et5se+no&Packet
N
p';
23 void recv&Packet
N
p) Handler
N
';
2= 8;
MMUMnsMtraceMtraceIcc
2> class TraceClass 9 p!blic TclClass 7
2A p!blic9
2B TraceClass&' 9 TclClass&HTraceH' 7 8
2/ TclObject
N
create&int ar$c) const c(ar
N
const
N
ar$v' 7
2G i" &ar$c K: >'
10 ret!rn &ne, Trace&
N
ar$v?=@'';
12 ret!rn 0;
11 8
13 8 trace5class;
1= Trace99Trace&int type' 9 Connector&') pt5&0') type5&type'
1> 7
1A bind&Hsrc5H) &int
N
'Fsrc5';
1B bind&Hdst5H) &int
N
'Fdst5';
1/ pt5 : ne, .aseTrace;
1G 8
MMUMnsMtclMlibMnsJtraceItcl
30 Trace instproc init type 7
32 Psel" ne*t Ptype
31 Psel" instvar type5
33 set type5 Ptype
3= 8
The Constructors
!ines 2:H2# and 3,H3: s&ow t&e constructors o/ a CCC class Trace and t&e
bound OTcl class Trace* resecti1ely) T&e OTcl constructor simly stores t&e
inut ar'ument in its inst1ar Ftype5G ?!ine 33@) Similarly* t&e CCC constructor
stores t&e inut ar'ument in 1ariable Ftype5G ?!ine 2:@) It also binds 1ariables
Fsrc5G and Fdst5G to t&e inst1ars wit& t&e same name ?!ines 28 and 22@ and
creates a new .aseTrace obBect F
N
pt5G ?!ine 2"@)
1:)3 Packet Tracin' 3#1
Program %/=%2 Cunction recv o/ class
Trace
MMUMnsMtraceMtraceIcc
2 void Trace99recv&Packet
N
p) Handler
N
('
1 7
3 "ormat&type5) src5) dst5) p';
= pt5JKd!mp&';
> i" &tar$et5 :: 0'
A Packet99"ree&p';
B else
/ send&p) (';
G 8
&unction recv&p)('
Cunction recv&p)(' is t&e main acket recetion /unction w&ose details are
s&own in Pro'ram 1:)12) !ine 3 in1okes /unction "ormat&type5)src5)
dst5)p' to store t&e details o/ t&e acket F
N
pG in t&e internal 1ariable F,rk5G
o/ t&e associated .aseTrace obBect F
N
pt5)G !ine : eAecutes Fpt5J
Kd!mp&'G w&ic& tells t&e attac&ed .aseTrace obBect to rint acket details to
its attac&ed trace /ile) I/ t&e Trace obBect contains a 1alid downstream obBect*
Ftar$et5*G !ine " will /orward t&e acket F
N
pG to t&e downstream obBect)
Ot&erwise* !ine 8 will destroy t&e acket F
N
p)G
&unction &ormat&tt)s)d)p'
S&own in Pro'rams 1:)13 and 1:)1:* /unction "ormat&tt)s)d)p' stores t&e
acket details in t&e internal 1ariable F,rk5G o/ t&e associated .aseTrace
obBect F
N
pt5G ?!ines 28H:3@) T&is /unction takes* as inut ar'uments* t&e acket
tracin' tye Ftt*G a source node I. Fs*G a destination node I. Fd*G and a ointer
to an incomin' acket F
N
p)G !ine 2 stores t&e acket tye in a local 1ariable
Fname)G !ines #H21 create a /la' strin' and store it in a local 1ariable F"la$)G
!ines 22H23 retrie1e addresses and orts o/ t&e source and t&e destination nodes)
Cinally* !ines
28H:3 rint out a acket trace strin' to 1ariable Fpt5JK,rk5)G
3
T&e acket trace
/ormat will be discussed in 'reater detail in Sect) 1:)3)3)
%/=*=2=* Main ,Tc# $ommans of a Packet Tracing
,b1ect
T&ere are t&ree OTcl main commands associated wit& t&e OTcl class Trace<
"l!s(/'* detac(/'* and attac(/"ile') In Pro'ram 1:)13* t&e OTcl command
3
4s we s&all see in Sect) 1:)3)3* t&e /unction b!""er&' o/ class .aseTrace simly returns
t&e 1ariable F,rk )G
3#2 1: Processin' an NS2 Simulation
Program %/=%* Cunction "ormat o/ class Trace
MMUMnsMtraceMtraceIcc
2 void Trace99"ormat&int tt) int s) int d) Packet
N
p'
1 7
3 (dr5cmn
N
t( : (dr5cmn99access&p';
= (dr5ip
N
ip( : (dr5ip99access&p';
> (dr5tcp
N
tcp( : (dr5tcp99access&p';
A packet5t t : t(JKptype&';
B const
N
name : packet5in"oIname&t';
/ int se+no : $et5se+no&p';
G c(ar "la$s?ND%QLA-S42@;
20 "or &int i : 0; i < ND%QLA-S; i44'
22 "la$s?i@ : ZJZ;
21 "la$s?ND%QLA-S@ : 0;
23 (dr5"la$s
N
(" : (dr5"la$s99access&p';
2= "la$s?0@ : ("JKecn5 Y ZCZ 9 ZJZ;
2> "la$s?2@ : ("JKpri5 Y ZPZ 9 ZJZ;
2A "la$s?1@ : ZJZ;
2B "la$s?3@ : ("JKcon$5action5 Y ZAZ 9 ZJZ;
2/ "la$s?=@ : ("JKecn5to5ec(o5 Y ZEZ 9 ZJZ;
2G "la$s?>@ : ("JK"s5 Y ZQZ 9 ZJZ;
10 "la$s?A@ : ("JKecn5capable5 Y ZNZ 9 ZJZ;
12 "la$s?B@ : 0;
11 c(ar
N
src5nodeaddr : Address99instance&'I
print5nodeaddr&ip(JKsaddr&'';
13 c(ar
N
src5portaddr : Address99instance&'I
print5portaddr&ip(JKsport&'';
1= c(ar
N
dst5nodeaddr : Address99instance&'I
print5nodeaddr&ip(JKdaddr&'';
1> c(ar
N
dst5portaddr : Address99instance&'I
print5portaddr&ip(JKdport&'';
III
"l!s(/' ?!ines 3H1,@ clears t&e bu//er o/ t&e attac&ed Tcl c&annel by in1okin'
pt5JK"l!s(&c('* w&ere Fc(G is t&e attac&ed Tcl c&annel) T&e OTcl command
detac(/' does not clear t&e c&annel bu//er* but simly sets t&e ointer w&ic&
oints to t&e attac&ed Tcl c&annel to Null ?see !ine 12@) Cinally* t&e OTcl
command attac(/"ile' sets t&e inut F"ileG as t&e Tcl /ile c&annel ?!ines 1#
and 2,@)
1$."." CCC 7elper Class !aseTrace
One o/ t&e main 1ariables o/ class Trace* Fpt5*G is a ointer to a .aseTrace
obBect) Class .aseTrace acts as an inter/ace /rom a acket tracin' obBect to a
Tcl c&annel) S&own in Pro'ram 1:)18* class .aseTrace is bound to an OTcl
class wit& t&e same name) It &as two main 1ariables< Fc(annel5G ?!ine 1:@ and
F,rk5G ?!ine 13@) 6&ile Fc(annel5G models a Tcl c&annel* F,rk5G is a
bu//er w&ic&
1:)3 Packet Tracin' 3#3
Program %/=%/ Cunction "ormat o/ class Trace ?cont)@
MMUMnsMtraceMtraceIcc
III
1A sprint"&pt5JKb!""er&')
1B HEc HTI%E5QO#%ATH Ed Ed Es Ed Es Ed EsIEs EsIEs
1/ tt)
1G pt5JKro!nd&Sc(ed!ler99instance&'Iclock&'')
30 s)
32 d)
31 name)
33 t(JKsi6e&')
3= "la$s)
3> ip(JK"lo,id&')
3A src5nodeaddr)
3B src5portaddr)
3/ dst5nodeaddr)
3G dst5portaddr)
=0 se+no)
=2 t(JK!id&')
=1 tcp(JKackno&')
=3 tcp(JK"la$s&')
== tcp(JK(len&')
=> tcp(JKsa5len$t(&' ';
=A delete ?@ src5nodeaddr;
=B delete ?@ src5portaddr;
=/ delete ?@ dst5nodeaddr;
=G delete ?@ dst5portaddr;
>0 8
stores a trace strin') 4t t&e construction* t&e Tcl c&annel Fc(annel5G is set to
Null ?!ine 2:@* and t&e trace strin' F,rk5G is allocated wit& memory sace w&ic&
can &old uto 1,28 c&aracters ?!ine 28@)
T&e key /unctions o/ class .aseTrace include c(annel&III'*
b!""er&'* "l!s(&c(annel'* and d!mp&') T&e oerations o/ t&e /irst t&ree
/unctions are /airly strai'&t/orward and are omitted /or bre1ity) T&e /unction
d!mp&' ?!ines 2"H
32 o/ Pro'ram 1:)18@ is resonsible /or dumin' a trace strin' stored in t&e
1ariable F,rk5G to t&e Tcl c&annel) Here* !ine 3, retrie1es and stores t&e len't&
o/ t&e strin' F,rk5G in a local 1ariable Fn)G !ine 32 attac&es an end9o/9line
c&aracter to F,rk5)G !ine 33 attac&es Jero to F,rk5G indicatin' t&e end o/ t&e
strin') !ine 3: writes F,rk5G to t&e Tcl c&annel Fc(annel5G usin' a /unction
Tcl5Write&III')
In common wit& class Trace* class .aseTrace &as t&ree main OTcl
commands< "l!s(/'* detac(/'* and attac(/"ile') T&ese t&ree commands
er/orm t&e same action as t&ose in class Trace) 6e will omit t&e details o/ t&ese
t&ree OTcl commands /or bre1ity)
3#: 1: Processin' an NS2 Simulation
Program %/=%0 Cunction command o/ class
Trace
MMUMnsMtraceMtraceIcc
2 int Trace99command&int ar$c) const c(ar
N
const
N
ar$v'
1 7
3 TclF tcl : Tcl99instance&';
= i" &ar$c :: 1' 7
> i" &strcmp&ar$v?2@) H"l!s(H' :: 0' 7
A Tcl5C(annel c( : pt5JKc(annel&';
B i" &c( C: 0'
/ pt5JK"l!s(&c(';
G ret!rn &TCL5OV';
20 8
22 i" &strcmp&ar$v?2@) Hdetac(H' :: 0' 7
21 pt5JKc(annel&0' ;
23 ret!rn &TCL5OV';
2= 8
2> 8 else i" &ar$c :: 3' 7
2A i" &strcmp&ar$v?2@) Hattac(H' :: 0' 7
2B int mode;
2/ const c(ar
N
id : ar$v?1@;
2G Tcl5C(annel c( : Tcl5-etC(annel&tclIinterp&')
&c(ar
N
'id)Fmode';
10 pt5JKc(annel&c(';
12 i" &pt5JKc(annel&' :: 0' 7
11 tclIres!lt"&Htrace9 canZt attac( Es
"or ,ritin$H) id';
13 ret!rn &TCL5E##O#';
1= 8
1> ret!rn &TCL5OV';
1A 8
1B 8
1/ ret!rn &Connector99command&ar$c) ar$v'';
1G 8
1$.".$ .ario!s Types of Pac'et Tracing
O-8ects
NS2 uses di//erent tyes o/ acket tracin' obBects to trace ackets at di//erent
laces) Cor eAamle* a TraceMEn+!e obBect is laced immediately be/ore a
Dueue to trace ackets w&ic& enter t&e Dueue) T&e tye ?i)e)* 1ariable Ftype5G@
o/ a TraceMEn+!e obBect is F4*G w&ic& is eDui1alent to :3 in decimal) 6&en a
acket asses t&rou'& a TraceMEn+!e obBect* a line be'innin' wit& F4G is
written onto t&e Tcl C&annel)
4mon' all built9in OTcl acket tracin' classes* t&e most common ones in9
clude<
TraceMEn+!e ?F4G@< Trace acket arri1al ?usually at a
Dueue@
TraceMDe+!e ?FJG@< Trace acket dearture ?usually at a
Dueue@
1:)3 Packet Tracin' 3#3
Program %/=%6 .eclaration* an OTcl bindin' class* t&e constructor o/ class
.aseTrace* and t&e /unction d!mp&' o/ class .aseTrace
MMUMnsMtraceMbasetraceI(
2 class .aseTrace 9 p!blic TclObject 7
1 p!blic9
3 .aseTrace&';
= U.aseTrace&';
> virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
A virt!al void d!mp&';
B inline Tcl5C(annel c(annel&' 7 ret!rn c(annel5; 8
/ inline void c(annel&Tcl5C(annel c(' 7c(annel5 : c(; 8
G inline c(ar
N
b!""er&' 7 ret!rn ,rk5 ; 8
20 void "l!s(&Tcl5C(annel c(annel' 7 Tcl5Ql!s(&c(annel'; 8
22 Ode"ine P#ECISION 2I0E4A
21 Ode"ine TI%E5QO#%AT HEI2>$H
23 protected9
2= Tcl5C(annel c(annel5;
2> c(ar
N
,rk5;
2A 8;
MMUMnsMtraceMbasetraceIcc
2B class .aseTraceClass 9 p!blic TclClass 7
2/ p!blic9
2G .aseTraceClass&' 9 TclClass&H.aseTraceH' 7 8
10 TclObject
N
create&int ar$c) const c(ar
N
const
N
ar$v' 7
12 ret!rn &ne, .aseTrace&'';
11 8
13 8 basetrace5class;
1= .aseTrace99.aseTrace&' 9 c(annel5&0')
1> 7
1A ,rk5 : ne, c(ar?201A@;
1B 8
1/ void .aseTrace99d!mp&'
1G 7
30 int n : strlen&,rk5';
32 i" &&n K 0' FF &c(annel5 C: 0'' 7
31 ,rk5?n@ : ZTnZ;
33 ,rk5?n 4 2@ : 0;
3= &void'Tcl5Write&c(annel5) ,rk5) n 4 2';
3> ,rk5?n@ : 0;
3A 8
3B 8
TraceMDrop ?FdG@< Trace acket dro ?deli1ered to a dro9tar'et@
TraceM#ecv ?FrG@< Trace acket recetion at a certain node
w&ere t&e c&aracters in t&e arent&eses are attributed to t&e 1ariable Ftype5G
de/ined in t&e CCC class Trace)
3#8 1: Processin' an NS2 Simulation
Program %/=%5 Constructors o/ classes TraceMEn+!e and TraceMDe+!e*
and t& e C CC b ind in' c la s s /or t& e O Tcl cla s s TraceMDe+!e
MMUMnsMtclMlibMnsJtraceItcl
2 Class TraceMEn+!e Js!perclass Trace
1 TraceMEn+!e instproc init 78 7
3 Psel" ne*t H4H
= 8
> TraceMDe+!e instproc init 78 7
A Psel" ne*t HJH
B 8
MMUMnsMtraceMtraceI(
/ static class De+!eTraceClass 9 p!blic TclClass 7
G p!blic9
20 De+!eTraceClass&' 9 TclClass&HTraceMDe+!eH' 7 8
22 TclObject
N
create&int ar$s) const c(ar
N
const
N
ar$v' 7
21 i" &ar$s K: >'
23 ret!rn &ne, De+!eTrace&
N
ar$v?=@'';
2= ret!rn NDLL;
2> 8
2A 8 de+!etrace5class;
4mon' t&ese /our classes* only class TraceMDe+!e &as an imlementation
in t&e CCC domain) T&e main di//erence amon' t&e abo1e /our acket tracin'
obBects lies in t&eir constructors) 4s s&own in Pro'ram 1:)12* t&e OTcl class
TraceMEn+!e deri1es /rom an OTcl class Trace ?!ine 1@* w&ile t&e OTcl
class TraceMDe+!e is maed to t&e CCC class De+!eTrace ?!ines "H18@)
!ines
3 and 8 s&ow t&at t&e classes TraceMEn+!e and TraceMDe+!e are
constructed
wit& c&aracters F4G and FJ*G resecti1ely) Crom !ine 2: o/ Pro'ram 1:)11* t&ese
c&aracters are stored in its CCC 1ariable Ftype5G de/ined at t&e base class
Trace)
4s an eAamle* consider t&e rocess o/ creatin' a TraceMEn+!e obBect in
Ci') 1:)8) T&e rocess starts w&en a statement Fne, TraceMEn+!eG is eAecuted
?e)')* !ine 23 in Pro'ram 1:)1,@) Crom wit&in t&e OTcl constructor* t&e tye F4G
is reeatedly /ed to t&e constructor u t&e &ierarc&y by t&e statement FPsel"
ne*t H4H)G 6&en class SplitObject is reac&ed* t&e interreter eAecutes
FcreateJs(ado, H4H*G w&ic& in turn in1okes t&e /unction create&' o/
class TraceClass in t&e CCC domain) Crom !ine 2: in Pro'ram 1:)11* t&e
constructor o/ class Trace is in1oked* and t&e tye F4G is /ed as an inut
ar'ument)
Since t&e constructor takes an inte'er as an inut ar'ument* t&e 4SCII code F4G
is con1erted into a decimal 1alue F:3)G Cinally* t&e constructor stores t&e inut
ar'ument ?i)e)* F:3G in t&is case@ in its 1ariable Ftype5)G
1:)3 Packet Tracin' 3#2
4ig= %/=6 Construction
o/ a TraceMEn+!e obBect
1$.".+ 5orat of Trace Strings for Pac'et
Tracing
T&e /inal roduct o/ acket tracin' is usually a trace /ile) Eac& line in a trace
/ile H usually called a trace record H /ollows a rede/ined acket trace /ormat)
T&is section discusses t&ree main tyes o/ acket trace /ormat) Cirst* normal
acket trace /ormat is associated wit& re'ular wired network simulation) Second*
wireless acket trace /ormat is t&e de/ault /ormat w&en runnin' a wireless network
simulation) T&is /ormat is sometimes re/erred to as old wireless trace /ormat or
C5E wireless trace format) Cinally* t&e new wireless trace /ormat is t&e most
comre&ensi1e built9in acket tracin' in NS2) 4mon' t&ese /ormats* t&e /ormer
two /ollow rede/ined structures) T&e interretation o/ t&ese traced /ormats is
mainly based on t&e ositions o/ strin's on a trace record) T&e last tye* on t&e
ot&er &and* is structureless) T&e interretation is based on t&e label located be/ore
a trace strin')
%/=*=0=% Norma# Packet Trace
4ormat
Packet trace /ormat is de/ined in t&e /unction "ormat&III' o/ class Trace
?Pro'rams 1:)13 and 1:)1:@) In a normal case* eac& trace record ?i)e)* eac& line in
a trace /ile@ /ollows t&e /ormat s&own in Ci') 1:)2* w&ere eac& boA and t&e sace
between two boAes reresent a trace strin' and a sace* resecti1ely* in a trace
record) 4 trace record /or t&e normal trace /ormat contains 12 /ields* eac& o/
w&ic& is indicated by t&e column number below eac& boA)
3#" 1: Processin' an NS2 Simulation
+(ent
'y6e 'ime
Sendin4
)ode
=ecei(in4
)ode
Payload
'y6e
Pac1et
Si<e
.la4s
.lo>
/D
Source
,ddress
Destination
,ddress
Se3uence
)umber
Pac1et
?ni3ue /D
1 2 3 4 % & A B 1! 11 12
4ig= %/=5 Packet trace /ormat
E1ent Tye< T&e tye ?i)e)* 1ariable Ftype5G@ o/ t&e Trace obBect w&ic&
'enerates t&e trace strin') %ost widely used e1ent tyes are s&own below) T&e
comlete list o/ e1ent tyes is 'i1en in /ile Tns$tcl$lib$ns9trace)tcl)
H F4G w&ic& reresents a acket enDue e1ent*
H FJG w&ic& reresents a acket deDue e1ent*
H FrG w&ic& reresents a acket recetion e1ent*
H FdG w&ic& reresents a acket dro ?e)')* sent to FdropHead5G@ e1ent* and
H FcG w&ic& reresents a acket collision e1ent at t&e %4C le1el)
Time< 6&en t&e acket trace record is created)
Sendin' Node and (ecei1in' Node< I.s o/ t&e nodes located be/ore and a/ter*
resecti1ely* t&e tracin' obBect w&ic& creates t&is trace record)
Payload Tye< Name o/ t&e ayload tye* as seci/ied in Pro'ram ")#)
Packet SiJe< SiJe o/ t&e acket in bytes)
Cla's< 4 29di'it /la' strin' is de/ined in !ines #H21 o/ Pro'ram 1:)13) Eac&
/la' di'it is set to FJ*G w&en disabled) Ot&erwise* it will be set as /ollows<
H 1st< Set to FEG i/ an ECN ?EAlicit Con'estion Noti/ication@ ec&o is enabled)
H 2nd< Set to FPG i/ t&e riority in t&e IP &eader is enabled)
H 3rd< Not in use)
H :t&< Set to FAG i/ t&e corresondin' TCP takes an action on a con'estion
?e)')* closes t&e con'estion window@)
H 3t&< Set to FEG i/ t&e con'estion &as occurred)
H 8t&< Set to FQG i/ t&e TCP /ast start is used)
H 2t&< Set to FN*G w&en t&e transort layer rotocol is caable o/ usin' EAlicit
Con'estion Noti/ication ?ECN@)
Clow I.< T&e /ield F"id5G o/ t&e IP acket &eader)
Source 4ddress and .estination 4ddress< T&e source and destination addresses
o/ a acket seci/ied in an IP acket &eader) Cor a /lat addressin' sc&eme* t&e
/ormat o/ t&ese two /ields is FaIb*G w&ere FaG is t&e address and FbG is t&e
ort)
SeDuence Number< T&e seDuence number corresondin' to t&e rotocol
seci/ied
in t&e acket ayload tye)
Packet 0niDue I.< 4 uniDue I. stored in t&e common acket &eader)
E%ample /*/* Consider t&e /ollowin' trace record /rom a trace /ile<
J 2I1>B/=G 0 1 tcp 20=0 JJJJJJJ 1 0I2 3I1 = 22/
T&e interretation /or t&is trace line is as /ollows) 4t F2I1>B/=GG second* a
acket wit& uniDue acket I. is F22/G eAits t&e Dueue ?FJG@ o/ t&e link
connectin' node
=eason '
-asic 'race
Strin4 ,dditional 'race Strin4
,*D9 trace; ==+5 Pac1et
Z!#Z
==+5
'y6e
Ho6
0ount
-roadcast
/D
Destination
/P ,ddress
Destination
Se3: )o:
Source
/P
,ddress
Source
Se3: )o:
Z=e3uestZ
/P 'race
Z$$$$$$$Z
Source
/P ,ddress
Z;Z
Source
Port )o:
Destination
/P ,ddress
Z;Z
Destination
Port )o:
'ime to
Li(e
)ext Ho6
/P ,ddress
-asic 'race Strin4
+(ent
'y6e
'ime
)ode
/D
'race
=eason
Le(el
Pac1et
?ni3ue /D
Payload
'y6e
Pac1et
Si<e
'ime to
Send
Data
Destination
M,0
,ddress
Source
M,0
,ddress
+thernet
Pac1et
'y6e
1 2 3 4 %
& A B 1! 11 12
4ig= %/=7 6ireless trace /ormat
F0G to node F1G) T&e acket is a FtcpG acket w&ose siJe is F20=0G bytes)
T&is acket belon's to t&e TCP /low number F1G and is ta''ed wit& seDuence
number F=G) T&e source and destination sockets o/ t&e acket are F0I2G and
F3I1G* resecti1ely* w&ere t&e address and ort are searated by a dot symbol
?FIG@)
%/=*=0=2 Wire#ess Packet Trace
4ormat
6ireless acket trace /ormat is acti1ated automatically w&en runnin' a wireless
network ?see C&a) 12 /or wireless networkin' in NS2@) 4s s&own in Ci') 1:)"*
wireless acket trace /ormat consists o/ two main arts) T&e /ormer H Basic trace
string H is mandatory) It aears on e1ery wireless trace record) T&e latter H
+dditional trace string H is rotocol9seci/ic) Its /ormat deends on t&e entity
bein' traced) 6&ile NS2 suorts se1eral traceable entity ?e)')* TCP* C+(*
TO(4@* Ci') 1:)" s&ows only two eAamles o/ additional trace strin' /ormat H
namely IP
trace and 4O.79##E trace)
8
4 more comre&ensi1e list o/ trace /ormat can
be
/ound in t&e /iles Tns$trace$cmu9trace)&*cc* in M12N* and in M11N)
T&e /ollowin' notations are also adoted in addition to t&ose used in Ci') 1:)2)
Strin's in Duotation marks are t&ose t&at aear in a trace record as t&ey are) 4lso*
a trace record contains bot& sDuare brackets and arent&eses) T&eir locations in a
trace record are s&own in Ci') 1:)") T&e column numbers are 'i1en /or t&e basic
tracin' only* since t&e /ield location /or additional trace strin' is rotocol9seci/ic)
Cields in a wireless trace record are s&own below<
8
See t&e details o/ 4O.7 in Sect) 12)2)
:,, 1: Processin' an NS2 Simulation
Trace le1el< T&e common le1els are A-T /or a'ent trace* #T# /or routin'
trace* %AC /or %4C trace) See t&e list o/ ossible 1alues in t&e /ile
Tns$trace$cmu9 trace)cc)
(eason< T&e reason /or t&is trace ?e)')* FN#TEG /or No (ouTe
Entry@)
Time to Send .ata< EAected duration reDuired to transmitted t&is acket o1er
t&e wireless c&annel as indicated by t&e underlyin' %4C rotocol)
Et&ernet Packet Tye< Currently* t&ere are only two Et&ernet acket
tyes<
H 4 'eneral IP acket< T&e 1alue is FETHE#T[PE5IPG de/ined as F0*0/00)G
H 4n 4(P acket< T&e 1alue is FETHE#T[PE5A#PG de/ined as F0*0/A0)G
((EI Tye< Tye as indicated in t&e /ield Fr+5typeG o/ t&e (dr5aodv5
re+!est str!ct data tye) +y de/ault* t&e 1alue is FAODST[PE5##EG
de/ined as F0*01)G
E%ample /*1* Consider t&e /ollowin' wireless trace record<
s 12I>001B>000 505 %AC JJJ 0 AODS 20A ?0 """""""" 0
/00@ JJJJJJ ?091>> J291>> 30 0@ ?0*1 2 = ?2 0@
?0 20@@&#EDEST'
T&e interretation /or t&e basic trace /ormat is as /ollows) T&e node F505G sends
?i)e)* FsG@ at time F12I>001B>G second) T&e trace le1el is at t&e F%ACG layer)
T&e acket &as t&e uniDue I. o/ F0*G contains an FAODSG ayload tye* and is
F20AG bytes in siJe) T&e %4C rotocol assumes t&at t&e delay o1er t&e
underlyin' wireless c&annel is Jero F0)G Its source and destination %4C
addresses are F0G and F""""""""*G resecti1ely) Cinally* t&is acket is an IP
acket runnin' o1er an Et&ernet network ?i)e)* F/00G@)
Cor t&e IP trace /ormat* t&is acket is ta''ed wit& source and destination
addresses o/ F0G and F2*G resecti1ely) T&e orts /or bot& source and destination
are F1>>)G T&e time to li1e and t&e address o/ t&e neAt &o node are F30G &os
and F0*G resecti1ely)
Cinally* /or 4O.7 trace /ormat* t&is acket is an ((EI acket ?i)e)* F0*1)G@
T&e number o/ &o counts is F2G and t&e broadcast I. is F=)G T&e destination IP
address and seDuence number are 2 and ,* resecti1ely) T&e source IP address
and seDuence number are 0 and 1,* resecti1ely) Cinally* t&e strin'
F&#EDEST'G con/irms t&at t&is is an ((EI acket)
%/=*=0=* New Wire#ess Trace 4ormat
New wireless trace /ormat is t&e most comre&ensi1e trace /ormat in NS2) It can
be acti1ated in a simulation o/ wireless networks by t&e /ollowin' OTcl statement<
Pns5 !seJne,trace
w&ere Pns5 is t&e Sim!lator obBect) T&e abo1e OTcl statement must be
laced be/ore t&e statement FPns5 traceJall <c(K)G Ot&erwise t&e new
wireless trace will not be acti1ated)
1:)3 Packet Tracin' :,1
4'ain* new wireless trace /ormat is structureless) !ike t&e /ormer two trace
/ormat* t&e new wireless trace be'ins wit& an e1ent tye H w&ic& can be Fsend
?s@*G Frecei1e ?r@*G Fdro ?d@*G or F/orward ?"@)G Howe1er* subseDuent trace
strin's /ollow t&e /ollowin' syntaA<
J<ta$K <t$5val!eK ?J<s!btabK <st$5val!eK@
w&ere <ta$K is a one9letter or two9letter otion ta'* indicatin' t&e meanin' o/
t&e /ollowin' <t$5val!eK) In addition* some ta's reDuire an otional
<s!bta$K w&ose 1alue is seci/ied in <st$5val!eK) T&e list o/ otion ta's
and sub9ta's as well as t&eir meanin' is 'i1en below<
;enera# information<
Jt Time
Noe information ?JN\@<
JNi Node I. JN*) JNy) JN6 Node coordinate
JNl Trace le1el< A-T$#T#$%AC JN, (eason
JNe Ener'y le1el ?de/ault U 91* i)e)* not tracin' ener'y
le1el@
'P 'nformation ?JI\@<
JIs Source ?addrIport@ JId .estination ?addrIport@
JIt Packet tye JIl Packet siJe
JI" Clow I. JIi 0niDue I.
JIv Time to li1e
Ne<t ho& ?JH\@<
JHs I. o/ t&is node JHs I. o/ t&e neAt &o node
MA$ #eve# information ?J%\@<
J%s Source Et&ernet address J%d .estination Et&ernet address
J%t Et&ernet tye J%a Packet transmission time
A&&#ication informationFARP ?JP arp JP\@<
JPs Source IP address JPd .estination IP address
JPm Source %4C address JPa .estination %4C address
JPo Eit&er F#EDESTG or F#EPL[G
A&&#ication informationF$BR ?JP cbr JP\@<
JPi SeDuence number
JP" T&e number o/ time t&is acket &as been /orwarded
JPo %in) number o/ &os to reac& t&e destination as indicated
by LO.) T&e de/ault 1alue w&en LO. is not in use is 91)
:,2 1: Processin' an NS2 Simulation
A&&#ication informationFT$P ?JP tcp JP\@<
JPs SeDuence number JPa 4cknowled'ement number
JP" Same as t&at o/ C+( JPo Same as t&at o/ C+(
w&ere t&e c&aracter F\G reresents a letter) 4'ain* t&e comlete list o/ tracin' ta's
and subta's can be /ound in t&e /iles Tns$trace$cmu9trace)&*cc* in M12N* and M11N)
E%ample /*8* Consider t&e /ollowin' new wireless trace
record<
s Jt 32I000000000 JHs 0 JHd J1
JNi 0 JN* 2GI3A JNy 2BI31 JN6 0I00 JNe J2I000000
JNl A-T JN, JJJ J%a 0 J%d 0 J%s 0 J%t 0
JIs 0I0 JId 2I0 JIt tcp JIl =0 JI" 1 JIi 3 JIv 31
JPn tcp JPs 0 JPa 0 JP" 0 JPo 0
T&e interretation is as /ollows) 4t 31 s* t&is record traces Node 0 at t&e a'ent
A-T le1el) T&e Node is located at t&e coordinate &2GI3A)2BI31)0') T&e
reasons strin' ?i)e)* JN,@ is emty) T&e record does not trace t&e node ener'y
le1el ?JNe
J2@) T&e acket is sent /rom t&e address , ort , to t&e node wit& t&e address 1
ort ,) T&e acket tye is Ftcp)G Its siJe is :, bytes) T&e /low I. is 1) T&e acket
uniDue I. is 3) T&e time to li1e is 31) T&is acket &as ne1er been /orwarded
be/ore) T&e otimal number /orwards is Jero ?i)e)* LO. is not acti1e@)
%/=/ $om&i#ation of Simu#ation Resu#ts
Comilation o/ simulation results re/ers to a rocess o/ collectin' in/ormation
/rom simulation and comute er/ormance measures under consideration) T&ere
are t&ree main aroac&es to collect simulation data /or result comilation<
t&rou'& CCC t&rou'&* 1ariable tracin'* and t&rou'& acket tracin')
Through CCC program< T&is re/ers to an aroac& w&ic& inserts CCC state9
ments into t&e ori'inal NS2 ro'ram) 4s mentioned earlier in t&is book* t&e
modi/ication o/ CCC ro'ram results in a Duick simulation) T&is aroac&
also ro1ides 'reat /leAibility in w&ic& most in/ormation would be accessible)
Howe1er* ro'rammers reDuire a /air amount o/ knowled'e about t&e CCC
arc&itecture to collect results /rom t&e simulation)
Through varia'le tracing< T&is met&od is er&as t&e most con1enient way to
collect t&e results) T&e ro'rammers do not need to know t&e details o/ t&e
CCC arc&itecture) T&ey only need to know t&e traceability and$or bindin'
structure o/ OTcl inst1ars under consideration) Howe1er* t&e ran'e o/
collectable in/ormation is limited to traceable 1ariables only)
Through packet tracing< Packet tracin' is easy to set u* and it ro1ides a
'reat deal o/ detailed acket mo1ements) T&e downside o/ acket tracin' is
t&at it si'ni/icantly drains comutational ower ?e)')* memory* CP0 time@* and
1:): Comilation o/ Simulation (esults :,3
dramatically slows down simulation) T&e 'reat amount o/ collected in/ormation
can also o1erw&elm researc&ers w&o need to comute er/ormance measure
suc& as t&rou'&ut) Ironically* t&is 'reat amount o/ in/ormation does not
necessarily contain t&e reDuired in/ormation suc& as t&e number o/ error
correction bits in acket &eaders) In most cases* acket tracin' roceeds in two
stes) T&e /irst ste is to write all in/ormation at t&e network c&eckoints into a
trace /ile usin' an OTcl statement FPns traceJall P"c()G T&e second
ste is to /ilter out unnecessary in/ormation and comute er/ormance
measures o/ interest) In t&is ste* a scritin' lan'ua'e suc& as 46K can be
used ?see 4endiA 4@)
E%ample /*9* Consider EAamle 1,)1 w&ic& creates t&e network in Ci') #)3)
Insert an error model wit& error robability ,)3P into t&e link connectin' Node 1
and Node 3) Suose t&e maAimum TCP transmission window siJe is set to 2,)
(un simulation /or 1, seconds* and er/orm t&e /ollowin' task)
Through CCC codes< Cind out t&e number o/ times TCP transmission window
is reduced)
Through varia'le tracing< Plot t&e dynamic 1ariation o/ TCP transmission
window)
Through packet tracing< Comute t&e a1era'e inter1al between two TCP
ackets enterin' t&e link layer bu//er)
Constructing a Network
4n error model can be inserted into t&e network by insertin' t&e /ollowin' OTcl
codes immediately a/ter !ine 2 o/ EAamle 1,)1<
set em ?ne, Error%odel@
Pem set rate5 0I00>
Pem !nit pkt
Pem ranvar ?ne, #andomSariableMDni"orm@
Pem dropJtar$et ?ne, A$entMN!ll@
Pns lossmodel Pem Pn2 Pn3
T&e maAimum TCP transmission window is set to 2, by t&e /ollowin'
statement a/ter !ine 1, in EAamle 1,)1< F Ptcp set ,indo,5 10)G
#esult Compilation Through CCC
Codes
TCP s&rinks its transmission window w&en t&e /unction slo,do,n&(o,'
o/ class TcpA$ent is in1oked) T&ere/ore* we may declare a 1ariable
Fn!m5slo,do,ns5G o/ class TcpA$ent in /ile Tns$tc$tc)&* initialiJe it
to Jero in t&e constructor* and add t&e two /ollowin' lines in t&e /unction
slo,do,n&(o,'<
:,: 1: Processin' an NS2 Simulation
n!m5slo,do,ns544;
print"&HTotal n!mber o" TCP ,indo, s(rinkin$ events
is Ed TnH) n!m5slo,do,ns5';
4/ter recomilin' NS2* we run t&e scrit FtcpItclG and obtain t&e /ollowin'
results<
KK ns tcpItcl
Total n!mber o" TCP ,indo, s(rinkin$ events is 2
Total n!mber o" TCP ,indo, s(rinkin$ events is 1
Total n!mber o" TCP ,indo, s(rinkin$ events is 3
III
Total n!mber o" TCP ,indo, s(rinkin$ events is 3A
In t&is simulation* TCP s&rinks its transmission window 38 times)
#esult Compilation Through ?aria'le
Tracing
7ariable tracin' re/ers to t&e met&ods /or trackin' c&an'es in OTcl inst1ars)
Section 1:)2 discussed a built9in mec&anism to do so) 4lternati1ely* ro'rammers
may use manual 1ariable tracin' s&own below)
Transmission window siJe o/ a TCP connection is t&e minimum o/ inst1ars
Fc,nd5G and F,indo,5G o/ a A$entMTCP obBect) Since t&ese two 1ariables
are a1ailable in t&e OTcl domain* we may collect samles o/ TCP window siJe
by insertin' t&e /ollowin' Tcl scrit a/ter !ine 1: in EAamle 1,)1)
2 set "5c,nd ?open c,ndItr ,@
1 proc plot5tcp 7 8 7
3 $lobal "5c,nd tcp ns
= i" 7 ?Ptcp set c,nd5@ < ?Ptcp set ,indo,5@ 8 7
> p!ts P"5c,nd H?Pns no,@ ?Ptcp set c,nd5@H
A 8 else 7
B p!ts P"5c,nd H?Pns no,@ ?Ptcp set ,indo,5@H
/ 8
G Pns at ?e*pr ?Pns no,@ 4 0I1@ plot5tcp
20 8
22 Pns at 0I02 Hplot5tcpH
T&e abo1e statements ut time and TCP transmission window siJe in t&e /ile
Fc,ndItrG e1ery ,)2 s) !ine 1 abo1e creates a Tcl c&annel F"5c,ndG w&ic&
is attac&ed to t&e /ile Fc,ndItr)G !ines 2H1, de/ine a rocedure plot5tcp/')
!ines 11 in1okes t&e rocedure plot5tcp/' at ,),1 s) 6it&in t&e rocedure
plot5tcp/'* !ines 3 and 2 rint inst1ars Fc,nd5G and F,indo,5*G w&ic&e1er
is less* on t&e Tcl c&annel F"5c,nd)G !ine # sc&edules an in1ocation o/ t&e
rocedure plot5tcp/' at ,)2 s in /uture) T&is in1ocation continuously rints out
simulation time and TCP transmission window siJe to t&e Tcl c&annel until t&e
simulation terminates)
'
r
a
n
s
m
i
s
s
i
o
n

>
i
n
d
o
>

s
i
<
e
1:): Comilation o/ Simulation (esults :,3
4ig= %/=8 .ynamics o/ TCP
2%
transmission window /or
EAamle 1:)2
2!
1%
1!
%
!
! 2 4 & 1!
'ime
4/ter runnin' t&e abo1e Tcl simulation scrit* t&e /ile Fc,ndItrG is created)
T&e /irst and t&e second columns o/ t&e /ile Fc,ndItrG are t&e time and t&e
corresondin' TCP transmission window* resecti1ely) Ci'ure 1:)# lots
simulation time ?1st column@ a'ainst transmission window siJe ?2nd column@)
Since we set t&e inst1ar F,indo,5G to be 2,* TCP transmission window can
ne1er eAceed 2,) 6e can also obser1e /reDuent decreases in TCP transmission
window siJe due to acket losses)
#esult Compilation Through Packet
Tracing
T&e /irst ste in t&is aroac& is to enable tracin' in t&e Tcl simulation scrit)
4'ain* t&is ste can be carried out by insertin' t&e /ollowin' statements a/ter !ine
: in EAamle 1,)1)
set "5trace ?open traceItr ,@
Pns traceJall P"5trace
T&e second ste is to rocess t&e trace /ile) In t&is case* t&ere is only one TCP
/low in t&e simulation and we can measure t&e inter1al between two TCP ackets
enterin' a Dueue* w&ic& connect Node 1 ?wit& I. ,@ to Node 3 ?wit& I. 1@* usin'
t&e 46K scrit /ile Fav$Ia,kG in Pro'ram 1:)1") +y eAecutin' t&e 46K scrit*
we will see t&e /ollowin' result on t&e screen<
KK a,k J" av$Ia,k traceItr
Avera$e TCP packet interJarrival time is 0I002B03
!ine 1 in Pro'ram 1:)1" initialiJes 1ariable FstartedG to Jero) !ines 2H1:
collect samles o/ t&e inter9arri1al time o/ TCP ackets) !ine 2 /ilter out t&e trace
records w&ic& do not be'in wit& F4)G Crom !ine 3* t&e samles are collected only
:,8 1: Processin' an NS2 Simulation
Program %/=%7 4n 46K scrit w&ic& comutes t&e a1era'e inter1al between two
TCP ackets enterin' a link layer bu//er o/ Node 1
MMav$Ia,k
2 .E-IN7 started : 0 8
1 M`4M 7
3 time : P1;
= i" &started :: 2' 7
> i" &P3::0 FF P=::1 FF P> :: HtcpH' 7
A interval : timeJold5time;
B old5time : time;
/ c!m5interval 4: interval;
G total5samples 44;
20 8
22 8 else 7
21 started : 2; old5time : time;
23 8
2= 8
2> END 7
2A av$5interval : c!m5intervalMtotal5samples;
2A print"&HAvera$e TCP packet interJarrival time
is E"TnH) av$5interval';
2B 8
/or t&e source node 0* t&e destination node 1* and rotocol FtcpG ?see Ci') 1:)2@)
Cinally* !ines 13H12 comute and rint t&e a1era'e TCP acket inter9arri1al time
on t&e screen)
%/=0 $ha&ter Summary
T&is c&ater /ocuses on debu''in'* tracin'* and comilation o/ simulation results)
.ebu''in' re/ers to a rocess o/ remo1in' comilation and run9time errors in bot&
CCC and OTcl domains) T&is c&ater ro1ides 'uidelines and necessary
commands /or debu''in') 4lt&ou'& ori'inally desi'ned to /acilitate t&e
understandin' o/ network dynamics* NS2 tracin' could also be use/ul in t&e
debu''in' rocess) NS2 suorts two tyes o/ tracin') 7ariable tracin' records
t&e c&an'es in 1alue o/ a 1ariable ?in most cases in a /ile@* w&ile acket tracin'
stores t&e details o/ ackets assin' t&rou'& network c&eckoints ?a'ain in most
cases in a /ile@)
T&ere are t&ree maBor result comilation aroac&es) T&e /irst aroac& is
t&rou'& CCC ro'ram) It is Duick at runtime and 'i1es ro'rammers an access to
most o/ t&e NS2 comonents) On t&e ot&er &and* t&e ro'rammers may reDuire a
/air amount o/ knowled'e on t&e CCC arc&itecture) 4lso* since t&is met&od
in1ol1es t&e modi/ication o/ CCC code* it could mess u t&e ori'inal NS2 source
codes)
T&e second aroac& is t&rou'& 1ariable tracin') T&is aroac& allows ro9
'rammers to collect t&e results /rom t&e OTcl domain in a simle way) 0sin' t&is
1:)8 EAercises :,2
aroac&* ro'rammers do not need to understand t&e entire arc&itecture o/ NS2*
but t&e ran'e o/ collectable in/ormation is /airly limited)
T&e last aroac& is t&rou'& acket tracin'* w&ic& consists o/ two stes< ?1@
recordin' trace strin's in a trace /ile and ?2@ rocessin' t&e trace /ile) 4lt&ou'&
sim9 le and in/ormati1e* t&is met&od drains comutation resource and can
o1erw&elm ro'rammers wit& t&e delu'e o/ in/ormation) Pro'rammers would
need to learn a scritin' lan'ua'e suc& as 46K to eAtract reDuired in/ormation
/rom t&e trace /ile) T&e abo1e t&ree aroac&es /or comilation o/ results &a1e
t&eir own stren't&s and weaknesses) Pro'rammers need to c&oose t&e ri'&t one
based on t&eir main simulation obBecti1es)
%/=6 "<ercises
1) EAlain t&e di//erence between 1ariable tracin' and acket tracin')
2) 6&at are t&e ossible causes o/ se'mentation /ault errorR
3) 6&at are t&e di//erences between comilation error and runtime errorR In
w&ic& domain ?CCC or OTcl@ do t&ese errors occurR
:) 6rite down t&e statements w&ic& retrie1e t&e current simulation time /rom
bot&
CCC and OTcl domainsR
3) 6rite down a CCC statement w&ic& con1erts a CCC obBect Fc5objG to
an OTcl re/erencin' strin' and a CCC statement w&ic& con1erts a OTcl
re/erencin' strin' FstrG to a CCC obBect)
8) 6&at are attributes o/ a traceable 1ariableR
2) EAlain t&e /ollowin' comonents and t&eir relations&i /or 1ariable tracin'<
TclObBects* traceable 1ariables* tracers* Tcl c&annels* and trace /iles) .raw a
dia'ram and 'i1e eAamles to suort your answer)
") Set u t&e acket tracin' network dia'ram in Ci') 2)8) 6&at are t&e OTcl
statements w&ic& set u acket tracin'R 6&at tye o/ acket tracin' /ormat
aear in t&e trace /ileR
#) Crom EAercise "* write 46K scrits to do t&e /ollowin'<
a) Comute t&e t&rou'&ut in bs o/ t&e link connectin' nodes N0 and
N1) b) Comute t&e t&rou'&ut in bs corresondin' to TCP0)
c) Comute a1era'e acket deli1ery delay /or t&e link connectin' nodes N1
and N3)
1,) In Ci') 2)8* trace c&an'es in acket seDuence number o/ TCP0 o1er time)
Plot your results in a 'ra&) EAlain in time seDuence &ow NS2 sets u t&e
trace and &ow it traces t&e 1ariable in realtime)
:," 1: Processin' an NS2 Simulation
11) Set u a simulation /or a wireless network wit& ten Nodes w&ic& runs 4O.7
as t&e routin' rotocol)
0sin' wireless ?i)e)* C%0@ tracin'* comute end9to9end t&rou'&ut a1er9
a'ed o1er all t&e nodes)
0sin' new wireless tracin'* lot t&e ener'y le1el o/ node 2)
$ha&ter %0
Re#ate He#&er $#asses
Heler classes 'enerally not a art o/ a network* but are used in NS2 as an
internal mec&anism and$or are network comonents in a secial case) T&is c&ater
discusses t&e details o/ t&ree main NS2 &eler classes) In Sect) 13)1* we /irst
discuss class Timer* w&ic& is widely used by ot&er NS2 modules suc& as TCP to
imlement conditional time9based actions) In Sect) 13)2* we demonstrate a random
number 'eneration rocess in NS2) In Sect) 13)3* we eAlain t&e details o/ class
Error%odel* w&ic& can be used to simulate acket error) Section 13): discusses
bit maskin' and bit s&i/tin' oerations used in 1arious laces in NS2) Cinally* t&e
c&ater summary is 'i1en in Sect) 13)3)
%0=% Timers
Timer is a comonent t&at can be used to delay actions) 0nless cancelled or
restarted* a timer takes actions a/ter it &as been started /or a 'i1en eriod o/ time
?i)e)* at t&e eAiration@) Cor eAamle* a sender starts a retransmission timer as soon
as it transmits a acket) 0nless cancelled by a recetion o/ an acknowled'ment
acket* t&e timer assumes acket loss and asks t&e sender to retransmit t&e lost
acket at t&e timer eAiration)
1+.1.1 Ipleentation Concept of Tier in %S2
4s s&own in Ci') 13)1* a timer consists o/ /our /ollowin' states< IDLE* SET
WAITIN- TI%E* WAITIN-* and ELPI#ED) 4 transition /rom one state to
anot&er occurs immediately w&en t&e oeration in t&e current state is comlete
?i)e)* by de/ault@* or w&en t&e timer recei1es a start messa'e* a restart messa'e* or
a cancel messa'e)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 13* = Srin'er Science>+usiness %edia* !!C 2,12
:,#
:1, 13 (elated Heler Classes
,0'/9+
restart(delay)
S+' [,/'/)K
'/M+ (@delay)
start(delay)
default
/DL+
default
[,/'/)K
cancel
default
default
+#P/=+D
('a1e +x6iration ,ctions)
4ig= %0=% Timer li/e cycle
6&en a timer is created* it sets t&e state to be IDLE) 0on recei1in' a start
messa'e* t&e timer mo1es to t&e state SET WAITIN- TI%E* w&ere it sets its
waitin' time to be FdelayG seconds and mo1es to t&e state WAITIN-) T&e timer
stays in t&e state WAITIN- /or FdelayG seconds and mo1es to t&e state
ELPI#ED) 4t t&is oint* t&e timer takes rede/ined eAiration actions and mo1es
back to t&e state IDLE) Herea/ter* we will say t&at t&e timer e%pires as soon as it
enters t&e state ELPI#ED) 4lso* we s&all re/er to t&e actions taken in state
ELPI#ED as e%piration actions)
T&e abo1e timer li/e cycle occurs by de/ault w&en t&e messa'e FstartG is
recei1ed) 6&en a FcancelG messa'es is recei1ed* t&e timer will sto waitin' and
mo1e back to t&e state IDLE) I/ a restart messa'e is recei1ed* t&e timer will restart
t&e waitin' rocess in t&e state SET WAITIN- TI%E)
Imlementation o/ timer in NS2 is a 1ery 'ood eAamle o/ t&e inheritance
concet in OOP) Eac& timer needs to imlement t&e t&ree /ollowin' mec&anisms<
?1@ waitin' mec&anism* ?2@ inter/ace /unctions to start* restart* and cancel t&e wait9
in' rocess* and ?3@ eAiration actions) T&e /irst two mec&anisms are common to
all timersO &owe1er* t&e last mec&anism ?i)e)* eAiration actions@ is w&at
di//erentiates one timer /rom anot&er) Crom an OOP oint o/ 1iew* t&e timer base
class must de/ine t&e waitin' mec&anism and messa'e recei1in' inter/aces* and
lea1e t&e imlementation o/ t&e eAiration actions to t&e deri1ed classes)
In NS2* timers are imlemented in bot& CCC and OTcl) Howe1er* bot& CCC
and OTcl timer classes are standalone ?i)e)* not bound to'et&er by TclClass@)
(ele1ant /unctions and 1ariables in bot& domains are s&own in Table 13)1) In bot&
domains* NS2 imlements t&e waitin' rocess by utiliJin' t&e Sc&eduler) 0on
enterin' t&e state SET WAITIN- TI%E* NS2 laces a timer eAiration e1ent on
t&e simulation timeline) 6&en t&e Sc&eduler /ires t&e eAiration e1ent* t&e timer
enters t&e state ELPI#ED and eAecutes t&e eAiration actions)
T ab # e %0 = % T im e r im l e m en t a ti o n i n C CC and O Tcl do m a i ns
Co m onen t s o / a ti m er C CC co m onen t s O Tcl co m onen t s
State IDLE stat!s5:TI%E#5IDLE Fid5G unset
State SET WAITIN- TI%E stat!s5:TI%E#5PENDIN- Fid5G set
State WAITIN- stat!s5:TI%E#5PENDIN- Fid5G set
State ELPI#ATION stat!s5:TI%E#5HANDLIN- Fid5G set
%essa'e start Cunction sc(ed Instrocs sc(ed
and
resc(ed
%essa'e restart Cunction resc(ed Instrocs sc(ed
and
resc(ed
%essa'e cancel Cunction cancel Instrocs cancel
and
4ction at t&e eAiration Cunction e*pire
destroy
Instroc timeo!t
1+.1.2 OTcl Ipleentation
In t&e OTcl domain* NS2 imlements timers usin' an OTcl class Timer) T&e
imlementation o/ class timer consists o/ t&ree arts) Cirst* t&e waitin' mec&anism
is imlemented by lacin' a timer eAiration e1ent on t&e simulation timeline
usin' t&e instroc at/III' o/ class Sim!lator ?See !ines # and 13 in Pro'ram
13)1@) Second* t&e inter/ace o/ class Timer is de/ined in t&e instrocs
sc(ed/delay'* resc(ed/delay'* cancel/'* and destroy/') Cinally* t&e
eAiration actions are seci/ied in t&e instroc timeo!t/'* w&ic& is
imlemented in c&ild classes o/ class Timer ?see class ConnTimer in /ile
Tns$tcl$webcac&e$webtra/)tcl* /or eAamle@)
Pro'ram 13)1 s&ows details o/ 1arious instrocs o/ OTcl class Timer) Class
Timer &as two key inst1ars< Fns5G in !ine 8 and Fid5G in !ine 2) T&e inst1ar
Fns5G is a re/erence to t&e Simulator) It is con/i'ured at t&e construction o/ a
Timer obBect ?see !ines 2H:@) T&e constructor o/ class Timer takes t&e
Simulator as its inut ar'ument and stores t&e inut instance in its inst1ar Fns5)G
T&e inst1ar Fid5G ?!ine 2@ indicates t&e state o/ t&e timer) I/ t&e timer is idle*
Fid5G will not eAist ?since it is !nset@) I/ t&e timer is acti1e* Fid5G will contain
t&e uniDue I. o/ t&e timer eAiration e1ent on t&e simulation timeline)
T&e instrocs sc(ed/delay' ?!ines 3H1,@ and resc(ed/delay' ?!ines 11H
13@ are NS2 imlementation /or recei1in' a start messa'e and a restart messa'e*
resecti1ely) T&ey take one inut ar'ument FdelayG and set t&e timer to eAire
a/ter FdelayG seconds) (e'ardless o/ t&e timer state* t&e instroc
sc(ed/delay' cancels t&e timer usin' t&e instroc cancel/' in !ine ") In !ine
#* it tells t&e timer to eAire at FdelayG seconds in /uture by in1okin' t&e
instroc a"ter/ival ar$s' o/ class Sim!lator) S&own in !ines 1:H18* t&e
instroc a"ter/III' uses an OTcl command at o/ class Sim!lator to lace
anot&er OTcl command in /uture)
1
Crom !ine #* t&e instroc sc(ed/delay'
sc&edules an in1ocation o/
1
4s discussed in Sect) :)2)3* t&e OTcl command Fat/III'G laces an AtEvent obBect on
t&e simulation timeline* and returns t&e uniDue I. o/ t&e sc&eduled e1ent to t&e caller)
:12 13 (elated Heler Classes
Program %0=% Timer related OTcl instrocs
MMUMnsMtclMmcastMtimerItcl
2 Class Timer
1 Timer instproc init 7 ns 8 7
3 Psel" set ns5 Pns
= 8
> Timer instproc sc(ed delay 7
A Psel" instvar ns5
B Psel" instvar id5
/ Psel" cancel
G set id5 ?Pns5 a"ter Pdelay HPsel" timeo!tH@
20 8
22 Timer instproc resc(ed delay 7
21 Psel" sc(ed Pdelay
23 8
MMUMnsMtclMlibMnsJlibItcl
2= Sim!lator instproc a"ter 7ival ar$s8 7
2> eval Psel" at ?e*pr ?Psel" no,@ 4 Pival@ Par$s
2A 8
MMUMnsMtclMmcastMtimerItcl
2B Timer instproc cancel 78 7
2/ Psel" instvar ns5
2G Psel" instvar id5
10 i" ?in"o e*ists id5@ 7
12 Pns5 cancel Pid5
11 !nset id5
13 8
1= 8
1> Timer instproc destroy 78 7
1A Psel" cancel
1B 8
t&e instroc Ftimeo!t/'G at FdelayG seconds in /uture and stores t&e uniDue I.
corresondin' to t&e timer eAiration e1ent in t&e inst1ar Fid5)G
!ines 12H22 in Pro'ram 13)1 s&ow details o/ t&e instrocs cancel/' and
destroy/' o/ class Timer) +ot& t&e instrocs act as an inter/ace to recei1e a
cancel messa'e) Note t&at Fid5G eAists only w&en a timer eAiration e1ent is
on t&e simulation timeline) Timer is cancelled only w&en Fid5G eAists ?i)e)* t&e
condition in !ine 2, is tr!e@) In t&is case* !ine 21 /eeds Fid5G to t&e instroc
cancel/id5' ?see Pro'ram 13)2@ o/ t&e Simulator instance to remo1e t&e timer
eAiration e1ent /rom t&e timeline) Cinally* !ine 22 unsets t&e inst1ar Fid5G to
indicate t&at t&e eAiration e1ent is no lon'er on t&e simulation timeline)
Pro'ram 13)2 s&ows details o/ t&e instroc cancel/III' o/ class
Sim!lator and t&e OTcl command cancel/!id' o/ class Sc(ed!ler) T&e
instroc cancel/III' takes one inut ar'ument F!id*G w&ic& is t&e uniDue
I. o/ an
13)1 Timers :13
Program %0=2 Instroc cancel o/ class Sim!lator and an OTcl command
cancel o/ class Sc(ed!ler
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc cancel ar$s 7
1 Psel" instvar sc(ed!ler5
3 ret!rn ?eval Psc(ed!ler5 cancel Par$s@
= 8
MMUMnsMcommonMsc(ed!lerIcc
> int Sc(ed!ler99command&int ar$c) const c(ar
N
const
N
ar$v'
A 7
B III
/ i" &strcmp&ar$v?2@) HcancelH' :: 0' 7
G Event
N
p : look!p&ST#TODID&ar$v?1@'';
20 i" &p C: 0' 7
22 cancel&p';
21 AtEvent
N
ae : &AtEvent
N
'p;
23 delete ae;
2= 8
2> 8
2A III
2B 8
e1ent to be cancelled) !ine 3 in1okes t&e OTcl command cancel/!id' o/ t&e
Sc&eduler ?stored in an inst1ar Fsc(ed!ler5G o/ t&e Simulator@* w&ic& remo1es
t&e timer eAiration e1ent w&ose uniDue I. is F!idG ?see !ines #H13@)
1+.1." CCC Class Ipleentation
T&is section eAlains t&e CCC imlementation o/ a timer) 6e /irst s&ow t&e li/e
cycle o/ a CCC timer based on CCC /unctions ?in Table 13)1@) Second* we
brie/ly discuss t&e declaration o/ CCC abstract class TimerHandler* w&ic&
reresents timers in t&e CCC domain) T&ird* we describe t&e details o/ t&ree main
comonents o/ a timer< ?1@ internal waitin' mec&anism* ?2@ inter/ace /unctions* and
?3@ eAiration actions) Court&* we demonstrate &ow a timer is cross9re/erenced wit&
anot&er obBect) Cinally* we conclude t&is section by ro1idin' 'uidelines /or
imlementin' timers in NS2)
%0=%=*=% Timer +ife $yc#e
+ased on Ci') 13)1 and Table 13)1* we redraw t&e li/e cycle o/ a TimerHandler
obBect ?i)e)* a CCC timer obBect@ in Ci') 13)2) T&e de/ault state o/ a timer is
TI%E#5IDLE) 0on in1okin' /unctions sc(ed&delay' or
resc(ed&delay'*
:1: 13 (elated Heler Classes
default
'/M+=C/DL+
sched(delay) or
resched(delay)
'/M+=CH,)DL/)K;
+x6iration actions
(in(o1e function ex6ire(e))
resched(delay)
handle(e)
cancel
'/M+=CP+)D/)K;
[ait for a 6eriod of
delay (seconds)
4ig= %0=2 !i/e cycle o/ a TimerHandler
obBect
t&e timer mo1es /rom t&e state TI%E#5IDLE to anot&er state
TI%E#5PENDIN-* w&ere t&e timer starts a waitin' eriod o/ FdelayG seconds)
6&en t&e timer eAires* it mo1es to t&e state TI%E#5HANDLIN- and takes
eAiration actions by in1okin' t&e /unction e*pire&e') 4/ter takin' eAiration
actions* t&e timer mo1es to t&e state TI%E#5IDLE* and t&e cycle starts o1er
a'ain) (e'ardless o/ t&e state* /unction resc(ed&delay' cancels t&e endin'
timer and restarts t&e timer) In t&e state TI%E#5PENDIN-* we may cancel t&e
timer by in1okin' /unction cancel&'* w&ic& stos t&e acti1e timer and c&an'es
t&e state o/ t&e timer to TI%E#5IDLE)
%0=%=*=2 Brief ,verview of $#ass TimerHandler
Pro'ram 13)3 s&ows t&e declaration o/ a CCC abstract class TimerHandler*
w&ic& reresents timers) !ine 2 de/ines t&ree states o/ a TimerHandler ob9
Bect as members o/ TimerStat!s en!m data tye< TI%E#5IDLE* TI%E#5
PENDIN-* and TI%E#5HANDLIN-) Class TimerHandler contains only two
member 1ariables< Fstat!s5G in !ine 12 and Fevent5G in !ine 13) T&e
1ariable Fstat!s5G stores t&e current timer state ?or status@) It takes a 1alue in
/,O 1O 2'* w&ic& corresonds to t&e 1alues o/ t&e TimerStat!s en!m tye
s&own in !ine
2) T&e de/ault state o/ a timer is TI%E#5IDLE) T&ere/ore* 1ariable Fstat!s5G
is set to TI%E#5IDLE at t&e timer construction ?see !ine 3@) 4not&er 1ariable
Fevent5G ?o/ class Event@ reresents a timer eAiration e1ent) It acts as a 'lue
between a TimerHandler obBect and t&e Sc&eduler) T&e details o/ 1ariable
Fevent5G will be discussed in t&e neAt section)
T&e key /unctions o/ class TimerHandler alon' wit& t&eir descritions are
'i1en below)
Program %0=* .eclaration o/ class TimerHandler
MMUMnsMcommonMtimerJ(andlerI(
2 class TimerHandler 9 p!blic Handler 7
1 p!blic9
3 TimerHandler&' 9 stat!s5&TI%E#5IDLE' 7 8
= void sc(ed&do!ble delay'; MM cannot be pendin$
> void resc(ed&do!ble delay'; MM may or may not be pendin$
A void cancel&'; MM m!st be pendin$
B en!m TimerStat!s 7 TI%E#5IDLE) TI%E#5PENDIN-)
TI%E#5HANDLIN-8;
/ int stat!s&' 7 ret!rn stat!s5; 8;
G protected9
20 virt!al void e*pire&Event
N
' : 0;
22 virt!al void (andle&Event
N
';
21 int stat!s5;
23 Event event5;
2= private9
2> inline void 5sc(ed&do!ble delay' 7
2A &void'Sc(ed!ler99instance&'Isc(ed!le&t(is) Fevent5)
2B delay'; 8
2/ inline void 5cancel&' 7
2G &void'Sc(ed!ler99instance&'Icancel&Fevent5';
10 8
12 8;
sc(ed&delay' Start t&e timer and set t&e timer to eAire at
FdelayG seconds in /uture)
5sc(ed&delay' Place a timer eAiration e1ent on t&e simulation
time line at FdelayG seconds in /uture)
resc(ed&delay' (estart t&e timer and set t&e timer to eAire at
FdelayG seconds in /uture)
cancel&' Cancel t&e endin' timer)
5cancel&' (emo1e a timer eAiration e1ent /rom t&e simula9
tion time line)
stat!s&' (eturn t&e 1ariable Fstat!s5*G t&e current state
o/ t&e timer)
(andle&e' In1okes t&e /unction e*pire&e') It is used by
t&e Sc&eduler to disatc& a timer eAiration e1ent
?see C&a) :@)
e*pire&e' Take eAiration actions) It is a ure 1irtual /unc9
tion* and must be imlemented by c&ild instan9
tiable classes o/ class TimerHandler)
:18 13 (elated Heler Classes
4ig= %0=* 4 dia'ram w&ic& reresents t&e timer waitin' rocess ?i)e)* /unction
sc(ed&delay'@
%0=%=*=* 'nterna# Waiting Mechanism
Class TimerHandler imlements waitin' mec&anism t&rou'& /unctions
5sc(ed &delay' and 5cancel&delay') +asically* t&ese two /unctions
lace
and remo1e Fevent5G on t&e simulation timeline) In !ine 18 o/ Pro'ram 13)3*
t&e
/unction 5sc(ed&delay' eAecutes
Fsc(ed!le&t(is)Fevent5)delay'*G
w&ere Ft(isG is t&e timer address* Fevent5G is an eAiration dummy e1ent
?see Sect) :)3)2@* and FdelayG is t&e duration until t&e timer eAires) T&e
/unction sc(ed!le&III' stores t&e address o/ t&e timer Ft(isG in t&e
1ariable F(andler5G o/ t&e Event ointer Fevent5*G essentially settin'
event5JK(andler5 to oint to t&e TimerHandler obBect) T&en* it laces
t&e obBect F
N
event5G on t&e simulation timeline at FdelayG seconds in
/uture) 4t t&e /irin' time* t&e Sc&eduler in1okes t&e /unction dispatc(&e'*
w&ic& in turn eAecutes event5JK(andler5JK(andle&III') Since t&e
1ariable F(andle5G o/ t&e disatc&ed Fevent5G oints to t&e TimerHandler
obBect ?see Ci') 13)3@* NS2 in1okes t&e /unction (andle&e' associated
wit& t&e TimerHandler obBect at t&e /irin' time) T&e /unction
(andle&e' o/ class TimerHandler in turn in1okes t&e /unction
e*pire&e' ?!ine 8 o/ Pro'ram 13):@ w&ic& takes eAiration actions
seci/ied by t&e deri1ed classes
o/ class TimerHandler)
Cunction 5cancel&' does t&e oosite o/ w&at /unction 5sc(ed&delay'
does) It remo1es t&e timer eAiration e1ent /rom t&e simulation timeline) Crom
!ine
1# in Pro'ram 13)3* it in1okes /unction cancel&Fevent5' o/ class
13)1 Timers :12
Sc(ed!ler
to remo1e t&e e1ent FeventG /rom t&e simulation
timeline)
:18 13 (elated Heler Classes
%0=%=*=/ "<&iration Actions
4t t&e /irin' time* t&e Sc&eduler disatc&es a timer eAiration e1ent by in1ok9
in' /unction (andle&e' o/ t&e associated timer ?see also Ci') 13)3@) .etails
o/ t&e /unction (andle&e' are s&own in Pro'ram 13):) !ine 3 /irst c&ecks
w&et&er t&e current Fstat!s5G is TI%E#5PENDIN-) I/ so* !ine 3 will c&an'e
t&e 1ariable Fstat!s5G to TI%E#5HANDLIN-* and !ine 8 will in1oke /unc9
tion e*pire&e' to take eAiration actions) 4/ter returnin' /rom t&e /unction
e*pire&e'* t&e 1ariable Fstat!s5G is set by de/ault to TI%E5IDLE ?!ine "@)
Howe1er* i/ Fstat!s5G &as already c&an'ed ?e)')* w&en t&e timer is resc&eduledO
Fstat!s5GVTI%E#5HANDLIN- in !ine 2@* /unction (andle&e' will not
c&an'e 1ariable Fstat!s5)G
Program %0=/ Cunction (andle o/ class TimerHandler
MMUMnsMcommonMtimerJ(andlerIcc
2 void TimerHandler99(andle&Event
N
e'
1 7
3 i" &stat!s5 C: TI%E#5PENDIN-'
= abort&';
> stat!s5 : TI%E#5HANDLIN-;
A e*pire&e';
B i" &stat!s5 :: TI%E#5HANDLIN-'
/ stat!s5 : TI%E#5IDLE;
G 8
In !ine 1, o/ Pro'ram 13)3* t&e /unction e*pire&e' is ure 1irtual)
T&ere/ore* deri1ed instantiable classes o/ class TimerHandler are resonsible
/or ro1idin' eAiration actions by o1erridin' t&is /unction) Cor eAamle* class
%yTimer below deri1es /rom class TimerHandler and o1errides /unction
e*pire&e'<
void %yTimer99e*pire&Event
N
e'
7
print"&H%yTimer (as j!st e*piredCCTnH';
8
w&ic& rints t&e statement F%yTimer (as j!st e*piredCCG on t&e screen
uon timer eAiration)
%0=%=*=0 'nterface 4unctions to Start3 Restart3 an $ance# a Timer
T&e details o/ /unction sc(ed&delay' o/ class TimerHandler is s&own
in Pro'ram 13)3) Cunction sc(ed&delay' takes one inut ar'ument Fdelay*G
and sets t&e timer to eAire at FdelayG seconds in t&e /uture by /eedin' FdelayG
into
13)1 Timers :1#
Program %0=0 Cunction sc(ed o/ class TimerHandler
MMUMnsMcommonMtimerJ(andlerIcc
2 void TimerHandler99sc(ed&do!ble delay'
1 7
3 i" &stat!s5 C: TI%E#5IDLE' 7
= "print"&stderr)HCo!ldnZt sc(ed!le timerH';
> abort&';
A 8
B 5sc(ed&delay';
/ stat!s5 : TI%E#5PENDIN-;
G 8
/unction 5sc(ed&delay' ?!ine 2@) Note t&at t&e /unction sc(ed&delay'
must be in1oked w&en t&e Fstat!s5G o/ t&e timer is TI%E#5IDLE) Ot&erwise*
!ines
: and 3 will s&ow an error messa'e and eAit t&e ro'ram)
Pro'ram 13)8 s&ows t&e details o/ /unctions resc(ed&delay' and
cancel&' o/ class TimerHandler) Cunction resc(ed&delay' is 1ery
similar to /unction sc(ed&delay') In /act* w&en in1oked wit& Fstat!s5G
V TI%E#5PENDIN-* it does t&e same as /unction sc(ed&delay' does ?i)e)*
starts t&e timer@) Howe1er* w&en stat!s5:TI%E#5PENDIN-?!ine 3@ H
meanin' Fevent5G was laced on t&e simulation timeline be/ore t&e in1ocation H
it remo1es t&e timer eAiration e1ent /rom t&e simulation time line* by
in1okin' /unction
5cancel&'* and ?re@starts t&e timer ?!ines : and 3*
resecti1ely@)
Program %0=6 Cunctions resc(ed and cancel o/ class TimerHandler
MMUMnsMcommonMtimerJ(andlerIcc
2 void TimerHandler99resc(ed&do!ble delay'
1 7
3 i" &stat!s5 :: TI%E#5PENDIN-'
= 5cancel&';
> 5sc(ed&delay';
A stat!s5 : TI%E#5PENDIN-;
B 8
/ void TimerHandler99cancel&'
G 7
20 i" &stat!s5 C: TI%E#5PENDIN-' 7
22 III
21 abort&';
23 8
2= 5cancel&';
2> stat!s5 : TI%E#5IDLE;
2A 8
:1" 13 (elated Heler Classes
!ines "H18 o/ Pro'ram 13)8 s&ow t&e details o/ /unction cancel&' o/ class
TimerHandler) Cunction cancel&' in1okes /unction 5cancel&' in
!ine
1: to remo1e t&e endin' timer eAiration e1ent /rom t&e simulation timeline)
Cunction cancel&' must not be in1oked* w&en Fevent5G is not on t&e simu9
lation timeline ?i)e)* Fstat!s5G is eit&er TI%E#5IDLE or
TI%E#5HANDLIN-@) Ot&erwise* NS2 will s&ow an error messa'e on t&e screen
and eAit t&e ro'ram ?!ines 11 and 12@)
%0=%=*=6 $ross.Referencing a Timer with Another ,b1ect
In most cases* t&e use/ulness o/ a timer stands out w&en it is cross9re/erenced wit&
anot&er obBect) In t&is case* t&e obBect uses a timer as a waitin' tool* w&ic& starts*
restarts* and cancels t&e waitin' rocess as necessary) T&e timer* on t&e ot&er
&and* in/orms t&e obBect o/ timer eAiration* uon w&ic& t&e obBect may take
eAiration actions)
4 tyical cross9re/erence between a timer and an obBect can be created as
/ollows<
1) .eclare t&e timer as a 1ariable o/ t&e obBect class)
2) .eclare a ointer to t&e obBect as a member o/ t&e timer class)
3) .e/ine a non9de/ault constructor /or t&e timer class) Store t&e inut ar'ument o/
t&e constructor in its member ointer 1ariable ?w&ic& oints to t&e associated
obBect@)
:) Instantiate a timer obBect /rom wit&in t&e constructor o/ t&e associated obBect)
0se t&e non9de/ault constructor o/ t&e timer class de/ined abo1e) Ceed t&e
ointer Ft(isG ?i)e)* t&e ointer to t&e obBect@ as an inut ar'ument to t&e
constructor o/ t&e timer)
6e now conclude t&is section wit& a simle timer
eAamle)
E%ample 1** Consider a rocess o/ countin' t&e number o/ customers w&o enter
a store durin' a day) !et class Store reresent a con1enience store ?i)e)* an
obBect class@* and let class StoreHo!r reresent t&e number o/ oenin' &ours
o/ a day ?i)e)* a timer class@) T&e oenin' &ours is seci/ied w&en t&e store is
oened) T&e obBecti1e &ere is to count t&e number o/ 1isitin' customers durin' a
day* and rint out t&e result w&en t&e store is closed)
Classes Store and
StoreHo!r
Crom Pro'ram 13)2* class Store also &as t&ree 1ariables) Cirst* F(o!rs5G ?!ine
12@ contains oenin' &ours o/ t&e store and is set to Jero at t&e construction)
Second* Fco!nt5G ?!ine 1"@ records t&e number o/ customers w&o &a1e entered
t&e store so /ar and is set to Jero at t&e construction) Cinally* 1ariable Ftimer5G
is a StoreHo!r obBect) Cunction close&' ?!ines 12 and 13@ o/ class
Store is in1oked w&en t&e store is bein' closed) It rints out t&e oenin'
&ours and
13)1 Timers :21
Program %0=5 .eclaration o/ classes Store and StoreHo!r
MMstoreI(
2 class Store;
1 class StoreHo!r 9 p!blic TimerHandler 7
3 p!blic9
= StoreHo!r&Store
N
s' 7 store5 : s; 8;
> virt!al void e*pire& Event
N
e ';
A protected9
B Store
N
store5;
/ 8;
G class Store 9 p!blic TclObject 7
20 p!blic9
22 Store&' 9 timer5&t(is' 7 (o!rs5 : J2; co!nt5 : 0; 8;
21 void close&'7
23 print"&HT(e n!mber o" c!stomers d!rin$
E1I1" (o!rs is EdTnH) (o!rs5)co!nt5';
2= 8;
2> int command&int ar$c) const c(ar
N
const
N
ar$v';
2A protected9
2B do!ble (o!rs5;
2/ int co!nt5;
2G StoreHo!r timer5;
10 8
number o/ 1isitin' customers /or today on t&e screen) .eclared in !ines 1H"* class
StoreHo!r &as only one 1ariable Fstore5G ?!ine 2@ w&ic& is a ointer to a
Store obBect)
Cross9(e/erencin' Store and StoreHo!r
ObBects
T&e rocess o/ cross9re/erencin' a Store obBect and a StoreHo!r obBect
is s&own in Ci') 13):) T&e constructor o/ class Store constructs its 1ariable
Ftimer5G wit& t&e ointer Ft(isG to t&e Store obBect ?see !ine 11@) T&e
constructor o/ class StoreHo!r stores t&e inut ointer in its 1ariable
Fstore5)G Since t&e inut ar'ument is t&e ointer to t&e Store obBect* t&e
constructor o/ t&e StoreHo!r obBect essentially sets t&e 1ariable Fstore5G to
oint back to t&e Store obBect)
.ue to t&e cross9re/erencin'* t&e comiler needs to reco'niJe one o/ t&ese two
classes w&en declarin' anot&er) !ine 1 &els t&e comiler reco'niJe class Store
w&en comilin' !ine 2) 4/ter comilin' !ine 2* t&e comiler reco'niJes class
StoreHo!r and can comile !ine 1# wit&out error)
It is also imortant to note t&at w&en comilin' !ines 2H"* t&e comiler reco'9
niJes only Store class name) 4ny attemt to in1oke /unctions ?e)')*
close&'@
o/ class Store will result in a comilation error) T&is is t&e reason w&y we
need
:2, 13 (elated Heler Classes
4ig= %0=/ 4 dia'ram w&ic&
reresents t&e rocess o/
cross9re/erencin' a Store
obBect and a StoreHo!r
obBect
Program %0=7 Cunction e*pire o/ class StoreHo!r as well as OTcl
Commands
open and ne,Jc!stomer o/ class
Store
MMstoreIcc
2 void StoreHo!r99e*pire&Event
N
' 7
1 store5JKclose&';
3 8;
= int Store99command&int ar$c) const c(ar
N
const
N
ar$v'
> 7
A i" &ar$c :: 3' 7
B i" &strcmp&ar$v?2@) HopenH' :: 0' 7
/ (o!rs5 : atoi&ar$v?1@';
G co!nt5 : 0;
20 timer5Isc(ed&(o!rs5';
22 ret!rn &TCL5OV';
21 8
23 8 else i" &ar$c :: 1' 7
2= i" &strcmp&ar$v?2@) Hne,Jc!stomerH' :: 0' 7
2> co!nt544;
2A ret!rn &TCL5OV';
2B 8
2/ 8
2G ret!rn TclObject99command&ar$c)ar$v';
10 8
to searate CCC ro'rams into &eader and CCC /iles) 4'ain* since a &eader /ile
is included at t&e to o/ a CCC /ile* t&e comiler /irst 'oes t&rou'& t&e &eader /ile
and reco'niJes all t&e 1ariables and /unctions seci/ied in t&e &eader /ile) 6it&
t&is knowled'e* t&e comiler can comile t&e CCC /ile wit&out error)
.e/inin' EAiration 4ctions
.eri1ed /rom class TimerHandler* class StoreHo!r o1errides /unction
e*pire& e' as s&own in !ines 1H3 o/ Pro'ram 13)") 4t t&e eAiration* t&e
timer ?i)e)* StoreHo!r obBect@ simly in1okes /unction close&' o/ t&e
associated Store obBect)
13)1 Timers :23
Creatin' OTcl Inter/ace
6e bind t&e CCC class Store to an OTcl class wit& t&e same name usin' a
main' class StoreClass s&own in Pro'ram 13)#) !ines :H2, in Pro'ram
13)" also s&ow OTcl inter/ace commands open/(o!rs' and ne,Jc!stomer/')
6it& oenin' &ours F(o!rsG as an inut ar'ument* t&e OTcl command
open/(o!rs' ?!ines "H11@ is in1oked w&en t&e store is oened) !ine " stores
t&e oenin' &ours in 1ariable F(o!rs5*G !ine # resets t&e number o/ 1isitin'
customers to Jero* and !ine 1, tells Ftimer5G to eAire at F(o!rs5G &ours in
/uture) T&e OTcl command ne,Jc!stomer/' is in1oked as a customer enters t&e
store) In !ine 13* t&is command simly increases Fco!nt5G by one) 4'ain* at t&e
timer eAiration* t&e timer in1okes /unction close&' t&rou'& t&e ointer
Fstore5G and rints out t&e oenin' &ours ?i)e)* F(o!rs5G@ as well as t&e
number o/ 1isitin' customers ?i)e)* Fco!nt5G@ /or today ?see /unction
e*pire&e' in !ine 2 o/ Pro'ram 13)"@)
Program %0=8 4 main' class StoreClass w&ic& binds CCC and OTcl
classes
Store
MMstoreIcc
2 static class StoreClass 9 p!blic TclClass 7
1 p!blic9
3 StoreClass&' 9 TclClass&HStoreH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, Store';
A 8
B 8 class5store;
Testin' t&e Codes
4/ter de/inin' /iles storeIcc and storeI(* we include storeIo to t&e
%akeQile and run FmakeG at NS2 root directory to include classes Store
and StoreHo!r into NS2 ?see Sect) 2)2@)
.e/ine a test Tcl simulation scrit in a /ile storeItcl)
MMstoreItcl
2 set ns ?ne, Sim!lator@
1 set my5store ?ne, Store@
3 Pmy5store open 20I0
= Pns at 2 HPmy5store ne,Jc!stomerH
> Pns at > HPmy5store ne,Jc!stomerH
A Pns at A HPmy5store ne,Jc!stomerH
B Pns at / HPmy5store ne,Jc!stomerH
/ Pns at 22 HPmy5store ne,Jc!stomerH
G Pns r!n
:22 13 (elated Heler Classes
6e run t&e scrit storeItcl and obtain t&e /ollowin' results<
KKns storeItcl
T(e n!mber o" c!stomers d!rin$ 20I0 (o!rs is =
Crom t&e abo1e scrit* w&en !ine 2 creates a Store obBect* NS2 automati9
cally creates a s&adow CCC Store ObBect) !ine 3 in1okes an OTcl command
open wit& inut ar'ument 1,),* essentially oenin' t&e store /or 1,), &) Crom
Pro'ram 13)"* t&e OTcl command open/20I0' and tells t&e associated timer to
eAire at 1,), & in /uture* and clears t&e 1ariable Fco!nt5)G !ines :H" in1oke
command ne,Jc!stomer/' at 1st* 3t&* 8t&* "t&* and 11t& &ours) Eac& o/ t&ese
lines increases t&e number o/ 1isitin' customers ?i)e)* Fco!nt5G@ by one) +y t&e
end o/ 11t& &our in /uture* 1ariable Fco!nt5G s&ould be 3) Howe1er* t&e ro'ram
s&ows t&at t&e number o/ 1isitin' customers is :) T&is is because t&e timer eAires
and in1okes t&e /unction close&' at t&e 1,t& &our)
1+.1.$ ,!idelines for Ipleenting Tiers in %S2
6e now summariJe t&e rocess o/ de/inin' a new timer) Suose t&at we would
like to de/ine a new timer class StoreHo!r) Suose /urt&er t&at a Store
obBect is resonsible /or startin'* restartin'* and cancelin' t&e StoreHo!r
obBect* and /or takin' eAiration actions) T&en* t&e imlementation o/ t&e abo1e
timer classes roceeds as /ollows<
Crom Class StoreHo!r
Step > .esi'n class structure<
H .eri1e class StoreHo!r /rom class TimerHandler)
H .eclare a ointer ?e)')* Fstore5G@ to class Store) T&e ublic /unction o/
class Store is accessible t&rou'& t&e abo1e ointer ?e)')*
Fstore5G@
Step 2> +ind t&e re/erence to class Store in t&e
constructor)
Step $> .e/ine eAiration actions in t&e /unction
e*pire&e')
Crom Class Store
Step > .esi'n class structure<
H .eri1e class Store /rom class TclObject only if an inter/ace to OTcl
is necessary)
H .eclare a StoreHo!r 1ariable ?e)')* Ftimer5G@ as a member 1ariable)
13)2 Imlementation o/ (andom Numbers in NS2 :23
Step 2> Crom wit&in t&e constructor instantiate t&e abo1e StoreHo!r
1ariable
?e)')* Ftimer5G@ wit& t&e ointer Ft(is)G
4t runtime* we only need to instantiate a Store obBect) T&e internal mec&anism
o/ class Store will automatically create and con/i'ure a StoreHo!r obBect)
4lso* we do not need any 'lobal ?or OTcl@ re/erence to t&e StoreHo!r obBect*
since it is usually maniulated by class Store)
%0=2 'm&#ementation of Ranom Numbers in NS2
T&is section demonstrates imlementation o/ random number 'enerators in NS2)
In rincile* NS2 uses so9called (andom Number Lenerator ?(NL@ to 'enerate
random numbers) 4n (NL seDuentially icks numbers /rom a stream o/ seudo9
random numbers) 4 set o/ 'enerated random numbers is c&aracteriJed by t&e oint
w&ere t&e (NL starts ickin' t&e numbers H called Fseed)G +y de/ault* NS2 sets
t&e seed to 1) T&ere/ore* t&e results obtained /rom e1ery run are essentially t&e
same)
(andom numbers can also be trans/ormed to con/orm to a 'i1en distribu9
tion) Suc& a trans/ormation is carried out t&rou'& instrocs in t&e OTcl do9
main* and t&rou'& classes deri1ed /rom class #andomSariable in t&e CCC
domain) 6e will discuss t&e details o/ (NLs and t&e seedin' mec&anism in
Sects) 13)2)1 and 13)2)2* resecti1ely) Section 13)2)3 s&ows t&e imlementation
o/ (NLs in NS2) Section 13)2): discusses di//erent simulation scenarios* w&ere
(NLs are set di//erently) Section 13)2)3 eAlains t&e imlementation o/ a CCC
class #andomSariable w&ic& trans/orms random numbers accordin' to a
'i1en distribution) Cinally* Sect) 13)2)8 'i1es a 'uideline to de/ine a new (NL and
a new random 1ariable in NS2)
1+.2.1 Rando %!-er ,eneration
NS2 'enerates random numbers by seDuentially ickin' numbers /rom a stream o/
seudo9random number ?as discussed in Sect) 1)3)1@) It uses t&e com'ined multiple
recursive generator ?%(L32k3a@ roosed by !5Ecuyer ?1###@ as a seudo9
random number 'enerator) Lenerally seakin'* an %(L32k3a 'enerator contains
streams o/ seudo9random numbers /rom w&ic& t&e numbers icked seDuentially
seem to be random) In Ci') 13)3* an %(L32k3a 'enerator ro1ides 1<" 1,
1#
indeendent streams* eac& o/ w&ic& consists o/ 2<3 1,
13
substreams) Eac&
substream contains
2<8 1,
22
random numbers ?i)e)* t&e eriod o/ eac& substream is 2<8 1,
22
@) In
summary* an %(L32k3a 'enerator can create 3<1 1,
32
numbers w&ic& aear to
be random)
:2: 13 (elated Heler Classes
4ig= %0=0 Streams and
substreams o/ an %(L32k3a
'enerator
1+.2.2 Seeding a Rando %!-er ,enerator
4s mentioned in Sect) 1)3)1* FseedG is one o/ t&e main in'redients o/ (andom
Number Lenerator ?(NL@) !oosely seakin'* a seed seci/ies t&e location on a
stream o/ seudo9random numbers* w&ere an (NL starts ickin' random numbers
seDuentially) 6&en seeded di//erently* two (NLs start ickin' seudo9random
numbers /rom di//erent locations* and t&ere/ore 'enerate two distinct sets o/
random numbers) On t&e ot&er &and* i/ seeded wit& t&e same number* two (NLs
will start ickin' random numbers /rom t&e same location* and t&ere/ore 'enerate
t&e same set o/ random numbers)
+y de/ault* NS2 always uses only one OTcl 1ariable de"a!lt#N- as a
de/ault (NL* and always seeds t&e de"a!lt#N- wit& 1) T&ere/ore* t&e
simulation results /or e1ery run are essentially t&e same) To collect indeendent
simulation results* we must seed di//erent runs di//erently)
E%ample 1*2* In t&e /ollowin'* we run NS2 /or t&ree times to s&ow NS2 seedin'
mec&anism)
2 KKns
1 KKPde"a!lt#N- seed
3 2
= KKPde"a!lt#N- ne*tJrandom
> B1G13A
A KKPde"a!lt#N- ne*tJrandom
B 22G3B==B=B
/ KKe*it
13)2 Imlementation o/ (andom Numbers in NS2 :22
OOO #ESTA#T NS1 OOO
G KK ns
20 KKPde"a!lt#N- seed
22 2
21 KKPde"a!lt#N- ne*tJrandom
23 B1G13A
2= KKPde"a!lt#N- ne*tJrandom
2> 22G3B==B=B
2A KKe*it
OOO #ESTA#T NS1 OOO
2B KKns
2/ KKPde"a!lt#N- seed 202
2G KKPde"a!lt#N- ne*tJrandom
10 B1>10AG0
12 KKPde"a!lt#N- ne*tJrandom
11 30/A3B200
13 KKe*it
In t&e /irst run ?!ines 1H"@* t&e 1ariable de"a!lt#N- ?i)e)* t&e de/ault (NL@
is used to 'enerate two random numbers) In !ine 2* t&e instroc seed returns
t&e current seed w&ic& is set ?by de/ault@ to 1) !ines : and 8 use t&e instroc
ne*tJrandom/' to 'enerate two random numbers* 22#238 and 11#32::2:2*
resecti1ely) Cinally* !ine " eAits t&e NS2 en1ironment)
!ines #H18 reeat t&e rocess in !ines 1H") In !ines 1, and 11* we can obser1e
t&at t&e seed is still 1) 4s eAected* t&e /irst and t&e second random numbers
'enerated are 22#238 and 11#32::2:2* resecti1ely) T&ese two numbers are t&e
same as t&ose in t&e /irst run) Essentially* t&e /irst run and t&e second run 'enerate
t&e same results) To 'enerate di//erent results* we need to seed t&e simulation
di//erently)
!ines 12H22 s&ow t&e last run* w&ere t&e seed is set di//erently ?to 1,1@) T&e
/irst and t&e second random number 'enerated in t&is case are 2232,8#, and
3,"8321,,* resecti1ely) T&ese two numbers are di//erent /rom t&ose in t&e /irst
two runs* since !ine 13 sets t&e seed o/ t&e de"a!lt#N- to 1,1)
T&e key oints about seedin' t&e mec&anism in NS2 are as /ollows<
4 seed seci/ies t&e startin' location on a stream o/ seudo9random numbers*
and &ence c&aracteriJes an (NL)
To 'enerate two indeendent simulation results* eac& simulation must be
seeded di//erently)
4t initialiJation* NS2 creates a 1ariable de"a!lt#N- as t&e de/ault (NL*
and seeds t&e de"a!lt#N- wit& 1) +y de/ault* NS2 'enerates t&e same
simulation result /or e1ery run)
:28 13 (elated Heler Classes
6&en seeded wit& Jero* an (NL relaces t&e seed wit& current time o/ t&e day
and counter) .esite t&eir tendency to be indeendent* two runs may ick t&e
same seed and 'enerate t&e same result) To ensure indeendent runs* we must
seed t&e (NL manually)
NS2 seeds a new #N- obBect to t&e be'innin' o/ t&e neAt random stream)
T&ere/ore* e1ery #N- obBect is indeendent o/ eac& ot&er)
1+.2." OTcl and CCC Ipleentation
NS2 uses a CCC class #N- ?w&ic& is bound to an OTcl class wit& t&e same
name@ to 'enerate random numbers ?see Pro'ram 13)1,@) In most cases* it is not
necessary to understand t&e details o/ t&e %(L32k3a 'enerator) T&is section
s&ows only t&e key con/i'uration and imlementation in t&e OTcl and CCC
domains) T&e readers may /ind t&e detailed imlementation o/ an %(L32k3a
'enerator in /iles Tns$tools$rn')cc*&)
Program %0=%: 4 main' class #N-Class w&ic& binds OTcl and CCC classes
#N-
MMUMnsMtoolsMrn$Icc
2 static class #N-Class 9 p!blic TclClass 7
1 p!blic9
3 #N-Class&' 9 TclClass&H#N-H' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn&ne, #N-&'';
A 8
B 8 class5rn$;
%0=2=*=% ,Tc# $ommans an 'nst&rocs
In t&e OTcl domain* class #N- de/ines t&e /ollowin' OTcl commands<
seed/' (eturn t&e seed o/ (NL)
seed/n' Set t&e t&e seed o/ (NL to be Fn)G
ne*tJrandom/' (eturn a random number)
ne*tJs!bstream/' 4d1ance to t&e be'innin' o/ t&e neAt
substream)
resetJstartJs!bstream/' (eturn to t&e be'innin' o/ t&e current
substream)
13)2 Imlementation o/ (andom Numbers in NS2 :2#
normal/av$ std' (eturn a random number normally dis9
tributed wit& a1era'e Fav$G and stan9
dard de1iation Fstd)G
lo$normal/av$ std' (eturn a random number lo'9normally
distributed wit& a1era'e Fav$G and
standard de1iation Fstd)G
.e/ined in /ile Tns$tcl$lib$ns9random)tcl* t&e /ollowin' instrocs 'enerate
random numbers<
e*ponential/m!' (eturn a random number eAonentially
distributed wit& mean Fm!)G
!ni"orm/min ma*' (eturn a random number uni/ormly distributed in
?min)ma*@)
inte$er/k' (eturn a random inte'er uni/ormly distributed in
/0)2) III) kJ2')
%0=2=*=2 $CC 4unctions
In t&e CCC domain* t&e key /unctions o/ class #N- include ?see t&e details in
/iles
Tns$tools$rn')cc*&@<
set5seed&n' I/ n : 0* set t&e t&e seed o/ t&e
(NL to be current time and
counter) Ot&erwise* set t&e seed to
be Fn)G
seed&' (eturn t&e seed o/ t&e (NL)
ne*t&' (eturn a random int number in
/0)2)III) %AL5INT')
ne*t5do!ble&' (eturn a random do!ble number
in M,*1N)
reset5start5s!bstream&' %o1e to t&e be'innin' o/ t&e cur9
rent substream)
reset5ne*t5s!bstream&' %o1e to t&e be'innin' o/ t&e neAt
substream)
!ni"orm&k' (eturn a random int number uni9
/ormly distributed in /0)2) III)
kJ2')
!ni"orm&r' (eturn a random do!ble number
uni/ormly distributed in M,*rN)
!ni"orm&a)b' (eturn a random do!ble number
uni/ormly distributed in Ma*bN)
:2" 13 (elated Heler Classes
e*ponential&k' (eturn a random number eAonentially
distributed wit& mean Fk)G
normal&av$)std' (eturn a random number normally dis9
tributed wit& a1era'e Fav$G and standard
de1iation Fstd)G
lo$normal&av$)std' (eturn a random number lo'9normally
dis9 tributed wit& a1era'e Fav$G and
standard de1iation Fstd)G
1+.2.$ Randoness in Si!lation Scenarios
In most cases* a simulation /alls into one o/ t&e /ollowin' t&ree
scenarios)
%0=2=/=% -eterministic Setting
T&is tye o/ simulation is usually used /or debu''in') Its urose is to locate
ro'rammin' errors in t&e simulation codes or to understand comleA be&a1ior
o/ a certain network) In bot& cases* it is con1enient to run t&e ro'ram under a
deterministic settin' and 'enerate t&e same result reeatedly) +y de/ault* NS2
seeds t&e simulation wit& 1) T&e deterministic settin' is t&ere/ore t&e de/ault
settin' /or NS2 simulation)
%0=2=/=2 Sing#e.Stream Ranom Setting
T&e simlest /orm o/ statistical analysis is to run a simulation /or se1eral times and
comute statistical measures suc& as a1era'e and$or standard de1iation) +y
de/ault* NS2 always uses de"a!lt#N- wit& seed F1G to 'enerate random
numbers) To statistically analyJe a system* we need to 'enerate se1eral distinct
sets o/ results) T&ere/ore* we need to seed di//erent runs di//erently) In a sin'le9
stream random settin'* we need only one (NL) Hence* we may simly introduce
t&e di1ersity to eac& run by seedin' di//erent runs wit& di//erent 1alues <nK ?e)')*
in EAamle 13)2* !ine 1" seeds t&e de/ault (NL wit& 1,1@)
Pde"a!lt#N- seed <nK
w&ic& seeds t&e de/ault (NL wit& a number <nK)
%0=2=/=* Mu#ti&#e.Stream Ranom Setting
In some cases* we may need more t&an one indeendent random 1ariable /or
a simulation) Cor eAamle* we may need to 'enerate random 1alues o/ acket
13)2 Imlementation o/ (andom Numbers in NS2 :31
inter9arri1al time as well as acket siJe) T&ese two 1ariables s&ould be
indeendent and s&ould not s&are t&e same random stream) 6e can create two
indeendent (NL usin' Fne, #N-)G Since NS2 seeds eac& (NL wit& di//erent
random stream ?see Sect) 13)2)2@* t&e random rocesses wit& di//erent (NLs are
indeendent o/ eac& ot&er)
E%ample 1*$* Suose t&at t&e inter9arri1al time and acket siJe are
eAonentially distributed wit& mean 3 and uni/ormly distributed wit&in Q1,,O 3,,,
* resecti1ely) Print out t&e /irst /i1e random 1alues o/ inter9arri1al time and acket
siJe)
Tcl Simulation Scrit
2 Pde"a!lt#N- seed 202
1 set arrival#N- ?ne, #N-@
3 set si6e#N- ?ne, #N-@
= set arrival5 ?ne, #andomSariableME*ponential@
> Parrival5 set av$5 >
A Parrival5 !seJrn$ Parrival#N-
B set si6e5 ?ne, #andomSariableMDni"orm@
/ Psi6e5 set min5 200
G Psi6e5 set ma*5 >000
20 Psi6e5 !seJrn$ Psi6e#N-
22 p!ts HInterJarrival time Packet si6eH
21 "or 7set j 08 7Pj < >8 7incr j8 7
23 p!ts ?"ormat HEJ/I3" EJ=dH ?Parrival5 val!e@ T
?e*pr ro!nd&?Psi6e5 val!e@'@@
2= 8
(esults on t&e Screen
InterJarrival time Packet si6e
2I0=/ 2//0
BIG2G 22A
/I0A2 3A3>
=IAB> 1220
BI102 2>G0
T&e details o/ t&e abo1e Tcl simulation scrit are as /ollows) !ines : and 2
create an eAonentially random 1ariable
2
Farrival5G and a uni/ormly
distributed
2
6e will discuss t&e details o/ random 1ariables in t&e neAt section)
:3, 13 (elated Heler Classes
4ig= %0=6 4 sc&ematic dia'ram o/ class #andomSariable
random 1ariable Fsi6e5G w&ose arameters are de/ined in !ines 3 and 8 and
!ines "H1,* resecti1ely) !ines 11H1: rint out /i1e random numbers 'enerated by
Farrival5G and Fsi6e5)G In Sect) 13)2)3* we will see t&at t&e OTcl command
Fval!eG o/ class #andomSariable returns a random number* and t&e OTcl
command F!seJrn$G is used to seci/y an (NL /or a random 1ariable)
+y de/ault* de"a!lt#N-
3
is used to 'enerate random numbers /or bot&
Farrival5G and Fsi6e5)G In t&is case* !ines 2 and 3 create two indeendent
(NLs< Farrival#N-G and Fsi6e#N-)G NS2 seci/ies t&ese two 1ariables as
(NLs /or Farrival5G and Fsi6e5G usin' an OTcl command !seJrn$ in
!ines
8 and 1,* resecti1ely) Since t&e created (NL obBects are indeendent* random
1ariable Farrival5G and Fsi6e5G are indeendent o/ eac& ot&er)
1+.2.+ Rando
.aria-les
In NS2* a random 1ariable is a module w&ic& 'enerates random 1alues w&ose
statis9 tics /ollow a certain distribution) It uses an (NL to 'enerate random
numbers and trans/orms t&e 'enerated numbers to 1alues w&ic& con/orm to a
'i1en distribution) T&is imlementation is carried out in CCC abstract class
#andomSariable w&ose dia'ram and declaration are s&own in Ci') 13)8 and
Pro'ram 13)11* resec9 ti1ely)
Consider t&e declaration o/ class #andomSariable in Pro'ram 13)11) Class
#andomSariable contains a ointer Frn$5G ?!ine #@ to an #N- obBect ?used
to 'enerate random numbers@* and two ure 1irtual inter/ace /unctions< val!e&'
in !ine 3 and av$&' in !ine :) Cunction val!e&' 'enerates random numbers*
trans9 /orms t&e 'enerated numbers to 1alues con/ormin' to t&e underlyin'
distribution* and returns t&e trans/ormed 1alues to t&e caller) Cunction av$&'
returns t&e a1era'e 1alue o/ t&e underlyin' distribution) Since t&ese two /unctions
are ure 1irtual* t&ey must be o1erridden by all deri1ed instantiable classes o/ class
#andomSariable) T&e list o/ key built9in instantiable CCC classes as well as
t&eir bound OTcl classes is 'i1en in Table 13)2)
3
!ine 1 sets t&e seed o/ de"a!lt#N- to be 1,1) +ut we do not use de"a!lt#N- in t&is
eAamle)
13)2 Imlementation o/ (andom Numbers in NS2 :33
Program %0=%% .eclaration o/ class #andomSariable
MMUMnsMtoolsMranvarI(
2 class #andomSariable 9 p!blic TclObject 7
1 p!blic9
3 virt!al do!ble val!e&' : 0;
= virt!al do!ble av$&' : 0;
> int command&int ar$c) const c(ar
N
const
N
ar$v';
A #andomSariable&';
B int seed&c(ar
N
';
/ protected9
G #N-
N
rn$5;
20 8;
T ab # e %0 = 2 + u ilt 9in C CC and O Tcl random 1 ar i ab l e c l asses
C CC c l ass O Tcl c l ass
Dni"orm#andomSariable #andomSariableMDni"orm
E*ponential#andomSariable #andomSariableME*ponential
Pareto#andomSariable #andomSariableMPareto
ParetoII#andomSariable #andomSariableMParetoII
Normal#andomSariable #andomSariableMNormal
Lo$Normal#andomSariable #andomSariableMLo$Normal
Constant#andomSariable #andomSariableMConstant
HyperE*ponential#andomSariable #andomSariableMHyperE*ponential
Weib!ll#andomSariable #andomSariableMWeib!ll
Empirical#andomSariable #andomSariableMEmpirical
%0=2=0=% Ranom Number ;enerator
4 #andomSariable obBect uses its 1ariable Frn$5G to 'enerate random num9
bers) +y de/ault* e1ery random 1ariable uses t&e de"a!lt#N- as its (NL) 4s
s&own in Pro'ram 13)12* t&e constructor ?!ines 1H:@ o/ class #andomSariable
stores t&e de/ault (NL returned /rom t&e statement #N-99de"a!ltrn$&' in
t&e 1ariable Frn$5)G
To create multile independent random 1ariables* t&e 1ariable Frn$5G o/ eac&
random 1ariable must be indeendent o/ eac& ot&er) Crom EAamle 13)3* t&is can
be ac&ie1ed by creatin' and bindin' a dedicated (NL to eac& random 1ariable)
4s will be discussed in t&e neAt section* t&e rocess o/ bindin' an (NL to a
random 1ariable is carried out usin' t&e OTcl command !seJrn$ associated
wit& a #andomSariable obBect)
%0=2=0=2 ,Tc# $ommans
S&own in Pro'ram 13)12* class #andomSariable de/ines t&e /ollowin' two
OTcl commands* w&ic& can be in1oked /rom t&e OTcl domain<
val!e/'< (eturns a random number by in1okin' t&e /unction val!e&'
?!ines #H12@)
:32 13 (elated Heler Classes
Program %0=%2 T&e constructor* OTcl command val!e* and OTcl command
!seJrn$ o/ class #andomSariable
MMUMnsMtoolsMranvarIcc
2 #andomSariable99#andomSariable&'
1 7
3 rn$5 : #N-99de"a!ltrn$&';
= 8
MMUMnsMtoolsMranvarIcc
> int #andomSariable99command&int ar$c) const c(ar
N
const
N
ar$v'
A 7
B III
/ i" &ar$c :: 1' 7
G i" &strcmp&ar$v?2@) Hval!eH' :: 0' 7
20 tclIres!lt"&HEAeH) val!e&'';
22 ret!rn&TCL5OV';
21 8
23 8
2= i" &ar$c :: 3' 7
2> i" &strcmp&ar$v?2@) H!seJrn$H' :: 0' 7
2A rn$5 : &#N-
N
'TclObject99look!p&ar$v?1@';
2B III
2/ ret!rn&TCL5OV';
2G 8
10 8
12 III
11 8
!seJrn$/rn$'< Casts t&e inut ar'ument Frn$G to tye #N-
N
* and stores t&e
cast obBect in t&e 1ariable Frn$5G ?!ines 13H1#@)
Note t&at an eAamle use o/ t&e OTcl command !seJrn$/rn$' is s&own in
!ines 8 and 1, in EAamle 13)3)
Since class #andomSariable is abstract* it is not bound to t&e OTcl
domain) Howe1er* all its deri1ed classes are bound to t&e OTcl domain) Table
13)2 lists ten built9in CCC and OTcl random 1ariable classes)
%0=2=0=* "<&onentia# Ranom >ariab#e
4s an eAamle* consider imlementation o/ an eAonentially distributed random
1ariable in Pro'ram 13)13) Crom Table 13)2* NS2 imlements an eAonentially
dis9 tributed random 1ariable usin' t&e CCC class
E*ponential#andomSariable and t&e OTcl class
#andomSariableME*ponential)
Since an eAonential random 1ariable is comletely c&aracteriJed by an a1era'e
1alue* class E*ponential#andomSariable &as only one member 1ariable
Fav$5G ?!ine #@* w&ic& stores t&e a1era'e 1alue) 4t t&e construction ?see !ines
1"H2,@* class E*ponential#andomSariable binds its 1ariable Fav$5G to
an
13)3 +uilt9in Error %odels :33
Program %0=%* 4n imlementation o/ class E*ponential#andomSariable
MMUMnsMtoolsMranvarI(
2 class E*ponential#andomSariable 9 p!blic #andomSariable 7
1 p!blic9
3 virt!al do!ble val!e&';
= E*ponential#andomSariable&';
> do!ble
N
av$p&' 7 ret!rn Fav$5; 8;
A virt!al inline do!ble av$&' 7 ret!rn av$5; 8;
B void setav$&do!ble d' 7 av$5 : d; 8;
/ private9
G do!ble av$5;
20 8;
MMUMnsMtoolsMranvarIcc
22 static class E*ponential#andomSariableClass 9 p!blic
TclClass 7
21 p!blic9
23 E*ponential#andomSariableClass&' 9
TclClass& H#andomSariableME*ponentialH' 78
2= TclObject
N
create&int) const c(ar
N
const
N
' 7
2> ret!rn&ne, E*ponential#andomSariable&'';
2A 8
2B 8 class5e*ponentialranvar;
2/ E*ponential#andomSariable99E*ponential#andomSariable&'7
2G bind&Hav$5H) Fav$5';
10 8
12 do!ble E*ponential#andomSariable99val!e&'7
11 ret!rn&rn$5JKe*ponential&av$5'';
13 8
inst1ar Fav$5G in t&e OTcl domain) Cunctions av$&' in !ine 8 and av$p&'
in !ine 3 return t&e 1alue stored in Fav$5G and t&e address o/ Fav$5*G re9
secti1ely) Cunction setav$&d' in !ine 2 stores t&e 1alue in FdG into 1ariable
Fav$5)G Cunction val!e&' in !ines 21H23 returns a random number eAonen9
tially distributed wit& mean Fav$5)G It in1okes /unction e*ponential&av$5'
o/ 1ariable Frn$5*G /eedin' 1ariable Fav$5G as an inut ar'ument to obtain an
eAonentially distributed random number)
1+.2./ ,!idelines for Rando %!-er ,eneration in %S2
6e conclude t&is section by ro1idin' t&e /ollowin' 'uidelines /or imlementin'
randomness numbers in NS2<
:3: 13 (elated Heler Classes
1) .etermine t&e tye o/ simulation< deterministic settin'* sin'le9stream random
settin'* or multi9stream random settin')
2) Create (NL?s@ accordin' to t&e simulation tye)
3) I/ needed* create a random 1ariable
H .e/ine t&e in&eritance structure< CCC* OTcl* and main' classes)
H .e/ine /unction av$&' w&ic& returns t&e a1era'e 1alue o/ t&e distribution
to t&e caller)
H .e/ine /unction val!e&' w&ic& returns a random number con/ormin' to
t&e seci/ied distribution)
:) Seci/y an (NL /or eac& random 1ariable usin' an OTcl command !seJrn$
o/ class #andomSariable)
%0=* Bui#t.in "rror Moe#s
4n error model is an NS2 module w&ic& imoses error on acket transmission)
.eri1ed /rom class Connector* it can be inserted between two NsObBects) 4n
error model simulates acket error uon recei1in' a acket) I/ t&e acket is
simulated to be in error* t&e error model will eit&er dro t&e acket or mark t&e
acket wit& an error /la') I/ t&e acket is simulated not to be in error* on t&e ot&er
&and* t&e error model will /orward t&e acket to its downstream obBect) 4n error
model can be used /or bot& wired and wireless networks) Howe1er* t&is section
discusses t&e details o/ an error model t&rou'& a wired class SimpleLink only)
Program %0=%/ Class Error%odelClass w&ic& binds CCC and OTcl classes
Error%odel
MMUMnsM+!e!eMerrmodelIcc
2 static class Error%odelClass 9 p!blic TclClass 7
1 p!blic9
3 Error%odelClass&' 9 TclClass&HError%odelH' 78
= TclObject
N
create&int) const c(ar
N
const
N
' 7
> ret!rn &ne, Error%odel';
A 8
B 8 class5errormodel;
NS2 imlements error models usin' a CCC class Error%odel w&ic& is
bound to an OTcl class wit& t&e same name ?see Pro'ram 13)1:@) Class
Error%odel simulates +ernoulli error* w&ere transmission is simulated to be
eit&er in error or not in error) NS2 also ro1ides Error%odel classes wit&
more /unctionalities suc& as two9state error model) Tables 13)3 and 13): s&ow
NS2 built9in error models w&ose imlementation is in t&e CCC and OTcl domain*
resecti1ely)
13)3 +uilt9in Error %odels :32
Comple*T,oState Error%odelMComple* Contain two obBects o/ class
%arkov%odel
%!ltiStateError%odel
T,oState%arkov
Error%odelM%!ltiState
T,oStateError%odel
Error model wit& more t&an
T ab # e %0 = * + u ilt 9in erro r m ode ls w & i c & con t a i n C CC an d O T c l im l e m en t a ti o n
C CC c l as s O T c l c l as s . escr i ti o n
T,oStateError%odel Error%odelMT,oState Error9/ree and error9rone
states
two states
TraceError%odel Error%odelMTrace Imose error based on a trace
/ile
PeriodicError%odel Error%odelMPeriodic .ro ackets once e1ery n
ackets
ListError%odel Error%odelMList Seci/y t&e a list o/ ackets
to be droed
SelectError%odel SelectError%odel Selecti1e acket dro
S#%Error%odel S#%Error%odel Error model /or S(%
%ro!teError%odel Error%odelMTraceM Error model /or multicast
%ro!te routin'
Error%od!le Error%od!le Send ackets to
classi/ier rat&er t&an
Ftar$et5G
P-%Error%odel P-%Error%odel Error model /or PL%
L%SError%odel L%SError%odel Error model /or !%S
Tab#e %0=/ +uilt9in OTcl error models de/ined in /ile Tns$tcl$lib$ns9errmodel)tcl
OTcl class +ase class .escrition
Error%odelMDni"orm
Error%odelME*po
Error%odel
Error%odelMT,oState
0ni/orm error model
Two state error modelO
Eac& state is
reresented by an
eAonential
random 1ariable)
Error%odelMEmpirical Error%odelMT,oState Two state error modelO
Eac& state is
reresented by an
emirical random
1ariable)
Error%odelMT,oState%arkov Error%odelME*po Error%odelME*po
model w&ere t&e
state residence
time is eAonential
1+.".1 OTcl Ipleentation9 *rror Model Config!ration
In common wit& t&ose o/ most obBects* con/i'uration inter/aces o/ an error model
are de/ined in t&e OTcl domain) Suc& a con/i'uration includes arameter
con/i'uration and network con/i'uration)
:38 13 (elated Heler Classes
%0=*=%=% Parameter $onfiguration
T&ere are two ways to con/i'ure an error model obBect< t&rou'& bound 1ariables
and t&rou'& OTcl commands) Class Error%odel binds t&e /ollowin' CCC
1ariables to OTcl inst1ars wit& t&e same name<
enabled5 Set to 1 i/ t&is error model is acti1e* and set to , ot&erwise)
rate5 Error robability
delay5pkt5 I/ set to tr!e* t&e error model will delay ?rat&er t&an
dro@ t&e transmission o/ corruted ackets)
delay5 .elay time in case t&at delay5pkt5 is set to tr!e)
band,idt(5 0sed to comute acket transmission time
markecn5 I/ set to tr!e* t&e error model will mark error /la'
?rat&er t&an dro@ in /la' &eader o/ t&e corruted acket)
T&e second con/i'uration met&od is t&rou'& t&e /ollowin' OTcl commands
w&ose inut ar'uments are stored in ar$s<
!nit/ar$' Store ar$ in CCC 1ariable F!nit5)G
ranvar/ar$' Store ar$ in CCC 1ariable Franvar5)G
QECstren$t(/ar$' Store ar$ in CCC 1ariable
QECstren$t(5)
datapktsi6e/ar$' Store ar$ in CCC 1ariable
Fdatapktsi6e5)G
cntrlpktsi6e/ar$' Store ar$ in CCC 1ariable
Fcntrlpktsi6e5)G
eventtrace/ar$' Store ar$ in CCC 1ariable Fet5)G
4mon' t&e abo1e OTcl commands* !nit/'* ranvar/'* and QEC
stren$t(/'* w&en takin' no inut ar'ument* return 1alues stored in F!nit5*G
Franvar5*G and FQECstren$t(5*G resecti1ely)
%0=*=%=2 Network $onfiguration
4s a Connector obBect* an error model can be inserted into a network to
simulate acket errors) OTcl de/ines two airs o/ instrocs to insert an error
model into a SimpleLink obBect ?see Sect) 2)1@) Eac& air consists o/ one
instroc /rom class SimpleLink and one instroc /rom class Sim!lator
as s&own below ?see Ci') 13)2@<
SimpleLink99errormod!le/em'< Inserts an error model FemG ri'&t a/ter
t&e &ead o/ a SimpleLink obBect)
13)3 +uilt9in Error %odels :3#
4ig= %0=5 Instrocs errormod!le and insertJlinkloss o/ class SimpleLink
Sim!lator99lossmodel/lossobj "rom to'< EAecutes FerrorJ
mod!leG/rom wit&in t&e SimpleLink obBect w&ic& connects node F"romG
to node Fto)G
SimpleLink99insertJlinkloss/em'< Inserts an error model FemG ri'&t
a/ter inst1ar Flink5G o/ t&e SimpleLink obBect)
Sim!lator99linkJlossmodel/lossobj "rom to'< EAecutes t&e in9
stroc FinsertJlinkloss/III'G /rom wit&in t&e SimpleLink obBect
w&ic& connects node F"romG to node Fto)G
Pro'ram 13)13 s&ows t&e details o/ instroc errormod!le/em' o/ class
SimpleLink* w&ic& inserts t&e inut error model ?e)')* FemG@ immediately a/ter
t&e link5s &ead) !ines 8 and 2 store t&e inut error model ?i)e)* FemG@ in inst1ar
Ferrmod!le5)G !ine " inserts t&e inut error model neAt to t&e link5s &ead by
in1okin' instroc addJtoJ(ead/em'* and !ine # sets t&e dro tar'et o/ t&e inut
error model FemG to Fdrop(ead5)G
Program %0=%0 Instroc errormod!le o/ class SimpleLink* and instroc
addJtoJ(ead o/ cla ss Link
MMUMnsMtclMlibMnsJlinkItcl
2 SimpleLink instproc errormod!le ar$s 7
1 Psel" instvar errmod!le5 +!e!e5 drop(ead5
3 i" 7 Par$s :: HH 8 7
= ret!rn Perrmod!le5
> 8
A set em ?linde* Par$s 0@
B set errmod!le5 Pem
/ Psel" addJtoJ(ead Pem
G Pem dropJtar$et Pdrop(ead5
20 8
22 Link instproc addJtoJ(ead 7 connector 8 7
21 Psel" instvar (ead5
23 Pconnector tar$et ?P(ead5 tar$et@
2= P(ead5 tar$et Pconnector
2> 8
:3" 13 (elated Heler Classes
In !ines 11H13 o/ Pro'ram 13)13* instroc addJtoJ(ead/connector'
inserts t&e inut ar'ument FconnectorG between link5s &ead ?i)e)* t&e inst1ar
F(ead5G@ and tar'et o/ t&e link5s &ead ?see !ines 13 and 1:@)
Pro'ram 13)18 s&ows t&e details o/ instroc insertJlinkloss/em'*
w&ic& inserts t&e inut error model a/ter t&e inst1ar Flink5)G !ine 8 stores
t&e inut error model in a local 1ariable Fem)G !ines 2H# delete t&e inst1ar
Flink5errmod!le5G i/ it eAists) T&en !ine 1, stores t&e 1ariable FemG in
t&e inst1ar Flink5errmod!le5)G !ines 11 and 12 insert t&e 1ariable FemG
immediately a/ter t&e inst1ar Flink5)G Cinally* !ine 13 sets t&e dro tar'et o/ t&e
1ariable FemG to be t&e inst1ar Fdrop(ead5)G
Program %0=%6 4n instroc insertJlinkloss o/ class SimpleLink
MMUMnsMtclMlibMnsJlinkItcl
2 SimpleLink instproc insertJlinkloss ar$s 7
1 Psel" instvar link5errmod!le5 +!e!e5 drop(ead5 link5
3 i" 7 Par$s :: HH 8 7
= ret!rn Plink5errmod!le5
> 8
A set em ?linde* Par$s 0@
B i" ?in"o e*ists link5errmod!le5@ 7
/ delete link5errmod!le5
G 8
20 set link5errmod!le5 Pem
22 Pem tar$et ?Plink5 tar$et@
21 Plink5 tar$et Pem
23 Pem dropJtar$et Pdrop(ead5
2= 8
In most cases* a SimpleLink obBect is inaccessible /rom a Tcl sim9
ulation scrit) T&ere/ore* class Sim!lator ro1ides inter/ace instrocs
lossmodel/III' and linkJlossmodel/III' to in1oke instrocs errorJ
mod!le/em' and insertJ linkloss/em'* resecti1ely* o/ class
SimpleJ Link)
:
T&e details o/ bot& t&e instroc lossmodel/lossobj "rom to' and t&e
instroc linkJlossmodel/lossobj "rom to' o/ class Sim!lator are
s&own in Pro'ram 13)12* w&ere t&ey insert an error model FlossobjG into t&e
link w&ic& connect a node F"romG to a node Fto)G !ines 2 and 8 in1oke instroc
link/"rom to' o/ class Sim!lator) In !ine 1"* t&is instroc returns t&e
Link obBect w&ic& connects a node F"romG to a node Fto)G !ines 3 and 2 t&en
insert an error model into t&e returned Link obBect* by eAecutin'
errormod!le/em' and insertJlinkloss/em'* resecti1ely)
:
Caution< T&e details o/ instroc insertJlinkloss &as been c&an'ed sli'&tly since NS
1ersion 2)33) T&e con/i'uration ?as in Ci') 13)2@ mi'&t look di//erent under di//erent 1ersions o/
NS2)
13)3 +uilt9in Error %odels ::1
Program %0=%5 Instrocs lossmodel* linkJlossmodel* and link o/ class
Sim!lator
MMUMnsMtclMlibMnsJlibItcl
2 Sim!lator instproc lossmodel 7lossobj "rom to8 7
1 set link ?Psel" link P"rom Pto@
3 Plink errormod!le Plossobj
= 8
> Sim!lator instproc linkJlossmodel 7lossobj "rom to8 7
A set link ?Psel" link P"rom Pto@
B Plink insertJlinkloss Plossobj
/ 8
G Sim!lator instproc link 7 n2 n1 8 7
20 Psel" instvar Node5 link5
22 i" 7 C?catc( HPn2 in"o class NodeH@ 8 7
21 set n2 ?Pn2 id@
23 8
2= i" 7 C?catc( HPn1 in"o class NodeH@ 8 7
2> set n1 ?Pn1 id@
2A 8
2B i" ?in"o e*ists link5&Pn29Pn1'@ 7
2/ ret!rn Plink5&Pn29Pn1'
2G 8
10 ret!rn HH
12 8
1+.".2 CCC Ipleentation9 *rror Model Si!lation
T&e internal mec&anism o/ an error model is seci/ied in t&e CCC domain)
4s s&own in Pro'ram 13)1"* CCC class Error%odel deri1es /rom class
Connector) It uses acket /orwardin'$droin' caabilities ?e)')* a 1ariable
Ftar$et5G and a /unction recv&p)('@ in&erited /rom class Connector* and
de/ine error simulation mec&anism)
%0=*=2=% >ariab#es
T&e key 1ariables o/ class Error%odel are 'i1en
below<
enable5 Set to 1 i/ t&is error model is acti1e* and set to , ot&erwise
rate5 Error robability
delay5 Time used to delay ?rat&er t&an droin'@ a corruted
acket
band,idt(5 Transmission bandwidt& used to comute acket trans9
mission time
::, 13 (elated Heler Classes
Program %0=%7 .eclaration o/ class Error%odel
MMUMnsM+!e!eMerrmodelI(
2 en!m ErrorDnit 7 ED5TI%E:0) ED5.[TE) ED5PVT) ED5.IT 8;
1 class Error%odel 9 p!blic Connector 7
3 p!blic9
= Error%odel&';
> virt!al void recv&Packet
N
) Handler
N
';
A virt!al void reset&';
B virt!al int corr!pt&Packet
N
';
/ inline do!ble rate&' 7 ret!rn rate5; 8
G inline ErrorDnit !nit&' 7 ret!rn !nit5; 8
20 protected9
22 int enable5;
21 ErrorDnit !nit5;
23 do!ble rate5;
2= do!ble delay5;
2> do!ble band,idt(5;
2A #andomSariable
N
ranvar5;
2B int QECstren$t(5;
2/ int datapktsi6e5;
2G int cntrlpktsi6e5;
10 do!ble
N
cntrlprb5;
12 do!ble
N
dataprb5;
11 Event intr5;
13 virt!al int command&int ar$c) const c(ar
N
const
N
ar$v';
1= int Corr!ptPkt&Packet
N
';
1> int Corr!pt.yte&Packet
N
';
1A int Corr!pt.it&Packet
N
';
1B do!ble PktLen$t(&Packet
N
';
1/ do!ble
N
Comp!te.itErrProb&int';
1G 8;
MMUMnsM+!e!eMerrmodelIcc
30 Error%odel99Error%odel&' 9 "irstTime5&2') !nit5&ED5PVT')
ranvar5&0') QECstren$t(5&2'
32 7
31 bind&Henable5H) Fenable5';
33 bind&Hrate5H) Frate5';
3= bind&Hdelay5H) Fdelay5';
3> 8
!nit5 Error unit ?ED5TI%E* ED5.[TE?de/ault@* ED5PVT* or
ED5.IT@
ranvar5 (andom 1ariable w&ic& simulates error
QECstren$t(5 Number o/ bits in a acket w&ic& can be corrected
datapktsi6e5 Number o/ bytes in a data acket
cntrlpktsi6e5 Number o/ bytes in a control acket
13)3 +uilt9in Error %odels ::3
dataprb5 4n array w&ose it& entry is t&e robability o/ &a1in' at
most i corruted data bits
cntrlprb5 4n array w&ose it& entry is t&e robability o/ &a1in' at
most most i corruted control bits
"irstTime5 Indicate w&et&er an error &as occurred)
intr5 4 Dueue callback obBect ?see Sect) 2)3)3@)
T&e 1ariable Frate5G seci/ies t&e error robability* w&ile t&e 1ariable
F!nit5G indicates t&e unit o/ Frate5)G I/ F!nit5G is ackets ?i)e)* ED5PVT@*
Frate5G will reresent acket error robability) I/ F!nit5G is bytes ?i)e)*
ED5.[TE@ or bits ?i)e)* ED5.IT@* Frate5G will reresent byte error robability
or bit error robability* resecti1ely)
%0=*=2=2 4unctions
T&e key /unctions o/ class Error%odel are 'i1en below<
rate&' (eturn t&e error robability stored in 1ari9
able Frate5)G
!nit&' (eturn t&e error unit stored in 1ariable
F!nit5)G
PktLen$t(&p' (eturn t&e len't& ?in error units@ o/ t&e
acket Fp)G
reset&' Set t&e 1ariable F"irstTime5G to 1)
recv&p)(' (ecei1e a acket FpG and a &andler F()G
corr!pt&p' (eturn 1$, i/ t&e transmission is in er9
ror$not in error)
Corr!ptPkt&p' (eturn 1$, i/ t&e transmission is in er9
ror$not in error)
Corr!pt.yte&p' (eturn 1$, i/ t&e transmission is in er9
ror$not in error)
Corr!pt.it&p' (eturn t&e number o/ corruted bits)
Comp!te.itErrProb&si6e' Comutes t&e cumulati1e distribution o/
&a1in' i: /,O O QECstren$t(5'
cor9 ruted bits)
::2 13 (elated Heler Classes
Program %0=%8 Cunction recv&p)(' o/ class Error%odel
MMUMnsM+!e!eMerrmodelIcc
2 void Error%odel99recv&Packet
N
p) Handler
N
('
1 7
3 (dr5cmn
N
c( : (dr5cmn99access&p';
= int error : corr!pt&p';
> i" &( FF &&error FF drop5' XX Ctar$et5'' 7
A do!ble delay : #andom99!ni"orm&/I0
N
c(JKsi6e&'M
band,idt(5';
B i" &intr5I!id5 < 0'
/ Sc(ed!ler99instance&'Isc(ed!le&() Fintr5)
delay';
G 8
20 i" &error' 7
22 c(JKerror&' X: error;
21 i" &drop5' 7
23 drop5JKrecv&p';
2= ret!rn;
2> 8
2A 8
2B i" &tar$et5' 7
2/ tar$et5JKrecv&p) (';
2G 8
10 8
%0=*=2=* Main Mechanism
T&e main mec&anism o/ an Error%odel obBect lies wit&in t&e acket recetion
/unction recv&p)(' s&own in Pro'ram 13)1#) 6&en recei1in' a acket* an
Error%odel obBect simulates acket error ?by in1okin' /unction
corr!pt&p' in !ine : o/ Pro'ram 13)1#@* and reacts to t&e error based on t&e
underlyin' con/i'uration) I/ an error occurs* !ine 11 will mark an error /la' in
t&e common acket &eader) T&en i/ Fdrop5G eAists* !ines 13 and 1: will dro
t&e acket and terminate t&e /unction) I/ t&e acket is not in error* on t&e ot&er
&and* /unction recv&p)(' will ski !ines 11H13 and will /orward t&e acket
to Ftar$et5G i/ it eAists) 4 cautionary note< since a corruted acket will
also be /orwarded to Ftar$et5G i/ Fdrop5G does not eAist* NS2 will not show
any error 'ut the simulation results might not 'e correctF
!ines 8H" in Pro'ram 13)1# are related to NS2 callback mec&anism discussed
in Sect) 2)3)3) Callback mec&anism is an NS2 tec&niDue to &a1e a downstream
obBect in1oke an ustream obBect alon' a downstream at&) Cor eAamle* a/ter
transmittin' a acket* a Dueue needs to wait until t&e acket lea1es t&e Dueue
?i)e)* wait /or a call'ack si'nal to release t&e Dueue /rom t&e blocked state@* be/ore
commencin' anot&er acket transmission) Crom Sect) 2)2* a LinkDelay obBect
uses t&e Sc&eduler to in/orm t&e Dueue o/ acket dearture ?i)e)* send a release
si'nal@ at t&e acket dearture time)
13)3 +uilt9in Error %odels ::3
4 callback rocess is imlemented by assin' t&e &andler ?(@ o/ an ustream
obBect ?e)')* t&e Dueue@ alon' wit& acket ?p@ to a downstream obBect t&rou'&
/unction recv&p)(') 0on recei1in' t&e &andler* an NsObBect reacts by eit&er
?1@ assin' t&e &andler to its downstream obBect and &oin' t&at t&e &andler will
be dealt wit& somew&ere alon' t&e downstream at&* or ?2@ immediately
sc&edulin' a callback e1ent at a certain time)
Condition ?1@ occurs w&en an ustream obBect asses down t&e &andler F(*G
and is waitin' /or a callback si'nal) Condition ?2@ indicates t&e case w&ere t&e
Error%odel obBect is resonsible /or sendin' a callback si'nal)
3
Condition ?2@
consists o/ t&e two /ollowin' subconditions) One is t&e case w&ere t&e acket
will be droed) 4not&er is w&en Ftar$et5G does not eAist) In t&ese cases* t&e
Error%odel will be t&e last obBect in a downstream at& w&ic& can deal wit&
t&e acket* and is t&ere/ore resonsible /or t&e callback mec&anism)
4ccordin' to !ine 3 in Pro'ram 13)1#* t&e Error%odel obBect c&ooses to
call back w&en bot& o/ t&e /ollowin' conditions are satis/ied<
1) Handler F(G eAists ?i)e)* nonJero@* and
2) Eit&er
?a@ Packet is in error and t&e 1ariable Fdrop5G eAists* and$or
?b@ T&e 1ariable Ftar$et5G does not eAist)
6&en c&oosin' to callback* !ine " sc&edules a callback e1ent a/ter a delay time
o/ FdelayG seconds) NS2 assumes t&at an error can occur in any lace in a acket
wit& eDual robability) Corresondin'ly* t&e time at w&ic& an error is materialiJed
is uni/ormly distributed in Q,O tA t * w&ere tA t is t&e acket transmission time
?!ine 8@)
%0=*=2=/ Simu#ating Transmission "rrors
In t&e re1ious section* we discussed &ow class Error%odel /orwards or dros
?or marks wit& an error /la'@ ackets based on t&e simulated error) T&is discusses
t&e details o/ /unction corr!pt&p' w&ic& simulates transmission error) Takin'
a acket ointer FpG as an inut ar'ument* t&e /unction corr!pt&p' returns
Jero and one i/ t&e transmission is simulated not to be and to be in error*
resecti1ely)
Pro'ram 13)2, s&ows t&e details o/ /unction corr!pt&p') T&e /unction
corr!pt&p' always returns Jero i/ t&e Error%odel obBect is disabled
?i)e)* enable5:0O see !ines : and 3@) Li1en t&at t&e Error%odel obBect is
enabled* t&e /unction corr!pt&p' returns a lo'ic 1alue ?i)e)* true or /alse@
deend9 in' on w&et&er t&e 1alue returned /rom t&e /unctions
Corr!ptPkt&p' in !ine 18* Corr!pt.yte&p' in !ine 1,*
Corr!pt.it&p' in !ines 13 and
1:* and Corr!ptTime&p' in !ine " is Jero* w&en F!nit5G is eDual to
3
I/ not* t&e Error%odel obBect will assi'n t&e resonsibility to its downstream obBect)
In t&is case* t&e &andler F(G s&ould be assed to t&e downstream obBect* by in1okin'
tar$et JKrecv&p)(')
::: 13 (elated Heler Classes
Program %0=2: Cunctions corr!pt Corr!ptPkt* Corr!pt.yte* and
PktLen$t( o/ class Error%odel
MMUMnsM+!e!eMerrmodelIcc
2 int Error%odel99corr!pt&Packet
N
p'
1 7
3 (dr5cmn
N
c( : HD#5C%N&p';
= i" &enable5 :: 0'
> ret!rn 0;
A s,itc( &!nit5' 7
B case ED5TI%E9
/ ret!rn &Corr!ptTime&p' C: 0';
G case ED5.[TE9
20 ret!rn &Corr!pt.yte&p' C: 0';
22 case ED5.IT9
21 c( : (dr5cmn99access&p';
23 c(JKerrbitcnt&' : Corr!pt.it&p';
2= ret!rn &c(JKerrbitcnt&' C: 0';
2> de"a!lt9
2A ret!rn &Corr!ptPkt&p' C: 0';
2B 8
2/ ret!rn 0;
2G 8
10 int Error%odel99Corr!ptPkt&Packet
N
'
12 7
11 do!ble ! : ranvar5 Y ranvar5JKval!e&' 9 #andom99
!ni"orm&';
13 ret!rn &! < rate5';
1= 8
1> int Error%odel99Corr!pt.yte&Packet
N
p'
1A 7
1B do!ble per : 2 J po,&2I0 J rate5) PktLen$t(&p'';
1/ do!ble ! : ranvar5 Y ranvar5JKval!e&' 9 #andom99
!ni"orm&';
1G ret!rn &! < per';
30 8
32 do!ble Error%odel99PktLen$t(&Packet
N
p'
31 7
33 i" &!nit5 :: ED5PVT'
3= ret!rn 2;
3> int byte : (dr5cmn99access&p'JKsi6e&';
3A i" &!nit5 :: ED5.[TE'
3B ret!rn byte;
3/ i" &!nit5 :: ED5.IT'
3G ret!rn /I0
N
byte;
=0 ret!rn /I0
N
byte M band,idt(5;
=2 8
13)3 +uilt9in Error %odels ::2
4ig= %0=7 Trans/ormin'
uni/orm distribution to
+ernoulli distribution
ED5PVT* ED5.[TE* ED5.IT* and ED5TI%E* resecti1ely) Similar to t&e
/unction corr!pt&p'* t&ese /unctions return a Jero and a nonJero 1alue i/ t&e
acket is not in error and is in error* resecti1ely)
In some cases* t&e acket error rocess in a communication link can be
modeled as &a1in' +ernoulli distribution) Suose t&at Franvar5G ?!ine 18 in
Pro'ram 13)1"@ is a random 1ariable w&ic& 'enerates uni/ormly distributed
random numbers F!G in t&e ran'e M,*1N) Crom Ci') 13)"* F!G could be any oint F
G in M,*1N wit& eDual robability) Li1en a t&res&old Frate5*G F!G will be in
M,*rate5@ wit& robability Frate5)G In ot&er words* to &a1e robability o/
Frate5G /or an e1ent ?e)')* acket error@* we need to 'enerate a uni/ormly
distributed random number F!*G and assume t&e occurrence o/ t&e e1ent i/ and only
i/ ! < rate5)
!ines 2,H:1 o/ Pro'ram 13)2, s&ow t&e details o/ /unctions Corr!ptPkt&p'*
Corr!pt.yte&p'* and pktLen$t(&p') Cunction Corr!ptPkt&p' in
!ines
2,H2: uses t&e abo1e met&od ?see Ci') 13)"@ to simulate acket error) In ot&er
words*
it 'enerates uni/ormly distributed random numbers F!G and assumes t&at a acket
is in error i/ and only i/ ! < rate5)
Cor /unction Corr!pt.yte&p'* t&e 1ariable Frate5G reresents byte
error robability) !ine 22 translates byte error robability to acket error
robability ?per@
8
and simulates acket error in t&e same way as t&e /unction
Corr!ptPkt&p' does)
Cunction PktLen$t(&p' in !ines 31H:, o/ Pro'ram 13)2, comutes t&e
len't& o/ a acket in t&e corresondin' F!nit5)G In articular* i/ F!nit5G is
ED5PVT* /unction PktLen$t(&p' will return 1 ?see !ine
3:@)
ED5.[TE* /unction PktLen$t(&p' will return t&e number o/ bytes in t&e
acket stored in /ield Fsi6e5G o/ t&e common acket &eader ?see !ines 33H32@)
ED5.ITS* /unction PktLen$t(&p' will return t&e number o/ bits in t&e
acket ?see !ine 3#@)
ED5TI%E ?i/ none o/ t&e abo1e matc&es@* /unction PktLen$t(&p' will
return t&e transmission time o/ t&e acket ?see !ine :,@)
Pro'ram 13)21 s&ows t&e details o/ /unction Corr!pt.it&p' o/ class
Error
%odel) 6&en t&is /unction is called /or t&e /irst time ?i)e)* F"irstTime5G is 1@*
8
Packet error robability is 1 )1 rate $
n
* w&ere Frate G is byte error robability and n U
::8 13 (elated Heler Classes
PktLen$t(&p' is number o/ bytes in a acket)
13)3 +uilt9in Error %odels ::2
!ines 3 and 8 recomute error robabilities /or a control acket and a data acket
and store t&e robabilities in Fcntrlprb5G and Fdataprb5*G resecti1ely)
T&e comutation is ac&ie1ed 1ia /unction Comp!te.itErrProb&si6e'
w&ic& takes t&e siJe o/ a control acket ?i)e)* si6e:cntrlpktsi6e5@ or
a data acket ?i)e)* si6e:datapktsi6e5@ as its inut ar'ument) T&e 1alues
stored in cntrlprb5?i@ and dataprb5?i@ denote t&e robability t&at at
most i bits are in error) !ine 2 t&en sets F"irstTime5G to Jero so t&at
/unction Corr!pt.it will ski !ines 3H2 w&en it is in1oked a'ain)
Cunction Corr!pt.it&p' comutes acket error robability based on eit&er
Fdataprb5G or Fcntrlprb5)G 4ny acket w&ose siJe is at least as lar'e as
Fdatapktsi6e5G is considered a data acket) In t&is case* !ine 1, stores
Fdataprb5G in Fdp"rG* later used to comute bit error robability) I/* on t&e
ot&er &and* t&e acket siJe is smaller t&an Fdatapktsi6e5*G it will be
considered a control acket* and Fcntrlpb5G will be stored in FdptrG as bit
error robability)
Program %0=2% Cunctions Corr!pt.it and Comp!te.itErrProb o/ class
Error%odel
MMUMnsM+!e!eMerrmodelIcc
2 int Error%odel99Corr!pt.it&Packet
N
p'
1 7
3 do!ble !)
N
dptr; int i;
= i" &"irstTime5 FF QECstren$t(5' 7
> cntrlprb5 : Comp!te.itErrProb&cntrlpktsi6e5';
A dataprb5 : Comp!te.itErrProb&datapktsi6e5';
B "irstTime5 : 0;
/ 8
G ! : ranvar5 Y ranvar5JKval!e&' 9 #andom99!ni"orm&';
20 dptr : &(dr5cmn99access&p'JKsi6e&' K: datapktsi6e5'
Y dataprb5 9 cntrlprb5;
22 "or &i : 0; i < &QECstren$t(5 4 1'; i44'
21 i" &dptr?i@ K !' break;
23 ret!rn&i';
2= 8
2> do!ble
N
Error%odel99Comp!te.itErrProb&int si6e'
2A 7
2B do!ble
N
dptr; int i;
2/ dptr : &do!ble
N
'calloc&&QECstren$t(5 4 1') si6eo"
&do!ble'';
2G "or &i : 0; i < &QECstren$t(5 4 2' ; i44'
10 dptr?i@ : comb&si6e) i'
N
po,&rate5)
&do!ble'i'
N
po,&2I0 J rate5) &do!ble'
&si6e J i'';
12 "or &i : 0; i < QECstren$t(5 ; i44'
11 dptr?i 4 2@ 4: dptr?i@;
13 dptr?QECstren$t(5 4 2@ : 2I0;
1= ret!rn dptr;
1> 8
::" 13 (elated Heler Classes
i
Since t&e 1alue stored in dptr?i@ is t&e robability t&at at most FiG bits are in
error* !ines 11 and 12 increment FiG until t&e robability eAceeds F!G and returns
FiG to t&e caller) In t&is case* t&e 1ariable FiG is t&e number o/ corruted bits)
T&e details o/ /unction Comp!te.itErrProb&si6e' are s&own in
Pro'ram 13)21) T&is /unction takes t&e acket siJe as an inut ar'ument and
returns an array FdptrG o/ do!ble w&ose i
t &
entry contains t&e robability o/
&a1in' at most i corruted bits) Li1en a acket siJe Fsi6e*G t&e robability o/
&a1in' eAactly i corruted bits is

si6e

)rate $
i
)1 rate $
si6eJi
*
as s&own
in !ine 2,* w&ere Frate5G is t&e bit error robability) !ines 21H23 comute t&e
cumulati1e summation o/ Fdprt)G Note t&at !ine 23 sets
dptr?QECstren$t(5
4 2@ to 1), since a acket is considered to be in error i/ t&e number o/
corruted bits is 'reater t&an QECstren$t(5)
1+."." ,!idelines for Ipleenting a %e& *rror Model in %S2
In order to imlement a new error model in NS2* we need to /ollow t&e t&ree stes
below<
1) .esi'n and create an error model class in OTcl* CCC* or bot& domains)
2) Con/i'ure t&e arameters o/ t&e error model obBect suc& as error robability
?rate5@* error unit ?!nit5@* and random 1ariable ?ranvar5@)
3) Insert an error model into t&e network ?e)')* usin' instroc lossmodel
/lossobj "rom to' or instroc linkJlossmodel/lossobj "rom
to' o/ class Sim!lator@)
E%ample 1*/* Consider t&e simulation scrit in Pro'ram #)1* w&ic& creates a
network as s&own in Ci') #)3) Include an error model wit& acket error robability
,)1 /or t&e link connectin' nodes n2 and
n3)
Tcl Simulation Script
2 set ns ?ne, Sim!lator@
1 set n2 ?Pns node@
3 set n1 ?Pns node@
= set n3 ?Pns node@
> Pns d!ple*Jlink Pn2 Pn1 >%b 1ms DropTail
A Pns d!ple*Jlink Pn1 Pn3 >%b 1ms DropTail
B Pns d!ple*Jlink Pn2 Pn1 >%b 1ms DropTail
/ set em ?ne, Error%odel@
G Pem set rate5 0I2
20 Pem !nit pkt
13): +it Oerations in NS2 ::#
4ig= %0=8 +it maskin'
22 Pem ranvar ?ne, #andomSariableMDni"orm@
21 Pem dropJtar$et ?ne, A$entMN!ll@
23 Pns linkJlossmodel Pem Pn2 Pn3
2= set !dp ?ne, A$entMDDP@
2> set n!ll ?ne, A$entMN!ll@
2A set cbr ?ne, ApplicationMTra""icMC.#@
2B Pns attac(Ja$ent Pn2 P!dp
2/ Pns attac(Ja$ent Pn3 Pn!ll
2G Pcbr attac(Ja$ent P!dp
10 Pns connect P!dp Pn!ll
12 Pns at 2I0 HPcbr startH
11 Pns at 200I0 HPcbr stopH
13 Pns r!n
w&ere !ines "H13 are included ?into t&e simulation scrit in Pro'ram #)1@ to
imose error on acket transmission) Note t&at t&e OTcl command !nit/!' sets
1ariable F!nit5G to t&e 1alue corresondin' to t&e inut ar'ument F!)G T&e
ossible 1alues o/ F!G include Ftime*G Fbyte*G Fpkt*G and Fbit)G
%0=/ Bit ,&erations in NS2
1+.$.1 2it Mas'ing
+it maskin' is a bit trans/ormation tec&niDue* w&ic& can be used /or 1arious
uroses) Li1en a mask* a 'it masking process trans/orms an original value to a
masked value ?see Ci') 13)#@) In t&is section* we will s&ow two eAamles o/ bit
maskin'< subnet maskin' and modulo maskin')
%0=/=%=% Subnet Masking
4 :9byte IP address can be di1ided into &ost address and network address) 6&ile a
&ost address identi/ies a &ost ?e)')* a comuter@* a network address c&aracteriJes a
:3, 13 (elated Heler Classes
'rou o/ &osts) 4 &ost is 'i1en a &ost IP address as its identi/ication and a :9byte
su'net mask w&ic& identi/ies its network) 4 subnet mask consists o/ all9one uer
bits and all9Jero lower bits ?i)e)* o/ /ormat F1 1, ,G@) Cor a 'i1en &ost IP
address and a subnet mask* t&e network IP address can be determined as /ollows<
Network IP 4ddress . Host IP 4ddress ] Subnet %ask ?13)1@
w&ere ] is a bitwise F4N.G oerator)
E%ample 1*1* 4 class9C ?i)e)* subnet mask . 233)233)233),@ &ost IP address
1,)1)2)3 &as t&e network IP address o/
)1,<1<2<3$])233<233<233<,$ . )1,]233$<)1]233$<)2]233$<)3],$ . 1,<1<2<,
?13)2@
In /act* all class9C IP addresses w&ose /irst t&ree bytes are 1,)1)2 &a1e t&e same
network address) Corresondin'ly* a class9C network address corresonds to 238
IP addresses)
Crom t&e abo1e eAamle* t&e ori'inal 1alue ?i)e)* &ost IP address@ 1,)1)2)3 is
masked ?usin' bitwise FandG@ wit& a mask 233)233)233), ?i)e)* class C subnet
mask@ suc& t&at t&e masked value ?i)e)* network IP address@ is 1,)1)2),)
%0=/=%=2 Mou#o Masking
%odulo is a remainder comutation rocess) Suose a . b c C d ) T&en aPc
. d * w&ere P is a modulo oerator) +it maskin' can also be used as a modulo
oerator wit& c . 2
n
w&ere n is a ositi1e inte'er)
To imlement a modulo maskin'* t&e uer and lower bits o/ a modulo mask
are set to conti'uous Jeros and conti'uous ones* resecti1ely ?i)e)* o/ /ormat
F, ,1 1G@* and t&e maskin' oeration is a bitwise F4N.G oeration)
Suose* an ori'inal 1alue is o/ /ormat AA<<AA* w&ere A can be Jero or one) T&e
modulo maskin' alies bitwise F4N.G to an ori'inal 1alue and t&e modulo
mask* and obtains t&e masked 1alue as /ollows<
ori'inal 1alue . A AA A
uer9bound mask . , ,1 1
masked 1alue . , ,A A)
Suose t&e number o/ one9bits o/ a modulo mask is n) T&e bits w&ose
ositions are 'reater t&an n are remo1ed durin' a maskin' rocess* and t&e
masked 1alue is bounded by 2
n
1) On t&e ot&er &and* t&e bits w&ose ositions are
not 'reater t&an n are ket unc&an'ed) T&ese lower order bits in /act reresent t&e
remainder w&en t&e ori'inal 1alue is di1ided by 2
n
) %odulo maskin' is t&ere/ore
eDui1alent to a modulo oeration)
y .
m.,
P
%
y .
13): +it Oerations in NS2 :31
Tab#e %0=0 Comonents o/ subnet maskin' and modulo maskin'
%askin' comonents Subnet maskin' %odulo maskin'
T&e mask
T&e mask oeration
1 1, ,
+itwise F4N.G
, ,1 1
+itwise F4N.G
%asked 1alue Network IP address (emainder
6e summariJe t&e maskin' comonents o/ subnet maskin' and modulo
maskin' in Table 13)3) Note t&at bot& subnet maskin' and modulo maskin' use a
bitwise F4N.G as t&eir mask oeration) Since t&eir masks are di//erent* t&e
imlications /or t&eir masked 1alue are di//erent)
1+.$.2 2it Shifting and )ecial M!ltiplication
4not&er imortant bit oeration is bit s&i/tin' w&ic& is eDui1alent to decimal
multilication) I/ a binary 1alue is s&i/ted to t&e le/t by n bits* t&e corresondin'
decimal 1alue will increase by 2
n
times) Similarly* a binary number ri'&t s&i/ted
by n bits returns t&e Duotient o/ t&e decimal 1alue di1ided by 2
n
)
To ro1e t&e abo1e statement* consider an arbitrary 1alue
P
%
m.,
A
m
2
m
*
w&ere A
m
2 /,O 1'O m . /,O O % ') !et y ZZ n denote t&e 1alue o/ y a/ter bein'
s&i/ted to t&e le/t by n bits) T&en
y ZZ n .

P
%
A
m
2
m

ZZ n . )AA A$ ZZ n
^
%
_
b
`
its
a
?13)3@
.
m.,
A
m
2
mCn

. )AA A ,, ,$<
^
%
_
b
`
its
a
^
n
_
b
`
its
a
Suose
P
%
m.,
A
m
2
m
) 6e &a1e
%
W
%
W
y 2
n
.
E
A
m
2
m
m.,
2
n
.
E
A
m
2
mCn
m.,
?13):@
w&ic& is t&e same as ?13)3@) T&is ro1es t&e /irst art ?i)e)* le/t s&i/tin'@ o/ t&e
abo1e statement) T&e second art o/ ?i)e)* ri'&t s&i/tin'@ t&e statement can be
ro1en similarly and is omitted /or bre1ity)
T&e relations&i between bit s&i/tin' and decimal multilication can be summa9
riJed as /ollows<
4n n9bit le/t s&i/t results in multilication o/ t&e decimal 1alue by 2
n
)
4n n9bit ri'&t s&i/t returns t&e Duotient w&en t&e decimal 1alue is di1ided by
2
n
)
:32 13 (elated Heler Classes
%0=0 $ha&ter Summary
T&is c&ater resents t&ree maBor &eler classes< timers* random number
'enerators* and error models) T&e /irst &eler class is Timer) 0nless restarted or
cancelled* class Timer waits /or a certain time and takes eAiration actions)
Class Timer ro1ides t&ree main inter/ace /unctions to start* restart* and cancel
t&e waitin' rocess) Class Timer is usually cross9re/erenced to anot&er obBect*
w&ic& contains an instruction on &ow to er/orm eAiration actions) 4t t&e
eAiration ?i)e)* w&en e*pire&e' is in1oked@* t&e timer in/orms t&e obBect to
eAecute t&e eAiration actions) T&e obBect* on t&e ot&er &and* may start* restart* or
cancel t&e timer t&rou'& its re/erence to t&e timer)
T&e second art o/ t&is c&ater demonstrates &ow NS2 imlements (andom
Number Lenerator ?(NL@ to 'enerate random numbers) +y de/ault* NS2 always
seeds t&e simulation wit& 1 H meanin' NS2 is deterministic by de/ault) To
introduce randomness into simulation* we need to seed de"a!lt#N- di//erently)
T&e last &eler class is class Error%odel w&ic& is a acket error simulation
class) .eri1ed /rom class Connector* it can be inserted into a network usin'
OTcl instrocs ?e)')* lossmodel/III' and insertJlossmodel/III'@)
Class
Error%odel simulates acket error uon a acket recetion) I/ t&e acket is
simulated to be in error* it will eit&er dro or mark t&e corruted acket wit& an
error /la') Ot&erwise* it will /orward t&e acket to its downstream
obBect)
T&is c&ater also resents two main bit oerations< bit maskin' and bit s&i/tin')
+it maskin' is a bit trans/ormation rocess w&ic& can be used /or 1arious
uroses) T&is c&ater 'i1es two eAamles o/ bit baskin') One is subnet
maskin'* w&ic& is a rocess to determine a network /or an IP address) 4not&er is
a modulo maskin'* w&ic& can be used as a modulo oeration) 4s anot&er bit
oeration* bit s&i/tin' can be used /or decimal multilication or di1ision) S&i/tin'
an ori'inal 1alue to t&e le/t and ri'&t by n bits is eDui1alent to multilyin' and
di1idin' t&e ori'inal 1alue by
2
n
* resecti1ely)
%0=6 "<ercises
1) In EAamle 13)3*
a) C&an'e t&e seed to F###)G (erun t&e scrit /or a coule o/ times) Obser1e
and eAlain t&e outut)
b) C&an'e t&e seed to F,)G (erun t&e scrit /or a coule o/ times) Obser1e and
eAlain t&e outut)
c) Print out t&e 1alues o/ Farrival5G and Fsi6e5G /or ?a@ and ?b@* and s&ow
t&at t&ey are eAonentially and uni/ormly distributed) ?Hint< Set t&e seed
roerly)@
d) C&an'e t&e mean o/ Farrival5G to 1, and t&e inter1al o/ Fsi6e5G to
Q:,,O 2,,, * and reeat ?c@)
13)8 EAercises :33
e) (emo1e !ine 8 and reeat ?c@) Obser1e and eAlain t&e outut)
/) (emo1e !ines 8 and 1, and reeat ?c@) Obser1e and eAlain t&e outut)
2) 6rite a simulation scrit w&ic& 'enerates random numbers eAonentially dis9
tributed wit& mean 1),) To 1eri/y t&e scrit* lot t&e robability density
/unction)
3) 6rite a simulation scrit w&ic& 'enerates a random number normally
distributed wit& mean 1), and standard de1iation ,),3) To 1eri/y t&e
scrit* lot t&e robability density /unction)
:) .e1elo a new class /or a discrete random 1ariable w&ose robability mass
/unction is ),<1O ,<3O ,<3O ,<2O ,<1$) Test t&e code by 'eneratin' random
numbers and 1eri/y t&e robability mass /unction)
3) In EAamle 13):* collect statistics /or ackets w&ic& are in error and not in
error) 7eri/y t&at t&e acket error robability is ,)1) 4dBust t&e simulation time
i/ necessary) How lon' must your simulation be to ensure t&e con1er'ence o/
,)1 error robability R
a) Initially set link bandwidt& to 3 %bs)
b) C&an'e t&e bandwidt& to 3,, kbs) 6&at &aens to t&e measured con1er9
'ence time R EAlain w&y)
8) Consider a two state error model* w&ic& consists o/ good and 'ad states) Packet
transmission in a 'ood state is always error /ree* w&ile acket transmitted in a
bad state is always corruted) T&e time t&at an error model stays in 'ood and
bad states is eAonentially distributed wit& means t
'ood
and t
bad
* resecti1ely)
6rite a simulation scrit /or t&e abo1e two state error model wit& t
'ood
. 1,
sand t
bad
. 1 s) 7eri/y t&e results and s&ow t&e con1er'ence time)
2) !et a modulo mask be 8:) S&ow t&at t&e modulo maskin' and modulo oeration
are eDui1alent /or t&e /ollowin' ori'inal 1alues< 83* 8:* 83* 122* 12"* and 12#)
") Consider a ball color9number matc&in' eAeriment* w&ere balls are /ed one9by9
one to an obser1er) Eac& ball is masked wit& a color and a number) T&e color
can be eit&er black or w&ite* w&ile t&e uniDue number is increased one9by9one
as t&e balls are /ed to t&e obser1er) Crom time to time* t&e obser1er is 'i1en a
number and is asked to identi/y t&e color o/ one o/ t&e 8: most recently
obser1ed balls) .esi'n a memory9/riendly aroac& /or t&e obser1ation)
#) 6&at are t&e 1alues o/ 2* 3* 31* :3* and 38* w&en s&i/ted to t&e le/t and ri'&t by
1* 2* and 3 bitsR
A
Programming "ssentia#s
T&is aendiA co1ers t&e ro'rammin' lan'ua'es* w&ic& are essential /or
de1eloin' NS2 simulation ro'rams) T&ese include Tcl$OTcl w&ic& is t&e basic
buildin' block o/ NS2 and 46K w&ic& can be used /or ostsimulation analysis)
A=% Tc# Programming
Tcl is an interreted lan'ua'e* w&ose stren't& is its simlicity) %ost Tcl
statements can be contained in one line M38N) 4t runtime* Tcl translates and
eAecutes Tcl statements line by line wit&out t&e need /or ro'ram comilation)
T&is section di'ests M38N down to only w&at necessary to understand NS2)
(eaders may re/er to M38N /or more details on Tcl)
A.1.1 Progra In#ocation
T&ere are t&ree aroac&es /or eAecutin' a Tcl ro'ram<
1) Interpret one Tcl statement< 4t t&e command romt* eAecute
KKtcls( <Tcl StatementK
KKns <Tcl StatementK
w&ere Ftcls(G is an eAecutable /ile w&ic& in1okes t&e Tcl intererter)
1
Since
NS2 understands Tcl* an alternati1e to enter into t&e Tcl en1ironment is to enter
NS2 en1ironment by eAecutin' FnsG ?i)e)* t&e lower line@ instead o/ Ftcls(G
?i)e)* t&e uer line@)
1
Cor NS2 1ersion 2)33* t&e /ile tcls(Ie*e is located in t&e directory nsJallinoneJ1I3>M
tcl/I>I/M!ni*I
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 18* = Srin'er Science>+usiness %edia* !!C 2,12
:33
2,, 4 Pro'rammin' Essentials
2) Enter into the Tcl environment and interpret Tcl statement line 'y line< T&e /irst
ste /or t&is aroac& is to enter a Tcl en1ironment by eAecutin' Ftcls(G or
FnsG at t&e command romt) T&en* write down t&e Tcl statements line by
line) Cinally* eAit t&e Tcl en1ironment by t&e command Fe*itG or a control
key FCtrl 4 C)G
3) Interpret a Tcl Scripting &ile< T&is aroac& is similar to t&e /irst one) 4t t&e
command romt* eAecute
KK tcls( <"ilenameK ?<ar$0K <ar$2K III@
KK ns <"ilenameK ?<ar$0K <ar$2K III@
Here* Tcl interrets t&e statements in t&e /ile <"ilenameK line by line)
Note t&at F<ar$0K <ar$2K IIIG are t&e otional inut ar'uments* w&ic&
can be used wit&in a Tcl ro'ram 1ia t&e /ollowin' two secial 1ariables<
ar$v 4 list 1ariable containin' all inut ar'uments ro1ided at t&e
ro'ram in1ocation
ar$c T&e number o/ elements in Far$vG
A.1.2 Synta1
0nlike keyword9based lan'ua'es suc& as CCC or ba1a* Tcl is a osition9based
lan9 'ua'e) T&ere is no reser1ed word ?e)')* print" in CCC@ in Tcl) Tcl
di//erentiates user9de/ined words /rom command words by lookin' at t&e osition
o/ t&e word) %ore seci/ically*
T&e /irst word in a statement is always a command
name)
Eac& word in a statement is searated by a w&ite sace)
2
4 statement is terminated wit& a semicolon ?i)e)* F;G@ or an end o/ t&e line)
T&e /ollowin' symbols can be used to comose comleA Tcl
statements<
Substitution
P Collowed by a 1ariable nameO a dollar si'n ?i)e)* P@ tells Tcl to
relace t&e entire word wit& t&e 1alue stored in t&e 1ariable)
?@ Lrou words as a Tcl statement ?i)e)* t&e /irst wit&in F?@G is treated
as a command word@) Tcl statements enclosed wit&in F?@G s&all be
eAecuted be/ore t&ose lyin' outside F?@)G
2
4 w&ite sace is one or more sace and$or tab c&aracters)
4)1 Tcl Pro'rammin' 2,1
;rou&ing
HH Lrou words as a strin') Substitute 1ariables wit& t&eir 1alues)
/' Lrou words as a strin') Treat all secial c&aracters as a normal
c&aracter) 4o not er/orm 1alue substitution)
,thers
&' Indicate an array indeA or inut ar'uments o/ mat&ematical
/unctions)
n Treat t&e /ollowin' secial c&aracter as a strin')
O %ark t&e be'innin' o/ a comment)
; %ark t&e end o/ a Tcl statement)
EndO"Line %ark t&e end o/ a Tcl statement)
A.1." .aria-les and 2asic Operations
+y de/ault* e1eryt&in' in Tcl is strin'* w&ic& can be maniulated usin' t&e
/ollowin' /i1e basic oerations<
+ssignment> set <nameK <val!eK ?e)')* set * 0@
Store <val!eK in t&e 1ariable w&ose name is
<nameK)
4eassignment> !nset <nameK ?e)')* !nset *@
(emo1e t&e 1ariable <nameK /rom t&e list o/ known
1ariables)
Input> $ets <c(annelK ?<varnameK@ ?e)')* $ets stdin *@
(etrie1e a line /rom w&at attac&ed to a Tcl <c(annelK) T&e
retrie1ed 1alue is stored in t&e 1ariable <varnameK) T&e details o/
Tcl c&annels will be discussed later in Sect) 4)1)2) In case o/ t&e
standard inut* t&e <c(annelK is Fstdin)G .urin' ro'ram
debu''in'* a statement F$ets stdinG asks t&e ro'ram to wait /or
an end9o/9line c&aracter /rom t&e user)
T&e command F$etsG returns t&e number o/ c&aracters it reads
/rom t&e c&annel) Howe1er* i/ it cannot read /rom <c(annelK
?e)')* reac&in' t&e end o/ t&e /ile@* it will return F 1)G
2,2 4 Pro'rammin' Essentials
(utput> p!ts ?Jnone,line@ ?<c(annelK@ <strK ?e)')* p!ts P*@
Outut <strK to <c(annelK) +y de/ault* <c(annelK is t&e
stan9 dard outut ?i)e)* screen@* and a new line c&aracter would be
attac&ed to <strK) Howe1er* t&e new line c&aracter can be
suressed by t&e otion Jnone,line) 4lso* t&e outut can be sent
to some ot&er lace by seci/yin' <c(annelK)
Error reporting> error <strK ?e)')* error HQatal
ErrorCCH@
(eort t&e error and send <strK to t&e associated alication ?e)')*
monitor@ and returnin' FTCL5E##O#G)
E%ample +** T&e /ollowin' Tcl scrit* FconvertItcl*G con1erts temeratures
/rom Ca&ren&eit to Celsius) T&e con1ersion starts at ,
c
?Ca&ren&eit@* roceeds wit&
a ste o/ 3,
c
?Ca&ren&eit@* and stos w&en t&e temerature eAceeds 1:,
c
?Ca&ren&eit@) T&e ro'ram rints out t&e con1erted temerature in Ca&ren&eit as
lon' as it does not eAceed 1:,
c
)
O convertItcl
O Qa(ren(eit to Celsi!s Conversion
2 set lo,er 0
1 set !pper 2=0
3 set step >0
= set "a(r Plo,er
> ,(ile 7P"a(r < P!pper8 7
A set celsi!s ?e*pr >
N
&P"a(r J 31'MG@
B p!ts Jnone,line HQa(ren(eit M Celsi!s 9
P"a(r M Pcelsi!sH
/ set "a(r ?e*pr P"a(r 4 Pstep@
G p!ts HTt Enter THyTH to contin!e IIIH
20 "l!s( stdo!t
22 set cont 0
21 ,(ile 7 Pcont C: y 8 7
23 $ets stdin cont
2= 8
2> 8
6&en eAecutin' t&e Tcl scritin' /ile FconvertItcl*G t&e /ollowin' results
s&ould be s&own on t&e screen<
KKtcls( convertItcl
Qa(ren(eit M Celsi!s 9 0 M J2/ Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 >0 M 20 Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 200 M 3BIBB/ Enter HyH
to contin!e IIIy
4)1 Tcl Pro'rammin' 2,3
4lternati1ely* since NS2 is written in Tcl* t&e /ollowin' in1ocation would lead
to t&e same result)
KKns convertItcl
Cor now* it is not imortant to understand e1ery line o/ t&e abo1e ro'ram) 6e
s&all reeatedly 1isit t&is eAamle* as we eAlain t&e syntaA o/ Tcl art by art)
!ines 1H3 s&ow eAamles o/ 1alue assi'nment usin' Fset*G w&ere Plo,er*
P!pper* Pstep are set to ,* 1:,* and 3,* resecti1ely) !ine : s&ows an
eAamle
use o/ t&e substitution c&aracter FP*G w&ere t&e 1alue stored in t&e 1ariable
Plo,er
is stored in t&e 1ariable P"a(r)
!ine 2 s&ows an eAamle use o/ t&e outut command Fp!tsG w&ic& rints a
strin' on t&e screen) Here* P"a(r is enclosed wit&in t&e Duotation marks ?i)e)*
HH@)
Since t&e Duotation marks allow 1alue substitution* t&e outut s&ows t&e 1alue
stored
in P"a(r) Note t&at t&e otion FJnone,lineG is used to suress a new line)
T&e Fp!tsG statement on !ine # concatenates anot&er strin' to t&at 'enerated by
line 2) !ine # also s&ows two eAamle uses o/ t&e symbol Fn)G T&e /irst one FntG
reresents a tab c&aracter) T&e second one* FnHG is treated as a re'ular c&aracter
FHG strin'* rat&er t&an a secial c&aracter)
Cinally !ine 13 s&ows eAamle use o/ t&e inut command F$ets)G Here* Tcl
stos and waits /or an inut /rom t&e standard inut ?i)e)* keyboard@) T&e 1alue
sulied by t&e user will be stored in t&e 1ariable Fcont)G
E%ample +*2* Insert t&e /ollowin' two lines into t&e end o/ t&e ro'ram in
EAamle 4)1)
2A !nset lo,er
2B p!ts Plo,er
4/ter eAecutin' t&e Tcl scrit FconvertItcl*G t&e /ollowin' result s&ould
aear on t&e screen<
KKtcls( convertItcl
Qa(ren(eit M Celsi!s 9 0 M J2/ Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 >0 M 20 Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 200 M 3BIBB/ Enter HyH
to contin!e IIIy
canZt read Hlo,erH9 no s!c( variable
,(ile e*ec!tin$
Hp!ts lo,erH
&"ile HconvertItclH line 2B'
4/ter bein' F!nset*G t&e 1ariable Plo,er becomes unknown to Tcl) Printin'
t&is 1ariable would result in a runtime error)
2,: 4 Pro'rammin' Essentials
A.1.$ Logical and Matheatical Operations
T&e main lo'ical and mat&ematical oerations include
.ogical statement> A <opsK .
(eturn tr!e or "alse 1alue o/ t&e statement* w&ere t&e list o/
lo'ical oerators <opsK is 'i1en below)
< &less t(an' : &e+!al'
<: &less t(an or e+!al' C: &Not E+!al'
K &$reater t(an' XX &O#'
K: &$reater t(an or e+!al' FF &AND'
C &ne$ation'
Increment> incr <varNameK ?<incrSalK@
Increment t&e 1ariable <varNameK by <incrSalK* w&ere
<incrSalK can be Jero* ositi1e* or ne'ati1e) T&e de/ault 1alue o/
<incrSalK is 1)
+rithmetic operation> e*pr A <opsK .
Interret FA <opsK .G as an arit&metic eAression* w&ere t&e list o/
'asic arit&metic oerators <opsK are 'i1en below<
4 &addition' J &s!btraction'
N
&m!ltiplication' M &division'
E &mod!lo'
T&e ad1anced arit&metic oerators <opsK are s&own below<
F &.it,ise AND' X &.it,ise O#'
<< &Le"t s(i"t' KK &#i$(t s(i"t'
*Yy96 &I" * is non6ero) t(en yI Ot(er,ise) 6'
5athematical function> e*pr <"nK&?<ar$sK@'
Interret <"nK&<ar$sK' as a mat&ematical /unction* w&ere t&e
mat&ematical /unctions <"nK are de/ined below<
abs&*' cos(&*' lo$&*' s+rt&*'
acos&*' do!ble&*' lo$20&*' srand&*'
asin&*' e*p&*' po,&*)y' tan&*'
atan&*' "loor&*' rand&*' tan(&*'
atan1&*' "mod&*' ro!nd&*' ,ide&*'
ceil&*' (ypot&*)y' sin&*'
cos&*' int&*' sin(&*'
4)1 Tcl Pro'rammin' 2,3
E%ample +*$* Insert t&e /ollowin' lines at t&e end o/ t&e ro'ram in EAamle 4)1)
2A p!ts H241 : ?e*pr 241@H
2B p!ts HLo$&20' : ?e*pr lo$20&20'@H
2/ p!ts HAbsol!te val!e o" J20 : ?e*pr abs&J20'@H
2G p!ts Jnone,line 7789 8
10 p!ts 7e*pr Plo,er8
12 p!ts Jnone,line 7HH9 8
11 p!ts He*pr Plo,erH
13 p!ts Jnone,line 7?@9 8
1= p!ts ?e*pr Plo,er@
4/ter eAecutin' t&e Tcl scrit FconvertItcl*G t&e /ollowin' result s&ould
aear on t&e screen<
KKtcls( convertItcl
Qa(ren(eit M Celsi!s 9 0 M J2/ Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 >0 M 20 Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 200 M 3BIBB/ Enter HyH
to contin!e IIIy
Lo$&20' : 2I0
Absol!te val!e o" J20 : 20
241 : 3
789 e*pr P"a(r 4 Pstep
HH9 e*pr 2>0 4 >0
?@9 100
!ines 18H1" s&ow eAamle use o/ arit&metic oerations and mat&ematical
/unctions) !ines 1#H2: s&ow eAamle uses o/ 1arious brackets in Tcl) Curly
braces 'rou words as a strin') Iuotation marks 'rou words* and substitute
1ariables wit& t&eir 1alues) Cinally* sDuare brackets 'rou words as a Tcl statement)
A.1.+ Control Str!ct!re
Tcl control structure de/ines &ow t&e ro'ram roceeds* usin' t&e commands i"M
elseMelsei"* s,itc(* "or* ,(ile* "oreac(* and breakMcontin!e)
Se#ection Structure
Selection ro1ides a ro'ram wit& c&oices* and let t&e ro'rams decide conditions
under w&ic& certain c&oices are taken) Tcl ro1ides two key selection control
structures)
2,8 4 Pro'rammin' Essentials
6&ile an i"MelseMelsei" structure ro1ides a ro'ram wit& a selecti1e
c&oice* t&e s,itc( structure is a con1enient relacement a lon' series o/ a
i"MelseMelsei" structure) T&eir syntaAes are s&own below<
i" 7<condition2K8 7 <actionSet2K 8
elsei" 7<condition1K8 7 <actionSet1K 8
III
else 7 <actionSetNK 8
s,itc( <variableK 7
<pattern52K 7 <actionSet2K 8
<pattern51K 7 <actionSet1K 8
III
de"a!lt 7 <actionSetNK 8
8
A=%=0=% Re&etition Structure
T&e commands F,(ile*G F"or*G and F"oreac(G are used w&en actions need to
be reeated /or se1eral times)
,(ile 7<conditionK8 7 <actionsK 8
"or 7<initK8 7<conditionK8 7<modK8 7 <actionsK 8
"oreac( 7<varK8 7<listK8 7 <actionsK 8
T&e F,(ileG structure reeats t&e <actionsK as lon' as t&e
<conditionK is tr!e)
3
T&e F"orG structure be'ins wit& an initialiJation
statement <initK) 4/ter takin' <actionsK* it eAecutes t&e Tcl statement
<modK and c&ecks w&et&er t&e <conditionK is tr!e) It will reeat t&e
<actionsK i/ so* and terminate ot&erwise) T&e structure F"oreac(G reeats
<actionsK /or e1ery item in t&e list 1ariable <listK) In eac& reetition* t&e
item is stored in t&e 1ariable <varK and can be used inside t&e loo)
A=%=0=2 Ium&ing Structure
T&e structure FbreakG and Fcontin!eG are used to sto t&e iterati1e /low o/ t&e
abo1e F,(ile*G F"or*G and F"oreac(G reetiti1e structures) T&eir key
di//erence is t&at w&ile t&e structure FbreakG immediately eAits t&e loo* t&e
structure Fcontin!eG restarts t&e loo)
3
See eAamles o/ t&e usa'e o/ F,(ileG on !ines 3 and 12 in EAamle 4)1)
4)1 Tcl Pro'rammin' 2,2
A.1./ Mod!lari<ation
%odulariJation breaks down a lar'e ro'ram into small mana'eable ieces) Eac&
small ortion o/ a ro'ram can be stored in a /ile or a rocedure)
A=%=6=% Storing a Program Portion into a 4i#e an 4i#e Sourcing
Cile Sourcin' is an act o/ loadin' a Tcl /ile w&ose name is <"ilenameK into an
acti1e Tcl ro'ram) T&e syntaA o/ sourcin' is s&own below<
so!rce <"ilenameK
A=%=6=2 Storing a Program Portion into a Proceure
Proceure -ec#aration
proc <nameK 7<ar$ListK8 7
<actionsK
?ret!rn <ret!rned5val!eK@
8
T&e declaration o/ a rocedure be'ins wit& a command word Fproc*G /ollowin'
by t&e name ?e)')* <nameK@* t&e list o/ inut ar'uments ?e)')* <ar$ListK@* and
t&e body* resecti1ely) 6it&in t&e body* t&e rocedure may otionally return a
1alue ?e)')* <ret!rned5val!eK@ usin' a Fret!rnG statement)
T&e list o/ inut ar'uments ?i)e)* <ar$ListK@ may consist o/ se1eral inut
ar'uments) Eac& inut ar'ument is searated by a w&ite sace) 4lso* Tcl allows
ro'rammers to seci/y a de/ault 1alue /or eac& inut ar'ument) T&e syntaA /or
declarin' inut ar'uments is as /ollows<
7 7<n2K <d2K8 7<n1K <d1K8 III8
w&ere <n2K and <n1K are names o/ t&e /irst and second inut ar'uments
w&ose de/ault 1alues are <d2K and <d1K* resecti1ely)
Proceure 'nvocation
4/ter declaration* a rocedure <nameK can be in1oked usin' t&e /ollowin'
syntaA<
<nameK <valListK
w&ere <valListK is t&e list o/ t&e inut ar'ument 1alues) I/ <valListK
is missin'* t&e de/ault 1alue will be used as inut 1alues)
2," 4 Pro'rammin' Essentials
E%ample +*/* T&e ro'ram in EAamle 4)1 can be modi/ied into a rocedure
?!ines
1H1:@ as /ollows<
O convert5procItcl
2 proc convert5proc 77lo,er 08 7!pper 2=08
7step >088 7
1 set "a(r Plo,er
3 ,(ile 7P"a(r < P!pper8 7
= set celsi!s ?e*pr >
N
&P"a(r J 31'MG@
> p!ts Jnone,line HQa(ren(eit M Celsi!s 9
P"a(r M Pcelsi!sH
A set "a(r ?e*pr P"a(r 4 Pstep@
B p!ts HTt Enter THyTH to contin!e IIIH
/ "l!s( stdo!t
G set cont 0
20 ,(ile 7 Pcont C: y 8 7
22 $ets stdin cont
21 8
23 8
2= 8
Here* t&e keyword FprocG marks t&e be'innin' o/ t&e rocedure) It is /ollowed
by t&e rocedure name ?i)e)* convert5proc@ and t&ree inut ar'uments ?i)e)*
Plo,er* P!pper* and Pstep@ accomanied by t&eir de/ault 1alues ?i)e)* ,* 1:,*
and 3,@)
T&e /ile Fconvert5r!nItclG ?!ines 13 and 18@ contains t&e main ro'ram)
O convert5r!nItcl
2> so!rce convert5procItcl
2A convert5proc 0 2=0 B0
4t t&e command romt* we can eAecute t&e ro'ram as /ollows<
KK tcls( convert5r!nItcl
Qa(ren(eit M Celsi!s 9 0 M J2/ Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 B0 M 12 Enter HyH
to contin!e IIIy
!ine 13 sources t&e Tcl /ile Fconvert5procItcl*G w&ic& contains t&e
roce9 dure Fconvert5proc*G into t&e acti1e ro'ram) !ine 18 eAecutes t&e
rocedure Fconvert5procG /eedin' ,* 1:,* and 2, as t&e inut ar'uments)
T&ese t&ree 1alues are stored in t&e 1ariables Plo,er* P!pper* and Pstep*
resecti1ely)
4)1 Tcl Pro'rammin' 2,#
A=%=6=* ;#oba# an +oca# >ariab#es
!ike in ot&er ro'rammin' lan'ua'es* 1ariables in Tcl are local by de/ault) T&at
is* t&ey are understood wit&in a certain boundary) Cor eAamle* t&e rocedure in
EAamle 4): understands 1ariables Plo,er* P!pper* Pstep* and P"a(r* but
it does not understand t&e 1ariables de/ined outside t&e rocedure) T&e syntaA to
make a 1ariable Pvarname 'lobal is as /ollows<
$lobal <varnameK
E%ample +*1* %odi/y EAamle 4): as s&own below<
O convert5procItcl
proc convert5proc 7 7 lo,er 0 8 7 !pper 2=0 8
7 step >0 8 8 7
$lobal e*t5var
III
p!ts HT(e variable e*t5var is Pe*t5varH
8
Here* we add two lines to t&e rocedure Fconvert5proc)G T&e /irst one is to
tell rocedure t&at t&e 1ariable Pe*t5var is de/ined in t&e 'lobal scoe ?i)e)* in
t&e main ro'ram@) T&e second one s&ows t&e 1alue o/ t&e 1ariable Pe*t5var
on t&e screen)
O convert5r!nItcl
so!rce convert5procItcl
set e*t5var GGG
convert5proc 0 2=0 B0
In t&e main ro'ram* t&e 1ariable Pe*t5var is set to ### be/ore t&e
in1ocation o/ t&e rocedure) T&ere/ore* t&e result on t&e screen would be as s&own
below<
KK tcls( convert5r!nItcl
Qa(ren(eit M Celsi!s 9 0 M J2/ Enter HyH
to contin!e IIIy
Qa(ren(eit M Celsi!s 9 B0 M 12 Enter HyH
to contin!e IIIy
T(e variable e*t5var is GGG
w&ere t&e last line is s&own in addition to t&e result /rom EAamle 4):)
A.1.4 Ad#anced Inp!t/O!tp!t9 5iles and Channels
Tcl uses a so9called Tcl c&annel to recei1e an inut usin' a command F$etsG and
to send an outut usin' a command Fp!ts)G
21, 4 Pro'rammin' Essentials
A=%=5=% Tc# $hanne#s
4 Tcl c&annel re/ers to an inter/ace w&ic& interacts wit& t&e outside world) Two
main tyes o/ Tcl c&annels are standard readin'$writin' c&annels and /ile
c&annels) T&e /ormer are classi/ied into FstdinG /or readin'* Fstdo!tG /or
writin'* and FstderrG /or error reortin'* w&ile t&e latter needs to be attac&ed to
a /ile be/ore it is usable)
T&ere are t&ree commands related to Tcl c&annels<
(pen the channel> open <"ileNameK ?<optK@
?e)')* open HinIt*tH HrH@
Create and connect a c&annel to a /ile w&ose name is <"ileNameK*
w&ere t&e otion <optK can be HrH ?readin'@* H,H ?writin'@* or
HaH ?aendin'@) T&is command returns a &andle ?i)e)* a re/erence@
to t&e created c&annel)
Close the channel> close P<"ilec(K ?e)')* close
Pc('
Close t&e c&annel P<c(K)
&lush the 'uffer> "l!s( P<"ilec(K ?e)')* "l!s(
Pc('
Clus& t&e internal bu//er associated wit& t&e c&annel P<"ilec(K)
T&e Tcl outut rocess is rat&er subtle) Tcl does not immediately writes to t&e
c&annel) Instead* it &olds t&e outut recei1ed /rom t&e command Fp!tsG in its
bu//er* and releases t&e outut under one o/ t&e t&ree /ollowin' conditions< t&e
bu//er is /ull* t&e c&annel is closed* or an eAlicit /lus&in' command is eAecuted)
Clus&in' bu//er /orces Tcl to release content in its bu//er wit&out closin'
t&e c&annel) EAamle use o/ t&e command F"l!s(G is s&own in !ine 1, o/
EAamle 4)1* w&ere we /orce t&e bu//er to releases its strin' be/ore t&e statement
F$ets stdin cont)G
E%ample +*8* Consider t&e /ollowin' Tcl ro'ram* w&ic& coies t&e inut /ile
Finp!tIt*tG to t&e outut /ile Fo!tp!tIt*tG line by line) In addition* t&e
line number is re/iAed at t&e be'innin' o/ eac& line)
O "ileItcl
p!ts HPress any key to be$in pre"i*in$ "ileIIIH
$ets stdin
set c(5in ?open Hinp!tIt*tH HrH@
set c(5o!t ?open Ho!tp!tIt*tH HaH@
set line5no 0
,(ile 7?$ets Pc(5in line@ K: 08 7
p!ts Pc(5o!t H?incr line5no@ PlineH
8
close Pc(5in
close Pc(5o!t
4)1 Tcl Pro'rammin' 211
Crom Sects) 4)1)3 and 4)1)3* t&e statement F,(ile /?$ets Pc(5in line@
K: 0'G reads a line /rom t&e /ile until reac&in' t&e end o/ t&e /ile w&ere F 1G is
returned) (eaders are encoura'ed to ro1ide t&eir own inut /ile* run t&e ro'ram*
and obser1e t&e result)
A.1.? )ata Types
Tcl allows 1ariable usa'e wit&out declaration) T&ere/ore* its data tye is limited to
strin'* list* and associati1e array)
A=%=7=% String
+y de/ault* e1eryt&in' in Tcl is strin') T&e basic strin' maniulation was s&own
in Sect) 4)1)3) 4dditionally* Tcl ro1ides t&ree /ollowin' strin' maniulation
commands<
strin$ <cmdK ?<ar$sK@
%ain maniulation command* w&ere <cmdK is a sub9command* and
<ar$sK are t&e inut ar'uments o/ t&e sub9command)
strin$ len$t( <strK< (eturn t&e len't& o/ t&e strin' <strK)
strin$ "irst <t*tK <strK< (eturn t&e /irst location wit&in
t&e strin' <strK w&ic& contains <t*tK* or F91G i/ t&e strin' does
not contain <t*tK)
strin$ last <t*tK <strK< Similar to t&e Fstrin$
"irstG command* but look /or t&e last occurrence)
strin$ matc( ?Jnocase@ <patternK <strK<
.etermine w&et&er t&e strin' <strK contains <pattermK)
(eturn 1 i/ so and , ot&erwise) See t&e details o/ attern matc&in' in
Sect) 4)3):)
strin$ ran$e <strK <"stK <lstK< (eturn t&e <"stKt&
c&aracter to t&e <lstKt& c&aracter o/ t&e strin' <strK)
"ormat <"mtK ?<d2K <d1K III@ ?e)')* "ormat E>I3" ?e*pr
1I0M3@@
Create a strin' usin' t&e CCC print" /ormat) T&e /ormat is
de/ined in <"mtK* and t&e 1alues are de/ined in <d2K* <d1K* and so
on)
scan <strK <"mtK ?<v2K <v1K III@ ?e)')* scan H%y NS1H /Es
Es' v2 v1@
T&is command is t&e re1erse o/ t&e command F"ormat)G It scans t&e
inut strin' <strK accordin' to t&e 'i1en /ormat <"mtK* and
eAtracts and stores t&e matc&ed 1alues in t&e corresondin'
1ariables <v2K*
<v1K* and so on)
212 4 Pro'rammin' Essentials
A=%=7=2 +ist
4 list contains a series o/ strin's or lists) It &as t&e /ollowin' roerties)
Items are 'rou into a list usin' curly braces ?i)e)* /III'@)
Eac& item is searated by a w&ite sace)
Eac& item is indeAed wit& ,* 1* 2* and so on) T&e last indeA can be re/erred to
by a keyword Fend)G
4n item can be a list)
4 list can be maniulated usin' t&e /ollowin' commands<
Creation -method 0> /<i2K ?<i1K III@'
Creation -method 20> /list <i2K ?<i1K III@'
?e)')* set mylist /2 1 3'* set mylist ?list 2 1 3@@
Construct a list w&ose items are <i2K* <i1K* and so on)
+ppending> /lappend <lK <i2K ?<i1K III@'
?e)')* lappend mylist = >@
4end t&e items <i2K* <i1K* and so on to t&e end o/ t&e list <lK)
String to list> /split <strK <c(arK' ?e)')* set mylist ?split
H2F1F3H F@@
Searate a strin' <strK usin' a delimitin' c&aracter <c(arK) T&en*
return a list w&ose items store t&e eAtracted &rases)
.ist to string> /join <lK <c(arK' ?e)')* join Pmylist F@
Con1ert a list <lK to a strin'* lacin' a c&aracter <c(arK between
eac& air o/ items)
.ength> /llen$t( <lK ' ?e)')* llen$t( Pmylist@
(eturn t&e number o/ items in t&e list <lK)
Det an item> /linde* <lK <inde*K ' ?e)')* linde* Pmylist 1@
(eturn t&e <inde*Kt& item o/ t&e list)
Det a su'list> /lran$e <lK <"iK <liK'
?e)')* lran$e Pmylist 0 end@
(eturn a list containin' all items between t&e <"iKt& item and t&e
<liKt& item o/ t&e list)
A=%=7=* Associative Array
4n associati1e array is a two9dimensional data structure) T&e /irst dimension is t&e
indeA* w&ile t&e second dimension is t&e associated 1alue) In Tcl* t&e /irst
dimension
4)2 ObBected9Oriented Tcl Pro'rammin' 213
is a strin'* w&ile t&e second one can be a strin'* a list* or an array) 4n array can be
maniulated as /ollows<
Set the va#ue2 set P<aNameK&<inde*K' <val!eK
?e)')* set Pmyarray&Apple' 1@
Create an entry /or an array w&ose name is <aNameK) T&e indeA and
1alue /or t&is entry are <inde*K and <val!eK* resecti1ely)
+ist to array2 array set <aNameK P<listnameK
?e)')* array set myarray /Apple 1 .anana 2'@
Con1ert a list 1ariable P<listnameK to an array w&ose name is
<aNameK) T&e items in t&e list are used alternately as indeAes and
1alues* resecti1ely* o/ t&e array)
Array to #ist2 array $et <aNameK ?e)')* array $et
myarray@
(eturn a list 1ariable containin' concatenated airs o/ indeAes and
1alues o/ t&e array w&ose name is <aNameK)
;et ine< #ist2 array name <aNameK
N
?e)')* array name myarray
N
@ (eturn a list 1ariable w&ose items contain t&e indeAes o/ t&e array)
Note t&at w&en creatin' an array* a list can be relaced wit& all its items
embraced wit&in curly braces)
T&ere are two key di//erences between lists and associati1e arrays) Cirst* a list is
a collection o/ ordered items) T&e indeAes o/ a list are ,* 1* and so on) Entries in
an associated array &a1e no order) T&ere is no suc& t&in' as t&e ne%t entry in an
array)
:
Eac& entry can be accessed directly)
4not&er di//erence is t&at an array cannot be directly oututted usin' Fp!ts)G
It must /irst be con1erted into a list* w&ic& can be oututted usin' Fp!ts)G
A=2 ,b1ecte.,riente Tc# Programming
OTcl is an obBect9oriented 1ersion o/ Tcl* Bust like CCC is an obBect9oriented
1ersion o/ C M31N) 4ll t&e basic arc&itecture and syntaA o/ Tcl are carried o1er to
OTcl) +y incororatin' t&e ObBect Oriented Pro'rammin' ?OOP@ concet* OTcl
&as additional bene/its suc& as scalability* modulariJation* and rotection /rom
unintentional access)
:
T&e abo1e eAamle does not imly t&at t&e entry Pmyarray&.anana' is t&e entry neAt to
Pmyarray&Apple')
21: 4 Pro'rammin' Essentials
A.2.1 OTcl Lang!age Str!ct!re
In OOP* all 1ariables and met&ods must be associated wit& classes) T&ey cannot be
in1oked as standalone 1ariables or rocedures) OTcl statements always /ollow one
o/ t&e /ollowin' t&ree atterns<
1) Class declaration< Class <classNameK ?<optionsK@
2) Class9associated met&od in1ocation<
<classNameK <instprocK ?<optionsK@
3) ObBect9associated met&od in1ocation<
P<objNameK <instprocK ?<optionsK@
!ike CCC* OTcl does not allow direction access to class 1ariables) OTcl class
1ariables must be accessed 1ia t&e instroc Fset)G
T&e /irst statement is t&e class declaration statement) T&e latter two are t&e ones
w&ic& in1oke class met&ods <instprocK* w&ic& can be associated wit& eit&er
class <classNameK or obBect P<obj5nameK)
!ike in Tcl* OTcl is a ositional lan'ua'e) T&e /irst osition can be eit&er
a keyword FClass*G a class name <classNameK* or a 1ariable w&ic& &old
t&e obBect P<obj5nameK) T&e second osition is eit&er a class name ?i)e)*
<classNameK@ or t&e name o/ class met&od ?i)e)* <instprocK@) Cinally* t&e
last osition is t&e otional inut ar'uments)
A.2.2 Classes and Inheritance
4 class is a reresentation o/ a 'rou o/ obBects w&ic& s&are similar roerties
includin' be&a1ior?s@ or attribute?s@) T&ese roerties can be assed down to c&ild
classes)
3
In t&is resect* t&e donor and t&e recei1er o/ t&e roerties are called a
suerclass ?base or arent class@ and a subclass ?deri1ed or c&ild class@*
resecti1ely) 4art /rom in&eritin' roerties /rom a suerclass* a class de/ines its
own roerties to make itsel/ more seci/ic)
In OTcl t&e syntaAes /or class declaration are s&own below<
$#ass ec#aration2 Class <classNameK ?Js!perclass <s!perCNK@
?e)')* class %obile Js!perclass Node@
.eclare a class w&ose name is <classNameK* and otionally seci/y
t&e class <s!perCNK as t&e suerclass o/ t&e class <classNameK)
3
In OTcl* t&e to9le1el class is class Object* w&ic& ro1ides basic 1ariables and /unctions*
/rom w&ic& e1ery user9de/ined class in&erits)
4)2 ObBected9Oriented Tcl Pro'rammin' 213
S&ecifying the su&erc#ass2 <classNameK s!perclass <s!perCNK
?e)')* %obile s!perclass Node@
Seci/y t&e class <s!perCNK as t&e suerclass o/ class
<classNameK)
A.2." O-8ects and O-8ect Constr!ction Process
T&e key distinction between classes and obBects is as /ollows) 4 class is a assi1e
de/inition o/ similar obBects de/ined be/ore t&e runtime) 4n obBect* on t&e ot&er
&and* is an acti1e entity created /rom a temlate de/ined in a class at runtime) Its
1alues c&an'e as t&e ro'ram runs)
A=2=*=% ,b1ect $onstruction Methos
4n OTcl obBect can be created usin' t&e /ollowin' two
met&ods<
,b1ect construction (Metho %) <classNameK <nameK ?<ar$sK@
,b1ect construction (Metho 2) <classNameK create P<nameK
?<ar$sK@
?e)')* Node n2* Node create Pn2@
Construct ?i)e)* instantiate@ an obBect /rom class <classNameK and
store t&e obBect in t&e 1ariable w&ose name is <nameK* otionally
/eedin' <ar$sK as inut ar'uments to t&e constructor)
T&e /irst met&od is t&e standard obBect instantiation met&od)
8
Howe1er* t&e second
met&od 2 is re/erable since it allocates sace and in1okes t&e constructor o/ all
t&e classes alon' t&e in&eritance tree)
A=2=*=2 ,b1ect $onstruction Process
6&en constructin' an obBect usin' %et&od 2* t&e instroc FcreateG in1okes t&e
/ollowin' two instrocs<
1) Instroc FallocG allocates memory sace to store t&e
obBect)
2) Instroc FinitG initialiJes t&e obBect ?e)')* its class 1ariable@)
8
6&en usin' %et&od 2* t&e 1ariable P<nameK must eAist in t&e list o/ known 1ariable be/ore
t&e construction)
218 4 Pro'rammin' Essentials
In most cases* t&e instroc FallocG is internal to OTcl* w&ile t&e instroc
FinitG is ro1ided by t&e ro'rammer) T&rou'&out t&is book* we s&all re/er to
t&e instroc FinitG as t&e OTcl constructor)
In 'eneral* OOP lan'ua'es construct an obBect by in1okin' all t&e constructors
alon' t&e entire in&eritance tree) T&e in1ocation is not automatically carried out in
OTcl) 4 ro'rammer needs to eAlicitly in1oke a constructor o/ all classes alon'
t&e in&eritance tree 1ia t&e instroc Fne*t)G
.e/ined in t&e OTcl to9le1el class FObject*G t&e instroc Fne*tG eAecutes t&e
same instroc de/ined in t&e suerclass) It is usually seen in t&e
/orm
P<objectK ne*t ?<ar$sK@
Suose t&e abo1e statement is located in an instroc <instprocNameK o/
class <classNameK) 4t t&e eAecution* t&is statement would in1oke t&e instroc
<instprocNameK o/ t&e suerclass o/ class
<classNameK)
+y insertin' t&e /ollowin' statement into t&e constructor ?i)e)* t&e instroc
FinitG@
Psel" ne*t ?<ar$sK@
t&e constructor o/ t&e suerclass will be eAecuted)
A.2.$ Me-er .aria-les and
5!nctions
4 class contains two main tyes o/ members< 1ariables and met&ods) 4 1ariable
de/ines an attribute and$or &olds t&e current status) 4 met&od* on t&e ot&er &and*
de/ines t&e actions t&at an obBect can do) +y con1ention* OTcl calls a member
1ariable an Finstance 1ariableG or an Finst1ar*G and it calls a member met&od an
Finstance rocedureG or an Finstroc)G
A=2=/=% 'nstance >ariab#es
Instance 1ariables can be maniulated as /ollows<
-ec#aration (tie to c#ass)2 <classNameK instvar <n2K ?<n1K III@
-ec#aration (tie to ob1ect)2 Psel" instvar <n2K ?<n1K III@
?e)')* Node instvar state* Psel" instvar state@
.eclare 1ariables w&ose names are <n2K* <n1K* and so on* inst1ars o/
t&e class <classNameK or o/ t&e obBect Psel" H a secial
1ariable w&ic& &olds t&e obBect itsel/ ?i)e)* Psel" corresonds to
t&e ointer Ft(isG in CCC@)
4)2 ObBected9Oriented Tcl Pro'rammin' 212
Access (tie to c#ass)2 <classNameK set <instvarNameK ?<val!eK@
Access (tie to ob1ect)2 P<varNameK set <instvarNameK ?<val!eK@
?e)')* Node set state 2* Pn set state 2@
I/ <val!eK eAists* it will be stored in t&e inst1ar
P<instvarNameK o/ class <classNameK or o/ t&e obBect
P<varNameK) Ot&erwise* t&e abo1e statements will return t&e
1alue stored in t&e inst1ar
P<instvarNameK)
4s an interreted lan'ua'e* Tcl reDuires no /ormal declaration o/ member
1ariables) T&e only reDuirements are t&at t&e 1ariables must be declared be/ore its
use* and t&at t&e declaration statement must be wit&in an instance rocedure)
I/ an inst1ar is tied to a class* all obBects instantiated /rom t&is class will
automatically contain t&e inst1ar) On t&e ot&er &and* i/ t&e inst1ar is tied to an
obBect* it will be a member o/ t&at obBect only) Ot&er obBects /rom t&e same class
will not contain t&is member 1ariable) T&ere/ore* /rom wit&in e1ery instance
rocedure* it is ad1isable to declare all necessary inst1ars as t&e /irst OTcl
statement)
A=2=/=2 'nstance Proceures
OTcl declares and in1okes instance rocedures as /ollows<
-ec#aration2 <classNameK instproc <instprocNameK /?<ar$sK@'
/<bodyK'
?e)')* %yNode instproc recv /pkt' /III'@
.eclare <instprocNameK as an instroc o/ class <classNameK)
T&e otional inut ar'uments and t&e body o/ t&e instroc are seci/ied
in <ar$sK and in <bodyK resecti1ely)
'nvocation2 P<objNameK <instprocNameK ?<val!esK@
?e)')* Pn recv p@
EAecute t&e instroc <instprocNameK w&ic& is associated wit& t&e
class o/ t&e obBect P<objNameK* w&ere <val!esK are otionally
/ed as inut ar'uments)
4t t&e in1ocation* OTcl roceeds as /ollows<
1) !ook /or t&e instroc <instprocNameK in t&e class corresondin' to P<obj
NameK) EAecute and terminate i/ /ound) Ot&erwise* 'o t&e neAt ste)
2) !ook /or t&e instroc F!nkno,nG in t&e same class) EAecute and terminate i/
/ound) Ot&erwise* 'o t&e neAt ste)
3) %o1e to t&e suerclass and 'o back to ste 1) I/ t&e current class does not &a1e
any suerclass* reort t&e error)
21" 4 Pro'rammin' Essentials
A=2=/=* Non.'nheritab#e Members
+ot& inst1ars and instrocs are in&eritable) Once de/ined /or a class* t&ese
members would be a1ailable /or all obBects instantiated /rom t&at class and its
subclasses)
OTcl also &as anot&er tye o/ members seci/ic to an obBect only) Once de/ined
/or a certain obBect* t&ese members would not aear in ot&er obBects instantiated
/rom t&e same class or its subclasses) T&ese members are Bust lain ?i)e)* local@
varia'les and procedures)
4 1ariable is declared usin' t&e abo1e met&od to access 1ariable* i)e)* usin'
Fset)G Crom t&e abo1e eAamle* t&e OTcl statement FPn set state 2G de9
clares a 1ariable FstateG to be a member 1ariable o/ t&e obBect Pn) Ot&er
1ariables instantiated /rom t&e same class as Pn would not contain t&e 1ariable
Fstate)G
4 rocedure is declared usin' t&e /ollowin' syntaA<
<objNameK proc <procNameK 7?<ar$sK@8 7<bodyK8
w&ic& is similar to t&e instroc declaration) Once declared* rocedures can be
in1oked as i/ t&ey are instrocs)
A.2.+ A List of 0sef!l Instance Proced!res
Here is a list o/ use/ul instrocs de/ined in t&e to9le1el class Object) 4'ain*
t&ese instrocs are a1ailable to all classes deri1ed /rom class Object)
create P<nameK ?<ar$sK@<
Create and store an obBect in t&e 1ariable P<nameK)
destroy P<nameK<
.estroy t&e obBect stored in t&e 1ariable P<nameK)
s!perclass <nameK<
Seci/y class <nameK as its
suerclass)
instvar P<nameK<
.eclare P<nameK as its
inst1ar)
instproc <nameK ?<ar$sK@<
.eclare <nameK as its
instroc)
alloc P<nameK<
4llocate memory /or an obBect P<nameK)
init ?<ar$sK@ ?i)e)* t&e
constructor@< InitialiJe t&e
created obBect)
ne*t ?<ar$sK@<
In1oke t&e instroc wit& t&e same name* de/ined in t&e suerclass)
in"o <optionK<
4)2 ObBected9Oriented Tcl Pro'rammin' 21#
(eturn related in/ormation as seci/ied in <optionK) Note t&at t&e
otions tied to a class are di//erent /rom t&ose tied to an obBect ?see
Tables 4)1 and 4)2@)
22, 4 Pro'rammin' Essentials
Tab#e A=% Otions o/ t&e instroc Fin"oG associated wit& classes
Otions Cunctions
s!perclass (eturn t&e suerclass o/ t&e current class)
s!bclass (eturn t&e list o/ all t&e subclasses)
(erita$e (eturn t&e list o/ t&e in&eritance tree)
instances (eturn t&e list o/ instances o/ t&e class)
instprocs (eturn t&e list o/ instrocs de/ined on t&e class)
instcommands (eturn t&e list o/ instrocs and OTcl commands de/ined on t&e
class)
instar$s <procK (eturn t&e list o/ ar'uments o/ t&e instroc <procK de/ined on
t&e class)
instbody <procK (eturn t&e body o/ t&e instroc <procK de/ined on t&e class)
instde"a!lt <procK (eturn 1 i/ t&e de/ault 1alue o/ t&e ar'ument <ar$K o/ t&e
<ar$K <varK instroc <procK is <varK* and return , ot&erwise)
Tab#e A=2 Otions o/ t&e Fin"oG instroc associated wit& obBects
Otions Cunctions
class (eturn t&e class o/ t&e obBect)
procs (eturn t&e list o/ all associated rocedures)
commands (eturn t&e list o/ associated rocedures and OTcl commands)
vars (eturn t&e list o/ 1ariables de/ined on t&e obBect)
ar$s <procK (eturn t&e list o/ ar'uments o/ t&e rocedure <procK de/ined on
t&e obBect)
body <procK (eturn t&e body o/ t&e rocedure <procK de/ined on t&e obBect)
de"a!lt <procK (eturn 1 i/ t&e de/ault 1alue o/ t&e ar'ument <ar$K o/ t&e
<ar$K <varK rocedure <procK is <varK* and returns , ot&erwise)
E%ample +*9* Consider a 'eneral network node) 6&en eDuied wit& mobility*
t&is node becomes a mobile node) .eclarations o/ a class FNodeG and its subclass
F%obileG are s&own in !ines 1 and 2 below) T&is declaration allows class
F%obileG to in&erit caabilities o/ class FNodeG ?e)')* recei1in' ackets@ and to
&a1e more caabilities ?e)')* mo1in'@ o/ its own)
O nodeItcl
2 Class Node
1 Class %obile Js!perclass Node
3 Node instproc recv 7pkt8 7
= Psel" instvar state
> set state 2
A Psel" processJpkt Ppkt
B 8
/ %obile instproc move 7* y8 7
G Psel" instvar location
20 set location?0@ P*
22 set location?2@ Py
21 8
23 Node instproc init 78 7
2= Psel" instvar state
2> set state 0
2A 8
2B %obile instproc init 78 7
2/ Psel" ne*t
2G Psel" instvar location
10 set location?0@ 0
12 set location?2@ 0
11 8
13 set n 52
1= Node create Pn
1> p!ts HT(e instance o" class Node is
?Node in"o instances@H
1A p!ts HT(e class o" Pn is ?Pn in"o class@H
+y eAecutin' t&e /ile FnodeItcl*G t&e /ollowin' result s&ould aear on t&e
screen)
KKns nodeItcl
T(e instance o" class Node is 52
T(e class o" 52 is Node
T&e key oints o/ t&is eAamle are t&e constructor and t&e use o/ t&e instroc
Fin"o)G !ines 13H22 s&ow eAamles o/ constructor) 4t t&e construction* class
FNodeG sets its inst1ar FstateG to , ?i)e)* inacti1e@) Class F%obileG /irst
in1okes t&e constructor o/ class FNodeG in !ine 1" usin' t&e instroc Fne*t)G
T&en* !ines
2, and 21 set t&e location o/ t&e mobile node to &0)0')
!ine 23 s&ows an eAamle w&ic& instantiates an obBect /rom class FNodeG
and stores t&e obBect in t&e 1ariable Pn) !ines 2: and 23 s&ow two eAamle uses
o/ t&e instroc Fin"oG w&ic& is tied to t&e class FNodeG and t&e obBect Pn*
resecti1ely)
A=* AWD Programming
46K is a ro'rammin' lan'ua'e desi'ned to rocess teAt /iles M32N) 46K re/ers
to eac& line in a /ile as a record) Eac& record consists o/ fields* eac& o/ w&ic& is
searated by a /ield searator)
2
Lenerally* 46K reads data /rom a /ile consistin'
o/ /ields o/ records* rocesses t&ose /ields* and oututs t&e results to a /ile as a
/ormatted reort)
2
T&e de/ault /ield searator is a w&ite sace)
4)3 46K Pro'rammin' 221
To rocess an inut /ile* 46K /ollows an instruction seci/ied in an +6B
script) 4n 46K scrit can be seci/ied at t&e command romt or in a /ile)
6&ile t&e stren't& o/ t&e /ormer is t&e simlicity ?in in1ocation@* t&at o/ t&e latter
is t&e /unctionality) In t&e latter* t&e ro'rammin' /unctionalities suc& as
1ariables* loo* and conditions can be included into an 46K scrit to er/orm t&e
desired actions) In w&at /ollows we 'i1e a brie/ introduction to t&e 46K
lan'ua'e) T&e details o/ 46K ro'rammin' can be /ound in M33N)
A.".1 Progra In#ocation
46K can be in1oked /rom a command romt in two ways based on t&e
/ollowin' syntaA<
KKa,k ? JQ<c(K @ 7<p$mK8 ? <varsK @ ? <data5"ileK @
KKa,k ? JQ<c(K @ 7 J" <p$m5"ileK 8 ? <varsK @
? <data5"ileK @
w&ere <c(K is a /ield searator* <p$mK is an 46K scrit* <p$m5"ileK is a
/ile containin' an 46K scrit ?i)e)* an 46K /ile@* <varsK is a list o/ 1ariables
used in an 46K scrit* and <data5"ileK is an inut teAt /ile)
+y de/ault* 46K uses a w&ite sace ?i)e)* one or more saces or tabs@ as a /ield
searator) Howe1er* i/ t&e otion FJQG is resent* 46K will use <c(K as a
/ield searator)
"
T&e uer in1ocation takes an 46K scrit <p$mK as an inut
ar'ument* w&ile t&e lower one takes an 46K /ile <p$m5"ileK as an inut
ar'ument) In bot& cases* 1ariables <varsK and inut teAt /ile <data5"ileK
can be otionally ro1ided) I/ an inut teAt /ile is not ro1ided* 46K will wait
/or inut ar'uments /rom t&e standard inut ?e)')* keyboard@ line by line)
E%ample +*:* !et an inut teAt /ile Fin"ileIt*tG be de/ined below) 6e s&all
use t&is inut /ile reeatedly in t&is section)
Oin"ileIt*t
#cv 0I2A1 QromNode 1 ToNode 3 cbr PktSi6e: >00 DID: 3
En 0I2A= QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: /
De 0I2A= QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: /
#cv 0I2B0 QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: B
En 0I2B0 QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: B
De 0I2B0 QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: B
#cv 0I2B2 QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: =
En 0I2B1 QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: G
De 0I2B1 QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: G
#cv 0I2B/ QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: /
"
Cor eAamle* Fa,k JQ9G uses a colon F9G as a /ield searator)
222 4 Pro'rammin' Essentials
En 0I2B/ QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: /
De 0I2B/ QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: /
Note t&at in 46K* FOG marks t&e be'innin' o/ a comment line)
4t t&e command romt* we may run an 46K scrit to s&ow t&e lines w&ic&
contain FEnG as /ollows<
KKa,k MEnM in"ileIt*t
En 0I2A= QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: /
En 0I2B0 QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: B
En 0I2B1 QromNode 2 ToNode 1 cbr PktSi6e: 2000 DID: G
En 0I2B/ QromNode 1 ToNode 3 cbr PktSi6e: 2000 DID: /
Here* t&e <p$mK is seci/ied as MEnM and t&e <data5"ileK is seci/ies
as in"ileIt*t) 4n 46K scrit MEnM looks /or lines w&ic& contain a
strin' FEnG and dislay t&e lines on t&e screen)
A.".2 An A3=
Script
4n 46K scrit contains an instruction /or w&at 46K will er/orm) It asks 46K
to look /or a attern in a record* and er/orms actions on a matc&ed attern) T&e
syntaA o/ an 46K scrit is as /ollows<
<patternK 7<actionsK8
4 <patternK could be a lo'ical eAression or a re'ular eAression)
#
T&e
<actionsK seci/ies actions /or t&e matc&ed attern) Eac& action in t&e curly
braces is searated by a semi9colon ?F;G@)
A."." A3= Prograing Str!ct!re
T&e 'eneral /orm o/ an 46K ro'ram is s&own
below<
.E-IN 7<initiali6ationK8
<pattern2K 7<actionSet2K8
<pattern1K 7<actionSet1K8
I
I
I
END 7<"inal "inalActionSetK8
#
6&ile a lo'ical eAression is usually imlemented by an i" statement* a re'ular
eAression returns tr!e w&en /indin' a matc&ed attern) T&e /ormal de/inition o/ a re'ular
eAression can be /ound in M3:N)
4)3 46K Pro'rammin' 223
Tab#e A=* Secial c&aracters used in re'ular eAressions
C&aracter .escrition
MIIIM Contain a re'ular eAression ?e)')* Mte*tM* MM matc&es e1ery line)@
` %atc& t&e be'innin' o/ a record only ?e)')* M`te*tM@
P %atc& t&e end o/ a record only ?e)')* Mte*tPM@
?@ %atc& any c&aracter inside ?e)')* ?te*t@@
?`<strK@ %atc& any c&aracter eAcet <strK ?e)')* ?`t`e`*`t@@
?<aKJ<bK@ %atc& any c&aracter between <aK and <bK
I %atc& any c&aracter ?e)')* Mte*IM@
N
%atc& Jero or more c&aracter in /ront o/ it ?e)')* Mte*
N
M@
I
N
%atc& any strin' o/ c&aracters
Y %atc& Jero or one re'ular eAression in /ront o/ it ?e)')* M?aJ6@YM@
4 %atc& one or more re'ular eAression in /ront o/ it ?e)')* M?aJ6@4M@
n, 4 word c&aracter ?i)e)* an al&anumeric or a F G@ w&ic& is eDui1alent to
?AJ\aJ60JG @
n s* n S* n t* n n 4 w & it e sace* a non9 w & it e9sace* a t ab c&arac t e r* and a n e w li n e c&arac t er
w&ic& consists o/ t&ree main stes<
1) +e/ore /ile rocessin'* run <initiali6ationK)
2) Cor eac& line o/ t&e inut /ile* run t&e action sets w&ic& matc& wit& t&e
associated
atterns)
3) 4/ter all t&e lines are rocessed* run <"inalActionSetK)
A.".$ Pattern Matching
T&e /irst art o/ an 46K scrit is a attern as seci/ied in <patternK) T&e
attern can be a lo'ical or a re'ular eAression) I/ t&is art e1aluates to Ftr!e*G
t&e corresondin' <actionsK will be taken)
T&e syntaA /or lo'ical eAression is t&e same as t&at used in Tcl ?see Sect) 4)1):
/or lo'ical oerators@) 4lt&ou'& sli'&tly more comlicated* re'ular eAression ro9
1ides a more concise and /leAible means to reresent a teAt o/ interest)
Syntactically* a re'ular eAression is enclosed wit&in a air o/ /orward slas&es
?FM*G e)')* MEnM@) Table 4)3 s&ows /reDuently used re'ular eAression symbols)
A.".+ 2asic Actions
T&e second art o/ an 46K scrit is to take <actionsK /or a matc&in'
<patternK) T&is section eAlains t&e basic actions in
46K)
22: 4 Pro'rammin' Essentials
Tab#e A=/ +uilt9in 1ariables
7ariables .escritions
P0 T&e current record
P2)P1)III T&e 1st* 2nd*))) /ield o/ t&e record
QILENA%E Name o/ t&e inut teAt /ile
QS ?Inut@ /ield searator ?a w&ite sace by de/ault@
#S ?Inut@ record searator ?a newline by de/ault@
NQ Number o/ /ields in a current record
N# Total number o/ records
OQ%T Cormat /or numeric outut ?EA$ be de/ault@
OQS Outut /ield searator ?a sace by de/ault@
O#S Outut record searator ?a newline by de/ault@
A=*=0=% Arithmetic ,&eration
+asic arit&metic oerations include addition* subtraction* multilication* di1ision*
and modulus) T&e arit&metic oerators are t&e same as 'asic Tcl oerators ?See
Sect) 4)1):@)
A=*=0=2 >ariab#es
4s an interreter* 46K does not need to declare data tye /or 1ariables) It can
simly assi'n a 1alue to a 1ariable usin' an assi'nment oerator ?F:G@) To a1oid
ambi'uity* 46K di//erentiates a 1ariable /rom a strin' by Duotation marks
?FHHG@) Cor eAamle* FvarG is a 1ariable w&ile FHvarHG is a strin' ?see EAamle
4)#@)
1,
46K also suorts one9dimensional arrays) Identi/ied by a sDuare bracket
??@@* indeAes o/ an array can be bot& numeric ?i)e)* a re'ular array@ or strin'
?i)e)* an associati1e array@) EAamle o/ arrays are node?2@* node?1@* and
link?H291H@)
4art /rom t&e abo1e user9de/ined 1ariables* 46K also ro1ides se1eral
use/ul built9in 1ariables as s&own in Table 4):)
A=*=0=* ,ut&uts
46K oututs a 1ariable or a strin' to a screen usin' eit&er FprintG or
Fprint"*G
w&ose syntaA are as /ollows<
print <item2K <item1K III
print"&<"ormatK)<item2K)<item1K)III'
1,
0nlike Tcl* 46K retrie1es t&e 1alue stored in a 1ariable wit&out a re/iA ?not like FPG in Tcl@)
4)3 46K Pro'rammin' 223
w&ere <item2K* <item1K* and so on can be eit&er 1ariables or strin's* and
<"ormatK is t&e /ormat o/ t&e outut) 0sin' Fprint*G a strin' needs to be
enclosed wit&in a Duotation mark ?HH@* w&ile a 1ariable could be indicated as it is)
E%ample +*;* .e/ine an 46K /ile FmyscriptIa,kG as s&own below)
O myscriptIa,k
.E-IN78
MEnM 7var : 20; print HNo !otation9 H var;8
MDeM 7var : 20; print HIn !otation9 H HvarH;8
END78
(un t&is scrit /or t&e inut teAt /ile Fin"ileIt*tG de/ined in EAamle 4)")
T&e /ollowin' result s&ould aear on t&e screen)
KKa,k J" myscriptIa,k in"ileIt*t
No !otation9 20
In !otation9 var
No !otation9 20
In !otation9 var
No !otation9 20
In !otation9 var
No !otation9 20
In !otation9 var
T&e abo1e 46K scrit rints out two 1ersions o/ t&e 1ariable Fvar)G T&e
uer line rints out t&e 1alue ?i)e)* 1,@ stored in t&e 1ariable Fvar)G In t&e lower
line* t&e 1ariable FvarG is enclosed wit&in a Duotation mark) T&ere/ore* t&e
strin' FvarG will be rinted instead)
T&e command Fprint"G ro1ides more rintin' /unctionality) It is 1ery
similar to /unction Fprint"G in CCC) In articular* it seci/ies t&e rintin'
/ormat as t&e /irst inut ar'ument) T&e subseDuent ar'uments simly ro1ide t&e
1alues /or t&e lace9&olders in t&e /irst inut ar'ument) T&e readers are
encoura'ed to /ind t&e details o/ t&e rintin' /ormat in any CCC book ?e)')* M18N@
or in M33N)
A."./ Redirection and O!tp!t to 5iles
46K does not &a1e a direct command to eAort t&e results to /iles) To do so* t&e
/ollowin' 0NIE redirection
11
commands can be used<
11
EAamles o/ 0niA outut redirection are Fa,k MEnM in"ileIt*t K o!tp!tIt*t*G
Fls K o!tp!tIt*t*G and Fp,d X ls)G
228 4 Pro'rammin' Essentials
K (edirect t&e standard outut
KK 4end t&e standard outut
X (edirect t&e standard outut to a command
Note t&at w&ile FKG redirects t&e outut to a new /ile* FKKG aends t&e outut
to an eAistin' /ile) I/ t&e /ile eAists* FKG will delete and recreate t&e /ile) T&e
command FK*G on t&e ot&er &and* aends t&e outut to t&e /ile wit&out destroyin'
t&e eAistin' /ile)
A.".4 Control Str!ct!re
46K suorts t&ree maBor tyes o/ selection and reetition control structures<
Fi"Melse*G F,(ile*G and F"or)G T&e syntaAes o/ t&ese control structures are
as /ollows<
i"&<conditionK' <actionSet2K ?else <actionSet1K@
,(ile&<conditionK' <actionsK
"or&<initiali6ationK;<conditionK;<endJo"Jloop
JactionsK' <actionsK
4'ain* w&en t&e actions contain more t&an one statement* eac& statement must be
terminated by a semi9colon ?i)e)* F;G@* and all o/ t&e statements must be embraced
wit&in curly braces)
46K also contains /our Bumin' control structures<
break ?EAit t&e loo@
continue ?(estart t&e loo@
neAt ?Process t&e neAt record@
eAit ?EAit t&e ro'ram@
A=/ "<ercises
1) (eeat EAamle 4)1 but write all t&e outut to /ile FconvertIo!tG usin' t&e
Tcl /ile c&annel)
2) Crom EAamle 4)3* do t&e /ollowin' items one by one) T&en run t&e ro'ram*
and obser1e and discuss t&e results)
a) (emo1e t&e 1ariable e*t5var*
b) %ake t&e 1ariable e*t5var a local 1ariable o/ t&e rocedure Fconvert5
proc*G
c) %ake t&e 1ariable e*t5var a local 1ariable o/ t&e main ro'ram* and
d) (emo1e t&e statement "l!s( stdo!t)
4): EAercises :"3
3) %odi/y EAamle 4)8 to take inut ar'uments as inut and outut /iles) I/ no
inut ar'uments are 'i1en* use Finp!tIt*tG and Fo!tp!tIt*tG as inut
and outut /iles* resecti1ely)
:) Crom EAamle 4)2* declare Pb!""erSi6e
as a) 4n inst1ar o/ class FNodeG
b) 4 1ariable o/ t&e obBect Pn
Cor eac& case* write an OTcl ro'ram to 1eri/y t&at Pb!""erSi6e is
declared roerly) Hint< 0se t&e instroc Fin"o)G
3) 6rite OTcl codes w&ic& make use o/ t&e abo1e otions /or instroc in"o in
Tables 4)1 and 4)2) Create your own eAamles)
8) 6rite an inut strin' w&ic& matc&es wit& each o/ t&e /ollowin' re'ular eAres9
sions) T&e inut strin' s&ould not matc& wit& ot&er re'ular eAressions)
M`Node MNodeP M?Nn@ode
MNodeI MNode
N
MNod?Ee@Y MNod?Ee@4
2) +ased on t&e inut /ile in EAamle 4)"* de1elo an 46K scrit to s&ow
a) Total number o/ FEnG e1ents*
b) T&e number o/ ackets t&at Node 3 recei1es* and
c) Total number o/ bytes t&at Node 3 recei1es)
") (eeat EAamle 4)#* but rint t&e result in a /ile Fo!t"ile It*t)G S&ow
t&e di//erence w&en usin' FKG and FKK)G
B
A Review of the Po#ymor&hism $once&t in ,,P
B=% 4unamenta#s of Po#ymor&hism
4s one o/ t&e main OOP concets* olymor&ism re/ers to t&e ability to in1oke t&e
same /unction wit& di//erent imlementation under di//erent conteAt) T&is concet
s&ould be simle to understand* since it occurs in our daily li/e)
E%ample B** Consider recetionists and &ow t&ey 'reet customers) Criendly*
moody* and rude recetionists 'reet customers by sayin' FLood mornin') How
can I &el you todayRG* F6&at do you wantRG* and F6&at do you wantR I5m
busy) Come back laterWWG* resecti1ely) 6e desi'n a class &ierarc&y /or
recetionists as s&own in Ci') +)1) T&e base class o/ t&e &ierarc&y is class
#eceptionist) +ased on t&e ersonality* we deri1e classes
Qriendly#eceptionist and %oody#eceptionist directly /rom class
#eceptionist) 4lso* we deri1e anot&er class #!de#eceptionist /rom
class %oody #eceptionist) T&e CCC code w&ic& reresents t&ese /our
classes is 'i1en below<
MMreceptionistIcc
2 Oincl!de HiostreamI(H
1 class #eceptionist 7
3 p!blic9
= void $reet&' 7co!t<<HSay9TnH;8;
> 8;
A class Qriendly#eceptionist 9 p!blic #eceptionist 7
B p!blic9
/ void $reet&'7
G co!t<<HSay9 -ood mornin$I Ho, can I (elp
yo! todayYTnH
20 8
22 8;
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 12* = Srin'er Science>+usiness %edia* !!C 2,12
:"3
23, + 4 (e1iew o/ t&e Polymor&ism Concet in OOP
4ig= B=% 4 olymor&ism
eAamle< (ecetionist class
&ierarc&y
=ece6tionist
.riendly=ece6tionist Moody=ece6tionist
=ude=ece6tionist
21 class %oody#eceptionist 9 p!blic #eceptionist 7
23 p!blic9
2= void $reet&' 7 co!t<<HSay9 W(at do yo!
,antYTnH; 8;
2> 8;
2A class #!de#eceptionist 9 p!blic %oody#eceptionist 7
2B p!blic9
2/ void $reet&'7
2G %oody#eceptionist99$reet&';
10 co!t<<HSay9 IZm b!syI Come back laterITnH;
12 8;
11 8;
13 main&' 7
1= Qriendly#eceptionist "5obj;
1> %oody#eceptionist m5obj;
1A #!de#eceptionist r5obj;
1B co!t<<HTnJJJJJJJJJJJJ Qriendly #eceptionist
JJJTnH;
1/ "5objI$reet&';
1G co!t<<HTnJJJJJJJJJJJJ %oody #eceptionist
JJJJJJJTnH;
30 m5objI$reet&';
32 co!t<<HTnJJJJJJJJJJJJ #!de #eceptionist
JJJJJJJTnH;
31 r5objI$reet&';
33 co!t<<HJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
JJJJTnH;
3= 8
Cunction main&' instantiates t&ree recetionist obBects) ObBects "5obj*
m5obj* and r5obj are o/ classes Qriendly#eceptionist* %oody
#eceptionist* and #!de#eceptionist* resecti1ely ?!ines 2:H28@) T&ey
'reet a customer in !ines 2"* 3,* and 32 by in1okin' /unction $reet&' in
+)1 Cundamentals o/ Polymor&ism :"2
!ines "H1,* 1:* and 1"H21* resecti1ely)
1
+y runnin' receptionist* t&e
/ollowin' results s&ould aear on t&e screen)
KKIMreceptionist
JJJJJJJJJJJJ Qriendly #eceptionist JJJJJJJJJ
Say9 -ood mornin$I Ho, can I (elp yo! todayY
JJJJJJJJJJJJ %oody #eceptionist JJJJJJJJJ
Say9 W(at do yo! ,antY
JJJJJJJJJJJJ #!de #eceptionist JJJJJJJJJ
Say9 W(at do yo! ,antY
Say9 IZm b!syI Come back laterCC
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
E%ample B*2* (emo1e !ine 1: in EAamle +)1 and run FIMreceptionistG
a'ain) T&e /ollowin' result s&ould aear on t&e screen<
KKIMreceptionist
JJJJJJJJJJJJ Qriendly #eceptionist JJJJJJJJJ
Say9 -ood mornin$I Ho, can I (elp yo! todayY
JJJJJJJJJJJJ %oody #eceptionist JJJJJJJJJ
Say9
JJJJJJJJJJJJ #!de #eceptionist JJJJJJJJJ
Say9
Say9 IZm b!syI Come back laterCC
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
Since class %oody#eceptionist does not de/ine /unction $reet ?!ine
1: is remo1ed@* it uses t&e /unction $reet&' in&erited /rom class
#eceptionist ?i)e)* rintin' FSay9G on t&e screen@)
EAamles +)1 and +)2 demonstrate t&e concets o/ olymor&ism t&rou'&
recetionists and &ow t&ey 'reet customers) 6&en in1okin' t&e same /unction
?e)')* $reet&'@* t&ree obBects o/ di//erent classes act di//erently ?e)')* by sayin'
di//erently@) EAamle +)1 s&ows a basic olymor&ism mec&anism* w&ere eac&
class &as its own imlementation) EAamle +)2 s&ows t&at it is also ossible not
to o1erride /unction $reet&')
2
1
Note t&at in !ine 1# /unction $reet&' o/ class %oody#eceptionist is in1oked in t&e
scoe o/ class #!de#eceptionist usin' F99)G
2
Cor eAamle* class %oody#eceptionist in&erits /unction $reet&' /rom class
#eceptionist)
232 + 4 (e1iew o/ t&e Polymor&ism Concet in OOP
B=2 Ty&e $asting an 4unction Ambiguity
In most cases* olymor&ism is /airly strai'&t/orward) 4 deri1ed class may in&erit
or o1erride /unctions /rom t&e base class) 6&en olymor&ism in1ol1es tye
castin'* t&e mec&anism in EAamles +)1 and +)2 may lead to di//erent results) To
see &ow* consider t&e /ollowin' eAamles)
E%ample B*$* (elace /unction FmainG in EAamle +)1 wit& t&e
/ollowin'<
2 main&' 7
1 Qriendly#eceptionist
N
"5pt;
3 %oody#eceptionist
N
m5pt;
= #!de#eceptionist
N
r5pt;
> "5pt : ne, Qriendly#eceptionist&';
A m5pt : ne, %oody#eceptionist&';
B r5pt : ne, #!de#eceptionist&';
/ co!t<<HTnJJJJJJJJJJJJ Qriendly #eceptionist JJJJTnH;
G "5ptJK$reet&';
20 co!t<<HTnJJJJJJJJJJJJ %oody #eceptionist JJJJTnH;
22 m5ptJK$reet&';
21 co!t<<HTnJJJJJJJJJJJJ #!de #eceptionist JJJJTnH;
23 r5ptJK$reet&';
2= co!t<<HJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
JJJJJTnH;
2> 8
6it& t&e abo1e code* t&e result /or runnin' IMreceptionist would be
t&e same as t&at in EAamle +)1) T&e maBor di//erence in t&e abo1e main&'
/unction is t&e use o/ ointers ?!ines 2H:@* instead o/ re'ular obBects ?in
EAamle +)1@)
E%ample B*/* In EAamle +)3* relace !ines 3 and : wit& t&e /ollowin'<
%oody#eceptionist
N
m5pt)
N
r5pt;
T&is is an eAamle o/ ambi'uity caused by tye castin') T&e ointer r5pt is de9
clared as a ointer to a %oody#eceptionist obBectO &owe1er* t&e
statement Fne, #!de#eceptionist&'G5 creates an obBect o/ tye #!de
#eceptionist) 6&en in1okin' a /unction ?e)')* $reet&'@* t&e key Duestion is
w&ic& class s&ould /unction $reet&' be associated wit&<
%oody#eceptionist ?i)e)* t&e declaration class@ or #!de#eceptionist
?i)e)* t&e construction class@R To answer t&is Duestion* we can simly run
FIMreceptionist*G and obtain t&e /ollowin' results<
KKIMreceptionist
JJJJJJJJJJJJ Qriendly #eceptionist JJJJJJJJJ
+)3 7irtual Cunctions :"#
Say9 -ood mornin$I Ho, can I (elp yo! todayY
JJJJJJJJJJJJ %oody #eceptionist JJJJJJJJJ
Say9 W(at do yo! ,antY
JJJJJJJJJJJJ #!de #eceptionist JJJJJJJJJJJJJ
Say9 W(at do yo! ,antY
JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ
Crom t&e abo1e result* t&e answer is t&e /ormer one<
%oody#eceptionist)
Consider t&e statement Fr5pt : ne, #!de#eceptionist)G T&e latter
art* Fne, #!de#eceptionist*G allocates memory sace to an obBect o/ class
#!de#eceptionist* and returns a ointer to t&e created obBect) T&e /ormer
art Fr5pt : G assi'ns t&e returned ointer to r5pt) Since r5pt is a ointer
to a %oody#eceptionist obBect* t&is statement imlicitly casts t&e created
#!de#eceptionist obBect to a %oody#eceptionist* be/ore t&e ointer
assi'nment rocess) It is now clear t&at t&e tye o/ r5pt be/ore and a/ter t&e
castin' is %oody#eceptionist
N
) T&ere/ore* /unction r5ptJK$reet&' is
associated wit& class %oody#eceptionist)
0nlike a re'ular obBect* a ointer needs two memory saces< one /or itsel/ and
anot&er /or t&e obBect t&at it oints to) T&e /ormer sace is created at t&e ointer
declaration* w&ile t&e latter is created usin' Fne,)G Cunction ambi'uity occurs
w&en t&e ointer is declared to oint to an obBect o/ one tye* but t&e ointed
obBect is created to store an obBect o/ anot&er tye) +y de/ault* t&e ointer and t&e
obBect will be associated wit& t&e declaration tye* not t&e construction tye)
B=* >irtua# 4unctions
T&e result in EAamle +)3 is di//erent /rom t&at in EAamle +)1) 6&en creatin'
a ointer by eAecutin' Fne, #!de#eceptionist*G we eAect t&e rude rece9
tionist to say F6&at do you wantR I5m busy) Come back laterWWG* not Bust F6&at do
you wantRG as in EAamle +):) To do so* a #!de#eceptionist obBect needs
to be associated wit& t&e construction tye not t&e declaration tye) In CCC* suc&
an association is carried out t&rou'& virtual functions)
0nlike re'ular /unctions* 1irtual /unctions always belon' to t&e construction
tye* re'ardless o/ tye castin') CCC declares a 1irtual /unction by uttin' a
keyword Fvirt!alG in /ront o/ t&e /unction declaration) Note t&at* t&e 1irtuality
roerty is in&eritable) 6e only need to declare t&e 1irtual /unction once in t&e
base class) T&e same /unction in t&e deri1ed class automatically in&erits t&e
1irtuality roerty)
E%ample B*1* In EAamle +):* relace !ine : /rom EAamle +)1 wit& t&e
/ollowin' line<
virt!al void $reet&' 7co!t<<HSay9TnH;8;
23: + 4 (e1iew o/ t&e Polymor&ism Concet in OOP
w&ic& declares t&e /unction $reet&' o/ class #eceptionist as
1irtual)
Since r5pt is created usin' Fne, #!de#eceptionist*G 1irtual /unction
r5ptJK$reet&' belon's to class #!de#eceptionist) 4t t&e declaration
F%oody#eceptionist
N
r5pt*G t&e ointer r5pt is created by its de/ault
constructor) Howe1er* t&e sace w&ere r5pt oints to ?i)e)*
N
r5pt@ is created
by t&e statement Fne, #!de#eceptionist)G Since a 1irtual /unction sticks to
t&e construction tye* t&e statement r5ptJK$reet&' in1okes /unction $reet
&' o/ class #!de#eceptionist) 4/ter runnin' IMreceptionist* we will
obtain t&e same result as t&at in EAamles +)1 and +)3)
B=/ Abstract $#asses an Pure >irtua# 4unctions
4n a'stract class ro1ides a 'eneral concet /rom w&ic& more seci/ic classes
deri1e) Con/ormin' to t&e olymor&ism concet* it seci/ies Fw&at to doG in
secial /unctions called pure virtual functions* and /orces its deri1ed classes to
de/ine t&eir own F&ow to doG by o1erridin' t&e ure 1irtual /unctions) Containin'
at least one ure 1irtual /unction* an abstract class is said to be incomplete since
it does not &a1e a F&ow to doG art) ConseDuently* no obBect can be initiated /rom
an abstract class) +y not imlementin' all 1irtual /unctions* t&e deri1ed class
would still be an abstract class ?i)e)* incomlete@* and cannot initiate any obBect)
CCC declares a ure 1irtual /unction by uttin' Fvirt!alG and F:0G at t&e
be'innin' and t&e end o/ /unction declaration* resecti1ely)
E%ample B*8* Consider a'ain t&e eAamle on recetionists and &ow t&ey 'reet
customers) 6e kee t&e class &ierarc&y in Ci') +)1 unc&an'ed) To make class
#eceptionist an abstract class* we modi/y EAamle +)3 by remo1in' !ines
: in EAamle +)1 relacin' t&e declaration o/ class #eceptionist in EAamle
+)1 wit& t&e /ollowin' codes<
2 class #eceptionist 7
1 p!blic9
3 virt!al void $reet&':0;
= 8;
4/ter runnin' FIMreceptionist*G we s&ould obtain t&e same results as in
EAamle +)1) In t&is eAamle* t&ree main comonents are related to t&e use o/ an
abstract class)
+ pure virtual function< Cunction $reet&' is declared in class #ecepti
onist as a ure 1irtual /unction ?!ine 3 in EAamle +)8@)
+n a'stract class< Containin' a ure 1irtual /unction $reet&'* class
#eceptionist is an abstract class) No obBect can be instantiated /rom
class #eceptionist) Class #eceptionist t&ere/ore acts as a temlate
class /or classes Qriendly#eceptionist* %oody#eceptionist* and
#!de #eceptionist)
:#2 + 4 (e1iew o/ t&e Polymor&ism Concet in OOP
Tab#e B=% .eclaration wit&
no imlementation*
declaration wit& no action*
and in1alid declaration
.eclaration EAamle
Pure 1irtual declaration virt!al void $reet&':0;
.eclaration wit& no action virt!al void $reet&' /';
In1alid declaration virt!al void $reet&';
+n instantia'le class< Classes Qriendly#eceptionist* %oody#ecepJ
tionist* and #!de#eceptionist must ro1ide imlementation /or /unc9
tion $reet&' ?see EAamle +)1@) 0nlike EAamle +)2* remo1in' t&e im9
lementation ?e)')* !ine 18 in EAamle +)1@ lea1es t&e deri1ed classes ?e)')*
%oody#eceptionist@ an abstract class* and t&e instantiation ?e)')* m5pt :
ne, %oody#eceptionist@ would cause a comilation error)
T&ere are t&ree related declarations /or a 1irtual /unction ?see Table +)1@) Cirst*
a ure 1irtual /unction is declared as eAlained abo1e ?e)')* virt!al void
$reet&' U 0;@) Secondly* a ?non9ure@ 1irtual /unction o/ a deri1ed instan9
tiable class must contain imlementation but may &a1e no action) Cor eAamle*
Fvirt!al void $reet&' /';G contains no action inside its curly braces)
T&is /unction o1errides t&e ure 1irtual /unction o/ its arent class* makin' t&e
class non9 abstract and instantiable) Cinally* consider a class w&ose arent class is
an abstract class) +y otin' out F/'G ?i)e* Fvirt!al void $reet&';G@* t&e
ure 1irtual /unction is le/t unimlemented and t&e class would still be an abstract
class) 4'ain* any obBect instantiation would lead to a comilation error)
3
+n
important note for NS2 users> Gou cannot opt out 'oth H:0I and H/'*I If you do
not want to provide an implementation= leave the curly 'races with no action
after the declaration* (therwise= NS2 will show an error at the compilation*
B=0 $#ass $om&osition2 An A&&#ication of Ty&e $asting
Po#ymor&hism
0to t&is oint* t&e readers may raise /ew Duestions) T&at is* w&y do we need
to cast an obBect to a di//erent tye and use t&e keyword virt!alR 6ouldn5t
it be easier to declare and construct an obBect wit& t&e same tyeR Cor eAamle*
can5t we use EAamle +)3 instead o/ EAamle +):R .oesn5t it remo1e /unction
ambi'uityR T&e answer is FyesGO ne1ert&eless* tye castin' makes t&e
ro'rammin' more scalable* ele'ant* and interestin') Cor t&is reason*
ro'rammin' wit& tye castin' is a common ractice in NS2)
3
Here* we assume t&at declaration and imlementation are in one /ile) 6&en declaration and
imlementation are searated in two /iles* you can ot out F/'G in a FI(G /ile and ro1ide t&e
imlementation in anot&er FIccG /ile)
B=6 Programming Po#ymor&hism with No Ty&e $asting2
An "<am&#e
EAamle +)2 below s&ows a scenario* w&ic& needs no 1irtual /unction) Howe1er*
we will see later t&at EAamle +)2 leads to ro'rammin' incon1enience as t&e
ro'ram becomes lar'er)
E%ample B*9* Consider a comany and &ow it ser1es a customer) T&e main
/unctionality o/ t&e comany is to ser1e customers) 4s a courtesy* t&e comany
'reets e1ery customer be/ore ser1in') 4ssume t&at t&e comany &as one
recetionist to 'reet t&e customer) T&e recetionist can be /riendly* moody* or
rude as seci/ied in EAamle +)1) T&e /ollowin' CCC code reresents t&e
comany wit& t&e abo1e descrition<
MMcompanyIcc
2 class Company 7
1 p!blic9
3 void serve&' 7
= $reet&';
> co!t<<HTnServin$ t(e c!stomer III TnH;
A 8;
B void $reet &' 78;
/ 8;
G class %oodyCompany 9 p!blic Company 7
20 p!blic9
22 %oodyCompany&'7employee5 : ne, %oody
#eceptionist;8;
21 void $reet&'7employee5JK$reet&';8;
23 private9
2= %oody#eceptionist
N
employee5;
2> 8;
2A int main&' 7
2B %oodyCompany my5company;
2/ my5companyIserve&';
2G ret!rn 0;
10 8
w&ere class %oody#eceptionist is de/ined in EAamle
+)1)
Class Company ?!ines 1H"@ &as two /unctions) Cunction serve&' in !ines
3H8 'reets t&e customers by in1okin' /unction $reet&') T&en* it ser1es t&e
customer by s&owin' t&e messa'e FServin$ t(e c!stomer IIIG on t&e
screen) T&e /unction $reet&' in !ine 2 &as no action in class Company* and
is imlemented by c&ild classes o/ class Company)
+)2 4 Scalability Problem Caused by Non9Tye Castin' Polymor&ism :#3
Class %oodyCompany ?!ines #H13@ deri1es /rom class Company) It &as
one moody recetionist stored in t&e 1ariable employee5 ?!ine 1:@) Class
%oodyCompany imlements /unction $reet&' by &a1in' employee5JK
$reet&' in !ine 12)
In t&e /unction main&'* an obBect my5company o/ class %oodyCompany
is instantiated in !ine 12) !ine 1" in1okes /unction serve&' associated wit&
t&e obBect my5company) +y runnin' t&e eAecutable /ile company* t&e /ollowin'
result will aear on t&e screen<
KKIMcompany
Say9 W(at do yo! ,antY
Servin$ t(e c!stomer III
w&ic& is Duite eAected /rom t&e code) Clearly* we do not need 1irtual /unctions in
t&is eAamle)
B=5 A Sca#abi#ity Prob#em $ause by Non.Ty&e $asting
Po#ymor&hism
T&e main roblem o/ olymor&ism wit& non9tye castin' is t&e scalability) 4s
t&e in&eritance tree becomes more comlicated* we may need to de1elo a lar'e
number o/ classes) Cor eAamle* suose we would like to c&an'e t&e recetionist
in t&e comany to be a /riendly recetionist) 6e will &a1e to de/ine anot&er class
as /ollows<
class QriendlyCompany 9 p!blic Company 7
p!blic9
QriendlyCompany&' 7 employee5 :
ne, Qriendly#eceptionist8
void $reet&' 7employee5JK$reet&';8;
private9
Qriendly#eceptionist
N
employee5;
8;
4lso* relace !ine 12 in EAamle +)2 wit&
QriendlyCompany my5company;
+y runnin' FIMcompany*G t&e /ollowin' result s&ould aear on t&e screen<
KKIMcompany
Say9 -ood mornin$I Ho, can I (elp yo! todayY
Servin$ t(e c!stomer III
T&e roblem is t&at a new Company class ?e)')* QriendlyCompany@ is re9
Duired /or e1ery new #eceptionist class ?e)')*
Qriendly#eceptionist@)
23" + 4 (e1iew o/ t&e Polymor&ism Concet in OOP
Curt&ermore* t&e comany may &a1e ot&er tyes o/ emloyee suc& as tec&nicians*
mana'ers* etc) I/ t&ere are ten classes /or recetionists and ten classes /or tec&ni9
cians* we need to de/ine 1,, classes to co1er all combination o/ emloyee tyes) In
t&e neAt section* we will s&ow &ow t&is scalability roblem can be a1oided usin'
class comosition)
B=7 The $#ass $om&osition Programming $once&t
Tye castin' acts as a tool w&ic& &els a1oid t&e scalability roblem) Instead o/
deri1in' all class combination ?e)')* 1,, classes o/ combinations o/ ten rece9
tionists and ten tec&nicians@* we may declare an a'stract user class obBect ?e)')*
#eceptionist@* and cast t&e abstract user class obBect to a more seci/ic obBect
?e)')* Qriendly#eceptionist@)
E%ample B*:* Consider a comany and &ow it ser1es a customer in EAamle +)2)
+y allowin' tye castin'* t&e code reresentin' t&e comany is 'i1en below<
MMcompanyIcc
2 class Company 7
1 p!blic9
3 void (ire&#eceptionist
N
r' 7
= employee5 : &#eceptionist
N
'r;
> 8;
A void serve&' 7
B employee5JK$reet&';
/ co!t<<HTnServin$ t(e c!stomer III TnH;
G 8;
20 private9
22 #eceptionist
N
employee5;
21 8;
23 int main&' 7
2= %oody#eceptionist
N
m5pt: ne, %oody#eceptionist
&';
2> Company my5company;
2A my5companyI(ire&m5pt';
2B my5companyI$reet&';
2/ ret!rn 0;
2G 8
4lso* to bind /unction $reet&' to t&e construction tye* we need to declare
/unction $reet o/ class #eceptionist as 1irtual) Here* we relace !ine
: in EAamle +)1 wit& Fvirt!al void $reet&';G or Fvirt!al void
$reet&' : 0;)G
6
o
l
y
m
o
r
6
h
i
s
m
+)" T&e Class Comosition Pro'rammin' Concet 23#
23#2
A/stract Class
(=ece6tionist)
inherit
Deri,e Class
(Moody=ece6tionist)
instantiate
A/stract 8ser Class
(0om6any)
8ser Class
(main)
declare
em6loyeeC
instantiate
myCcom6any
mC6t
use
em6loyeeC$Q4reet()
ty6e
castin4
-ind
(myCcom6any$Qhire(mC6t)
instantiate
4ig= B=2 4 dia'ram o/ t&e class comosition concet wit& tye castin' olymor&ism
Class Company declares a 1ariable employee5 as a #eceptionist
ointer in !ine 11) T&e comany &ires an emloyee by in1okin' /unction
(ire&r' in !ines 3H3) Takin' a #eceptionist
N
obBect* r* as an
inut ar'ument* /unction (ire&r' assi'ns an inut #ecectionist ointer
to its ri1ate 1ariable employee5) In !ines 8H#* t&e comany serves t&e
customers as it does in EAamle +)2)
In /unction Fmain&'*G an obBect o/ class Company* my5company* is created
in !ine 13) In !ine 18* my5company &ires an emloyee m5pt w&ic& is a
ointer to a %oody#eceptionist obBect) Crom !ines 3H3* /unction
(ire&m5pt' casts t&e ointer m5pt to a #eceptionist ointer) Since t&e
/unction $reet&' o/ class %oody#eceptionist is 1irtual* employee5J
K$reet&' is associated wit& t&e construction tye in !ine 1: ?i)e)* class
%oody#eceptionist@) +y runnin' FIMcompany*G we will obtain t&e
/ollowin' result<
KKIMcompany
Say9 W(at do yo! ,antY
Servin$ t(e c!stomer III
w&ic& is t&e same as t&at in EAamle +)2)
4s s&own in Ci') +)2* t&e class comosition ro'rammin' concet wit& tye9
castin' olymor&ism consists o/ /our main class tyes)
4n a'stract class ?e)')* #eceptionist@ is a temlate class)
4 derived class ?e)')* classes %oody#eceptionist@ deri1es /rom t&e abo1e
abstract class)
4n a'stract user class ?e)')* class Company@ declares obBects o/ t&e a'stract
class ?e)')* #eceptionist@) It uses t&e /unctions o/ t&e abstract class wit&out
t&e need to know t&e detailed imlementation o/ t&e abstract class) In EAam9
le +)"* class Company does not need to know w&at tye o/ #eceptionist
t&e employee5 is* nor &ow t&e employee5 'reets t&e customers)
4 user class ?e)')* main@ declares obBects o/ t&e derived class ?e)')* %oody
#eceptionist@) It makes t&e abstract class more seci/ic by bindin' ?e)')*
usin' /unction (ire&r'@ t&e abstract 1ariable ?e)')*
N
employee5@ belon'in'
to t&e abstract user obBect ?e)')* my5company@ to t&e deri1ed obBect ?e)')*
m5pt@)
T&e concet o/ class comosition is to &a1e an abstract user class ?e)')*
Company@ declare its 1ariable /rom an abstract class ?e)')* #eceptionist@ and
later cast t&e declared obBect ?e)')* employee5@ to a more seci/ic tye ?e)')*
%oody#eceptionist@) In articular* t&e mec&anism consists o/ /our /ollowin'
stes<
1) .eclare an abstract class ?e)')* #eceptionist@)
2) Crom wit&in an abstract user class ?e)')* Company@* declare ?e)')* (ecetionistd
employee5@ and use ?e)')* employee5JK$reet&'@ obBects o/ t&e abo1e
abstract class)
:
3) In a user class ?e)')* main&'@*
a) Instantiate an obBect ?e)')* my5company@ o/ t&e abstract user class ?e)')*
Company@)
b) Instantiate an obBect ?e)')*
N
m5pt@ o/ t&e deri1ed class ?e)')* %oody
#eceptionist@)
:) +ind ?e)')* usin' (ire&r'@ t&e abstract class obBect ?e)')*
N
employee5@ in
t&e abstract user class ?e)')* Company@ to t&e obBect initiated /rom wit&in t&e
user class ?e)')*
N
m5pt@) Since t&e latter obBect class deri1es /rom t&e /ormer
one* t&e tye castin' is /airly strai'&t/orward)
To c&an'e t&e comany5s recetionist to be a /riendly recetionist* we only
need to c&an'e /unction main as /ollows* wit&out &a1in' to modi/y ot&er arts
o/ t&e codes<
int main&'
7 Qriendly#eceptionist
N
"5pt;
"5pt : ne, Qriendly#eceptionist&';
Company my5company&';
my5companyI(ire &"5pt';
my5companyIserve&';
ret!rn 0;
8
:
4'ain* declaration o/ a too seci/ic ?e)')* %oody#eceptionist as oosed to
#eceptionist@ class in non9tye9castin' olymor&ism leads to t&e scalability roblem) 4s
t&e ro'ram becomes lar'er* we need to rede/ine classes /or e1ery new class* &ence substantially
increasin' t&e total number o/ classes) To a1oid t&e scalability roblem* we need to declare
classes to be as 'eneral as ossible) T&is 'eneral class can later be cast as a more seci/ic class)
To see &ow tye castin' &els a1oid scalability* consider t&e abo1e eAamle
w&ere a comany may &a1e one o/ ten ossible recetionist classes and one o/ ten
ossible tec&nician classes) 6it&out tye castin'* we need to de/ine 1,, classes
to co1er all t&e combination o/ recetionists and tec&nicians in addition to one
base class Company) +y allowin' tye castin'* we can declare two 1ariables ?o/
abstract classes #eceptionist and Tec(nician@ in a comany) In t&e main
ro'ram* we can instantiate a recetionist and a tec&nician /rom any o/ t&ese
#eceptionist and Tec(nician classes) 4/ter instantiatin' recetionist
and tec&nician obBects /rom t&e deri1ed class* we can cast t&e instantiated obBects
back to classes #eceptionist and Tec(nician and assi'n t&em to t&e
comany) 0nder t&e same scenario* t&e class comosition concet reDuires only
2, classes /or recetionists and tec&nicians* and t&ere/ore* 'reatly alle1iates t&e
scalability roblem)
$
BS- +ink +ist an Bit +eve# 4unctions
$=% BS- +ink +ist
Similar to an array* a link list is a data structure w&ic& can contain a collection o/
data items M18N) !ink lists are imlemented usin' ointers) T&ere/ore*
ro'rammers do not need to seci/y memory reDuirement /or a link list) T&e
memory is allocated to t&e link list at runtime)
NS2 de/ines macros /or link lists in t&e /ile Tns$lib$bsd9list)& as /ollows<
LIST HEAD&<nameK)<typeK'<
.eclare a str!ct data tye w&ic& models a &ead ointer to t&e link
list) T&e name o/ t&e data tye is <nameK* and t&e data tye o/ eac&
item in t&e link list is <typeK)
LIST ENT#[&<typeK'<
.eclare a str!ct data tye w&ic& models an entry in a link list) T&e
data tye o/ eac& item in t&e link list is <typeK)
LIST INSE#T AQTE#&(ead)elm)"ield'<
Insert
N
<elmK as t&e /irst element o/ t&e link list w&ose &ead ointer
is <(eadK* w&ere <"ieldK is a str!ct 1ariable containin'
ointers w&ic& make u t&e link list)
$=2 Bit +eve# 4unctions
NS2 emloys se1eral CCC bit le1el oeration /unctions)
bcopy&p2)p1)n'
Coy n bytes /rom
N
p2 to
N
p1)
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 1"* = Srin'er Science>+usiness %edia* !!C 2,12
:##
References
b6ero&p)n'
Set /irst n bytes o/
N
p to be
Jero)
bsearc(&keypt)arrpt)n!m)bytes)cmp "n'
!ook /or
N
keypt wit&in arrpt w&ic& contains n!m elements*
eac& wit& siJe bytes) It returns a ointer to t&e matc&in' element* and
Jero i/ no matc&in' key is /ound) Cor eac& element in t&e array
arrpt* t&is /unction /eeds
N
keypt and t&e array element as t&e
inut ar'uments o/ t&e /unction cmp5"n) T&e /unction cmp5"n
must return ne'ati1e* Jero* and ositi1e 1alues i/
N
keypt is less
t&an* eDual to* and 'reater t&an array element* resecti1ely)
3,, C +S. !ink !ist and +it !e1el Cunctions
1) 4) S) Tanenbaum* Computer Networks* 3rd ed) Prentice Hall* 1##8)
2) () E) S&annon* FIntroduction to t&e art and science o/ simulation*G in Proc* of the $2th
conference on 6inter simulation -6SCJ;:0* 1#"#)
3) 6) T) Kasc&* b) () 6ard* and b) 4ndrusenko F6ireless network modelin' and simulation
tools /or desi'ners and de1eloers*G IEEE Communication %a'aJine* ) 12,H122* %arc&*
2,,#) Proc* of the $2th conference on 6inter simulation -6SCJ;:0* 1#"#)
:) () L) In'alls* FIntroduction to simulation< Introduction to simulation*G in 6SC J22>
Proceedings of the $/th conference on 6inter simulation) 6inter Simulation Con/erence*
2,,2* ) 2H18)
3) 6) H) Tranter* et al)* Principles of Communication Systems Simulation) Prentice Hall* 2,,:)
8) 4) Paoulis and S) 0) Pillai* Pro'a'ility= #andom ?aria'les and Stochastic Processes* 2nd
ed) %cLrawHill* 2,,2)
2) 6) H) Press* et al)* Numerical #ecipes in C* 2nd ed) Cambrid'e 0ni1ersity Press* 1##2)
") () %) Loldber'* Parallel and 4istri'uted Simulation Systems) bo&n 6iley ] Sons* Inc)* 2,,,)
#) b) +anks andI) b) S) Carson* 4iscrete)Event Systems Simulation) Prentice9Hall* Inc)* 1#":)
1,) T&e Network Simulator 6iki) MOnlineN) 41ailable< &tt<$$n sna m) i s i )e du$n s n a m$ind e A)&$
11) T&e Network Simulator 6ikiHNS92Trace Cormats) MOnlineN) 41ailable< & tt <$$ nsna m )i s i) edu $
nsnam$$indeA)&$NS92 Trace CormatseOld 6ireless Trace Cormats
12) T&e Network Simulator H ns92) MOnlineN) 41ailable< & tt <$$ ww w )i s i) edu $ nsna m $ ns$
13) %) Lreis) Tutorial /or t&e Network Simulator NS2) MOnlineN) 41ailable< & tt <$$ww w )i s i) edu $
nsnam$ns$tutorial$
1:) b) C&un' and %) Clayool) Ns by eAamle) MOnlineN) 41ailable< & tt <$$ n il e )w i) edu $N S $
13) T&e Network Simulator 6ikiHContributed Code) MOnlineN) 41ailable< & tt <$$ nsna m )i s i) edu $
nsnam$indeA)&$Contributed Code
18) P) .eitel and H) .eitel* CCC <ow to Program= 9th Edition* Pearson* 2,1,) :t& ed) %cLraw9
Hill$Osborne %edia* 2,,2)
12) K) Call and K) 7arad&an) ?2,,2* 4u')@ T&e ns manual ?/ormerly known as ns notes and
documentation@) MOnlineN) 41ailable< & tt <$$ ww w )i s i) edu $ nsna m $ ns $ ns 9 docu m en t a ti on ) & t ml
1") (efseauA et Per/ormances) NS 2)28 source ori'inal< Hierarc&ical indeA) MOnlineN) 41ailable<
& tt <$$ www 9 r )li 8 ) /r $ ns 9 doc $ ns228 9 doc $ & t m l$ & i erarc& y ) & t m
1#) T) H) Cormen* et al)* Introduction to +lgorithms* 2nd ed) %IT Press and %cLraw9Hill* 2,,1)
2,) %) %at&is* et al)* TCP selective acknowledgement options* (CC 28" Std)* 1##8)
21) b) Kurose) T&e TCP$IP course website) MOnlineN) 41ailable< & tt <$$ ww w ) ne t w orksorcer y ) co m$
en$rotocol$ud)&tm
22) b) C) Kurose and K) 6) (oss* Computer Networking> + Top)4own +pproach) Pearson
4ddison9 6esley* 2,,")
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 * = Srin'er Science>+usiness %edia* !!C 2,12
3,1
2:8 (e/erences
23) 7) PaAson and %) 4llman* Computing TCPJs #etransmission Timer* (CC 2#"" Std)*
No1ember
2,,,)
2:) C) E) Perkins* +d <oc Networking* 4ddison96esley* 2,,1)
23) P) !5Ecuyer* FLood arameters and imlementations /or combined multile recursi1e
random number 'enerators*G (perations #esearch* 1ol) :2* no) 1* ) 13#H18:* 1###)
28) .) !ibes* F4 debu''er /or Tcl alications*G in TclATk 6orkshop* bune 1##3) MOnlineN)
41ailable< & tt <$$ e Aec t) n i s t) ' o 1 $t c l 9 de b u' $t c l 9 de b u' ) s )S
22) T&e L.+ .e1eloers) L.+< T&e LN0 roBect debu''er) MOnlineN) 41ailable< &tt<$$www)
'nu)or'$so/tware$'db$
2") T) Nanda'oal* S) !u* and 7) +&ar'&ar1an F4 uni/ied arc&itecture /or t&e desi'n and
e1aluation o/ wireless /air Dueuin' al'orit&ms*G 5(BIC(5;;* ) 132H1:2* 1###)
2#) S) San/ilio) 4n introduction to t&e Tcl ro'rammin' lan'ua'e) MOnlineN) 41ailable< &tt<$$
ww w )i n 1 ece ) o r' $t cl w i s e
3,) How can I do mat& in Tcl* 6elcome to t&e Tclers 6ikiW* & tt <$$wi k i)t c l)t k $ 32 "
31) +erkeley Continuous %edia Toolkit) OTcl tutorial) MOnlineN) 41ailable< & tt <$$ b m rc ) ber k e l e y)
edu$researc&$cmt$cmtdoc$otcl$
32) 4) (obbins and .) Lilly* Eni% in a Nutshell> System ? Edition) O5(eilly ] 4ssociates* Inc)*
1###)
33) 4n 46K rimer) MOnlineN) 41ailable< & tt <$$ww w ) 1 ec t ors it e ) ne t$t s a w k ) & tml
3:) 6ikiedia) (e'ular eAression) MOnlineN) 41ailable< & tt <$$ en )wi k i ed i a ) o r' $wi k i$ ( e 'u l a r
eAression
33) 7) PaAson and %) 4llman* #&C 2;::> Computing TCPJs #etransmission Timer*) MOnlineN)
41ailable< & tt <$$ ww w )i e t / ) o r' $ r/c $ r/c2#"" )t A t
38) C) Clynt* TclATk> + 4eveloperJs Duide* Second Edition* %or'an Kau/mann* 2,,3)
32) C) E) Perkins and E) %) (oyer F4d9&oc On9.emand .istance 7ector (outin'*G
IEEE 6orkshop on 5o'ile Computing Systems and +pplications* 1###* !4)
3") %) Sc&wartJ* 5o'ile 6ireless Communications* Cambrid'e 0ni1ersity Press* 2,,3)
3#) IEEE Standard for 6ireless .+N 5edium +ccess Control and Physical .ayer Specification=
P:22** IEEE* 1###)
:,) T) Issariyakul* E) Hossain* and .) I) Kim* F%edium access control rotocols /or wireless
mobile ad &oc networks< Issues and aroac&es*G 6iley Interscience 6ireless
Communications and 5o'ile Computing* 1ol)3* no) "* .ec)* 2,,3)
;enera# 'ne<
A
4bstract class* :#,
4cknowled'ment* 211
cumulati1e* 211
dulicated* 211
4cti1ities* "
4'ent
de/inin' new* 222
Null* 222
0.P* 223
4ntannae* 331
4O.7* 3,3* 312
construction rocess* 311
acket /low* 312
acket tyes* 3,8
timers* 313
4lication* 2,#* 223
4lication layer* :
4(P* 318
4(I* 3:3
4utomatic (eeat reIuest* 3:3
46K* 3:
B
+a' o/ bits* 1",
+inary eAonential backo//* 232
+it maskin'* ::#
dia'ram* ::#
mask* ::#
masked 1alue* ::#
maskin' rocess* ::#
+it s&i/tin'* :31
+reakoints* 321
$
Callback mec&anism* 181
C&ain o/ e1ents* 22
Classi/ier* 11:
Command* 28
Comiled &ierarc&y* 28* :1
Con/idence inter1al* #
Con'estion a1oidance* 212
Con'estion control* 212
Con'estion window* 212
close* 212
oen* 212
Constant bit rate* 2":
Constant9bit9rate ?C+(@ tra//ic* 2#
Con1ention* 23
-
.ata ayload* 122* 2,,
.ebu''in'* 38#
commands* 322
.e/ault 1alues* :#
.eendency rules* 38
.escritor /ile* 33
.iscrete9e1ent simulator* 22
.isatc&* 2"
.isatc&in' time* 2"
.ownstream* 28
"
Entities* 2
Error
comilation* 32,
runtime* 32,
Error model* :33
dia'ram* :3"
main mec&anism* ::3
E1ent9dri1en simulation* 13
E1ents* 22
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 * = Srin'er Science>+usiness %edia* !!C 2,12
3,3
2:" Leneral IndeA
EAiration actions* :,#
EAonential On$O//* 2"3
4
Cast retransmit* 213
Cirin' time* 2"
Corwardin' obBect* 28
Cree acket list* 12:
arc&itecture* 123
CTP* 2#
;
Llobal 1ariables* "
LO.* 33"
H
Handle* 22* 82
Handler* 2"
Has& classi/ier* 11#
Has& entry* 11#
Has& key* 11#
Has& table* 11#
Has& 1alue* 11#
Header* 3
Heler obBect$class* #"
'
IEEE ",2)11* 31"
carrier sensin'* 32#
collision* 328
collision a1oidance ?C4@* 31"
.CC* 31"
Cour9way &ands&ake* 31"
ICS* 31#
N47* 31#* 331
recei1in'* 328
retransmission* 328
sendin'* 323
timers* 323
Instance rocedure* 28
Instance 1ariable* 28
Instroc* 22* 28
Inst1ar* 22* 28
Inter9burst transmission inter1al* 2"3
Inter/ace* 2
Interreted &ierarc&y* 28* :1
+
!ayerin'* 2
!ink layer* 3* 313
!ow le1el network* 2,#
M
%4C
NS2 states* 31#
make* 33
make/ile* 33
%edium access control* 312
%et&od bindin'* 33
%I+* 321
%obile node arc&itecture*
2#8 construction rocess*
2#" &ierarc&y* 2#:
acket /low* 2#2
%obility
cbr'en utility* 3:2
deterministic* 332
random* 33#
scenario /iles* 3:3
setdest utility* 3:1
%odulo maskin'* :3,
N
Network con/i'uration &ase* 22
Network limited* 232
Network obBect$class* #"
Node* 111 arc&itecture* 112
construction rocess* 1:1
NS2 data tye* 3,
NsObBect* #"
,
O//set* 1",
comutation* 1#3
OSI re/erence model* :
OTcl command* 33
in1ocation* 33* 3#
returnin' structure* 38
syntaA* 33
OTcl met&od* 1"2
O1erloadin' oerator* 32"
P
Packet
actual acket* 18#
allocation* 123* 12"
arc&itecture* 12,
as an e1ent* 122
customiJation* 2,2
Packet bu//erin'* 131
Leneral IndeA 3,3
Packet &eader* 1",
access mec&anism* 1#,
acti1e rotocol* 122* 1#:
common* 1"2
construction rocess* 1#:
IP* 1"3
TCP* 231
Packet &eader mana'er* 122* 1#3
arc&itecture* 1#:
initialiJation* 1#:
Packet sc&eduler
6ei'&ted Cair Iueuin' ?6CI@* 38"
Packet tracin'
tye* 3#:
Packet transmission time* 131* 138
Packet9related obBect$class* #"
Packet&eader
arc&itecture* 1",
Pareto On$O//* 2"3
Payload tye* 1":
Peers* 2
P&ysical layer* 3
Port classi/ier* 11"
Primiti1e* 2
Proa'ation delay* 131
Protocol* 2
Protocol seci/ic &eader* 121* 1"8
acti1ate* deacti1ate* 2,3
Psuedo9random number 'enerator* :2:
Pure 1irtual /unction* :#,
?
Iueue
rioritiJed* 312
Iueue blockin'* 181
R
(andom number 'enerator* "* :2:
(andom scenario* :2#
(andom 1ariable
dia'ram* :31
(eeatability* #
(esource* 2
(etransmission timeout ?(TO@* 211
(NL* :2:
(ound tri time ?(TT@* 211
(oute lo'ic* 111* 132
(outer* 111
(outin'
con/i'uration rocess* 1:3
terminolo'y* 111
(outin' a'ent* 111
(outin' al'orit&m* 111
(outin' loo* 3,8
(outin' mec&anism* 111
(outin' module* 111* 123
name* 131
(outin' rotocol* 111
(outin' rule* 111
(outin' table* 111
(TO* 211 bounded*
23# comutation*
211 unbounded*
238
(TT* 211
samles* 211
smoot&ed* 211
1ariation* 211
S
Sc&eduler* "2
dynamics o/ uniDue I.* "8
Sc&eduler and Simulation Clock* "
Seed* :23
Se'ment* :
Ser1ice* 2
S&adow obBect* 28
Simle!ink
arc&itecture* 132
OTcl constructor* 13:
Simulation clock* 11
Simulation &ase* 2"* #2
Simulation timeline* 22
Simulation9related obBect$class* #"
Simulator* "#
Slot* 11:
Slow start* 212
Slow start t&res&old* 212
State 1ariables* "
Statistics 'at&erer* "
T
Tar'et* 28
Tcl simulation scrit* 23* 3,* :3
TclClass
de/inin' your own* :2* 81
eAamle* :8
namin' con1ention* :"
TclCommand* 8,
TclObBect creatin'*
83 re/erencin'*
82
TCP* 21,
recei1er* 233
23, Leneral IndeA
TCP ?cont*@
tick* 232
1ariants* 21:
TCP$IP re/erence model* :
T&res&old
carrier sensin'* 332
acket recetion* 332
Time9deendent simulation* 11
Time9dri1en simulation* 12
Timeout* 211
Timer* :,#
li/e cycle* :1,* :13
Timer eAiration* :,#
Trace c&annel* 3",
Trace /ormat* 3#" new
wireless* :,1
acket tracin'* 3#8
TCP* 323
wireless* 3##
Traceable 1ariable* 323* 322
Tracer* 32"
Tracin'
1ariable
acti1ation* 32:
comonents* 328
/ormat* 3"1
Tra//ic 'enerator* 2",
Tra//ic trace* 2"8
Transmission Control Protocol* 21,
Transort layer* :
Transort layer a'ent* 2,#
recei1in' a'ent* 2,#
sendin' a'ent* 2,#
9
0.P* 2,#
0stream* 28
0ser .ata'ram Protocol* 2,#
>
7ariable bindin'* :"
7ariable 1iewer* 321
7irtual /unction* :"#
W
6ired9cum9wireless* 2#3
6ireless c&annel* 333
$oe 'ne<
A
4cker
declaration* 232
/unctions* 23"
1ariables* 232
4'ent* 21"
attac&9a* 22:
c&annel * 3":
/unctions* 21"
1ariables* inst1ars* 21"
4'ent$Null* 222
4'ent$TCP
inst1ars* 232
4'ent$0.P* 223
4O.7
classes* 3,#
declaration* 3,#
/iles* 3,#
rec1* 313
timers* 31:
4.ata
declaration* 2,1
/unctions* 2,,
1ariables* 2,,
4.ataTye
declaration* 2,1
4lication
declaration* 222
/unctions* 22"
OTcl commands* 2",
1ariables* 228
4lication$Tra//ic$C+(
inst1ars* 2"3
4lication$Tra//ic$EAonentia
l inst1ars* 2"8
4lication$Tra//ic$Pareto
inst1ars* 2"2
ar'c* ::
ar'1* ::
4tE1ent* ",
4tHandler* ",
B
+ase(outin'%odule* 131
declaration* 132
/unctions* 131
1ariables* 131
+aseTrace
declaration* 3#3
/unctions* 3#3
OTcl commands* 3#3
1ariables* 3#2
$
C+( Tra//ic
declaration* 2""
/unctions* 2""
1ariables* 2"2
cbr'en)tcl* 3:2
C&annel
declaration* 333
rec1* 33:
Classi/ier
declaration* 113
/unctions* 113
OTcl commands* 118
1ariables* 11:
T) Issariyakul and E) Hossain* Introduction to Network Simulator NS2*
.OI 1,)1,,2$#2"919:81:91:,893 * = Srin'er Science>+usiness %edia* !!C 2,12
3,2
232 Code IndeA
CommonHeaderClass* 1#,
bind o//set* 1#,
create* 83
-
de/ault(NL* :23
delete* 82
.estHas&Classi/ier
declaration* 123
/unctions* 122
.roTail* 183
duleA9link* 133
"
EmbeddedTcl* :1
Error%odel
declaration* ::1
/unctions* ::2
inst1ars* :32
unit* ::#
1ariables* ::,
E1ent* 2"
;
LO.* 33#
H
Handler* 2"
Has&Classi/ier
declaration* 121
/unctions* 121
1ariables* 12,
&dr cmn* 1"2
access* 1"2* 1#2
declaration* 1"2
/unctions* 1"2
tye * 1":
1ariables* 1"2
&dr i
declaration* 1"3
1ariables* 1"3
&dr tc
declaration* 232
1ariables* 231
'
install* 2:
Inst7ar* :1
declaration* 322
int32 t* 1"3
+
!ink.elay* 138
/unctions* 138
1ariables* 138
!!* 313
declaration* 318
rec1* 318
M
%ac
declaration* 31#
/unctions* 321
1ariables* 31#
%ac",2 11
timers* 32:
%ac",2 11
backo//Handler* 323
collision* 32"
declaration* 31#
/unctions* 321
rec1* 323
rec1 timer* 322
rA resume* 322
send* 323
send timer* 32"
timers* 33,
tA resume* 32#
1ariables* 31#
%4C %I+* 321
%obileNode
declaration* 2#:
start* 3:,
%6% ?%aAimum 6indow %ask@* 23"
%6S ?%aAimum 6indow SiJe@* 232
N
new* 83
Node
add9route* 1:,
attac&9a'ent* 13"
delete9route* 1:,
inst1ars* 133
Node$%obileNode
add9inter/ace* 3,3
comosition* 3,3
ns addr t* 1"3
addr * 1"3
ort * 1"3
NsObBect* 1,,
NsObBect<<&andle* ",
Code IndeA 3,#
P
in/o* 1":
name* 1":
Packet* 12,
accessdata* userdata* setdata* datalen* 2,3
declaration* 121
/unctions* 121
1ariables* 12,
acket in/o* 1":
acket t* 1":
Packet.ata
declaration* 2,2
/unctions* 2,,
1ariables* 2,,
PacketHeaderClass* 1"2
declaration* 1""
1ariables* 1"2
PacketHeader%ana'er
declaration* 1#3
PacketIueue* 13#* 18,
/unctions* 13#
1ariables* 13#
P&y
declaration* 332
rec1* 33:
PH; %I+* 321
?
Iueue* 13"
/unctions* 13#
rec1* 181
resume* 183
1ariables* 13"* 18,
R
(andom7ariable
declaration* :32
/unctions* :31
1ariables* :31
(NL* :22
instrocs* :2"
(oute!o'ic
declaration* 133
/unctions* 133
instrocs* 13:
1ariables* 132
(outin' module
1ariables* 128
(t%odule* 12#
instrocs* 12#
inst1ars* 12#
(t%odule$+ase* 131
S
Sc&eduler at*
"1 clock*
"3
disatc&* ":
instance* "3
sc&edule* ":
Se'mentation /ault* 321
setdest* 3:1
Simle!ink
errormodule* :32
insert9linkloss* :3"
inst1ars* 132
trace* 3""
simleA9link* 133
Simulation
attac&9a'ent* 13#
Simulator* #1 at*
"1 connect*
228
create9aod19a'ent* 311
create9trace* 3""
create9wireless9node* 3,1
inst1ars* "#* #,
link9lossmodel* :3"
lossmodel* :32
node* 1:1
node9con/i'* 113
otions* 2#2
wireless* 2##
run* #3
trace9all* 3"8
trace9Dueue* 3"2
SlitObBect* 82
T
Tcl* :1
/unctions* 8"* 8#* 21
TC! E((O(* 32
TC! OK* 32
TclC!* 22* 23* :1
TclClass* :1
TclCommand* :1
TclObBect* :1* 322
/unctions* :"
trace* 3",* 3"2
trace7ar* 3"2
Tc4'ent attac&*
3": constants*
28"
/unctions* 2:2* 23,* 23#* 282
trace* 3",
23: Code IndeA
Tc4'ent ?cont*@
trace7ar* 3",
1ariables* 232
TcSink ack* 2:,
declaration* 2:1
rec1* 2:,
Timer
cross re/erencin'* :1#
instrocs* :11
inst1ars* :11
TimerHandler
declaration* :13
/unctions* :13
1ariables* :1:
TimerStatus* :1:
Trace
declaration* 3#,
/unctions* 3"#
OTcl commands* 3#1
1ariables* 3"#
TracedInt
declaration* 32#
/unctions* 32"
1ariables* 32"
Trace.ouble
eAamle* 323
Traced7ar
declaration* 32#
1ariables* 32"
TraceInt
eAamle* 323
Tra//icLenerator
/unctions* 2"1
1ariables* 2"1
Tra//icTimer
declaration* 2":
eAire* 2":
9
0d4'ent* 223
declaration* 22:
OTcl commands* 228
sendms'*idle* 223
W
6irelessC&annel
declaration* 333
send0* 333
6irelessP&y
declaration* 332
send.own* 33:
send0* 338

Вам также может понравиться