SlideShare uma empresa Scribd logo
1 de 75
Introduction To NS-2Introduction To NS-2
By
Arshad Ahmad Khan Mohammad
Part Time Research Scholar (CNIS)
KL University, Andhra Pradesh
India,
.
Outline Of PresentationOutline Of Presentation
 IntroductionIntroduction
 InstallationInstallation
 ArchitectureArchitecture
 Tcl & Otcl ExamplesTcl & Otcl Examples
 Simulation StepsSimulation Steps
 Examples (Wired)Examples (Wired)
 Examples (Wireless)Examples (Wireless)
IntroductionIntroduction
 About NS2About NS2
 Advantages of NS2Advantages of NS2
 NS2 Supported Protocols(Wired &NS2 Supported Protocols(Wired &
Wireless)Wireless)
Arshad KhanArshad Khan 44
Network Simulation *Network Simulation *
Motivation:Motivation:
 Learn fundamentalsLearn fundamentals
of evaluatingof evaluating
networknetwork
performance viaperformance via
simulationsimulation
•
Overview:Overview:
 fundamentals offundamentals of
discrete eventdiscrete event
simulationsimulation
 ns-2 simulationns-2 simulation
Arshad KhanArshad Khan 55
Why Simulation? *Why Simulation? *
 real-system notreal-system not available, is complex/costly oravailable, is complex/costly or
dangerousdangerous ((eg: space simulations, flighteg: space simulations, flight
simulations)simulations)
 quickly evaluate designquickly evaluate design alternativesalternatives (eg:(eg:
different system configurations)different system configurations)
 evaluateevaluate complex functionscomplex functions for which closedfor which closed
form formulas or numerical techniques notform formulas or numerical techniques not
availableavailable
Arshad KhanArshad Khan 66
Simulation: advantages/drawbacks*Simulation: advantages/drawbacks*
 advantages:advantages:
• sometimes cheapersometimes cheaper
• find bugs (in design) in advancefind bugs (in design) in advance
• generality:generality: over analytic/numerical techniquesover analytic/numerical techniques
• detail:detail: can simulate system details at arbitrarycan simulate system details at arbitrary
levellevel
 drawbacks:drawbacks:
• caution: does model reflect realitycaution: does model reflect reality
• large scale systems: lots of resources tolarge scale systems: lots of resources to
simulate (especially accurately simulate)simulate (especially accurately simulate)
• may be slow (computationally expensive – 1may be slow (computationally expensive – 1
min real time could be hours of simulated time)min real time could be hours of simulated time)
• art: determining right level of model complexityart: determining right level of model complexity
• statistical uncertainty in resultsstatistical uncertainty in results
OverviewOverview
 Ns2 is event simulator where the advanceNs2 is event simulator where the advance
of time depends on the timing of eventsof time depends on the timing of events
which are maintained by a scheduler.which are maintained by a scheduler.
 Event – an object in C++ hierarchy.Event – an object in C++ hierarchy.
unique ID, Scheduled time,unique ID, Scheduled time,
pointer to an objectpointer to an object
 Scheduler – maintains ordered dataScheduler – maintains ordered data
structure with the events to be executedstructure with the events to be executed
and fires them one by one, invoking theand fires them one by one, invoking the
handler of the event.handler of the event.
Arshad KhanArshad Khan
Discrete event simulatorDiscrete event simulator
 ns-2 is an discrete event driven simulationns-2 is an discrete event driven simulation
• Physical activities are translated to eventsPhysical activities are translated to events
• Events are queued and processed in the order of theirEvents are queued and processed in the order of their
scheduled occurrencesscheduled occurrences
• Time progresses as the events are processedTime progresses as the events are processed
1 2
Time: 1.5 sec Time: 1.7 sec
Time: 1.8 secTime: 2.0 sec
99
Event Driven SimulationEvent Driven Simulation
TX Pkt Event
@ 1.5sec
Node 1
Module
Node 2
Module
TX Pkt Event
@ 1.5sec
RX Pkt Event
@ 1.7sec
RX Pkt Event
@ 1.7sec
TX Ack Event
@ 1.8sec
TX Ack Event
@ 1.8sec
RX Ack Event
@ 2.0sec
RX Ack Event
@ 2.0sec
Event Queue
Simulation Finished!
1010
Discrete Event ExamplesDiscrete Event Examples
Consider two nodes
on an Ethernet:
A B
simple
queuing
model:
t=1, A enqueues pkt on LAN
t=1.01, LAN dequeues pkt
and triggers B
detailed
CSMA/CD
model:
t=1.0: A sends pkt to NIC
A’s NIC starts carrier sense
t=1.005: A’s NIC concludes cs,
starts tx
t=1.006: B’s NIC begins reciving pkt
t=1.01: B’s NIC concludes pkt
B’s NIC passes pkt to app
1111
ns-2 Environmentns-2 Environment
Simulation
Scenario
Tcl Script
C++
Implementation
1 2
set ns_ [new Simulator]
set node_(0) [$ns_ node]
set node_(1) [$ns_ node]
class MobileNode : public Node
{
friend class PositionHandler;
public:
MobileNode();
•
•
}
1212
LanguagesLanguages
 C++ forC++ for datadata
• Per-packet processing, the core ofPer-packet processing, the core of nsns
• Fast to run, detailed, complete controlFast to run, detailed, complete control
 OTcl forOTcl for controlcontrol
• Simulation descriptionSimulation description
• Periodic or triggered actionsPeriodic or triggered actions
• Manipulating existing C++ objectsManipulating existing C++ objects
• Faster to write and changeFaster to write and change
 (a matter of opinion)(a matter of opinion)
Working with NSWorking with NS
 NSNS
an OTcl interpreter with network librariesan OTcl interpreter with network libraries
InvocationInvocation
 Interactive modeInteractive mode
nsns
% (This is the ns prom)% (This is the ns prom)
 Batch modeBatch mode
ns tclfile.tclns tclfile.tcl
““Hello World” Example (Interactive)Hello World” Example (Interactive)
 nsns
 % puts "Hello World!!!"% puts "Hello World!!!"
 Hello World!!!Hello World!!!
 % puts "Hello NS newbie"% puts "Hello NS newbie"
 Hello NS newbieHello NS newbie
 %exit%exit
““Hello World” Example (Batch)Hello World” Example (Batch)
 Hello.tclHello.tcl
puts "Hello World!!!"puts "Hello World!!!"
puts "Hello NS newbie"puts "Hello NS newbie"
 InvocationInvocation
ns hello.tclns hello.tcl
"Hello World!!!“"Hello World!!!“
"Hello NS newbie""Hello NS newbie"
OTclOTcl
 NS is an interpreter of OtclNS is an interpreter of Otcl
 We communicate with NS by OtclWe communicate with NS by Otcl
 We need to know how to use OTclWe need to know how to use OTcl
Its syntaxIts syntax
Basic commandsBasic commands
OTcl BasicsOTcl Basics
 set: Assign a value to a variableset: Assign a value to a variable
 $x: The value of variable x$x: The value of variable x
 [ … ]: Run command and return result[ … ]: Run command and return result
 [expr …]: Calculate the value of expression[expr …]: Calculate the value of expression
 set x $a: Assign value of a to variable xset x $a: Assign value of a to variable x
 puts … : print outputs … : print out
 proc: Define a procedureproc: Define a procedure
 gets stdin x: Read variable x from stdingets stdin x: Read variable x from stdin
Be careful about spacesBe careful about spaces
OTcl: Example 1OTcl: Example 1
puts "Enter 1th operand"puts "Enter 1th operand"
gets stdin agets stdin a
puts "Enter 2th operand"puts "Enter 2th operand"
gets stdin bgets stdin b
set sum [expr $a + $b]set sum [expr $a + $b]
set diff [expr $a - $b]set diff [expr $a - $b]
puts "$a + $b = $sum"puts "$a + $b = $sum"
puts "$a - $b = $diff"puts "$a - $b = $diff"
1919
Basic TclBasic Tcl
# Variables:# Variables:
setset x 10x 10
setset xx
putsputs “x is $x”“x is $x”
# Functions and expressions:# Functions and expressions:
setset y [pow x 2]y [pow x 2]
setset y [expr x*x]y [expr x*x]
# Control flow:# Control flow:
ifif {$x > 0} {{$x > 0} { returnreturn $x }$x } elseelse {{
returnreturn [expr -$x] }[expr -$x] }
whilewhile { $x > 0 } {{ $x > 0 } {
putsputs $x$x
incrincr x –1x –1
}}
forfor {{setset i 0} {$i<10} {i 0} {$i<10} {incrincr i} {i} {
putsputs “$i == $i”“$i == $i”
}}
# Procedures:# Procedures:
procproc pow {x n} {pow {x n} {
ifif {$n == 1} {{$n == 1} { returnreturn $x }$x }
setset part [part [powpow x [x [exprexpr $n-1]]$n-1]]
returnreturn [[exprexpr $x*$part]$x*$part]
}}
# Files:# Files:
setset file [file [open “open “nstrace.txt” w]nstrace.txt” w]
setset line [line [getsgets $file]$file]
puts –nonewlineputs –nonewline $file “hello!”$file “hello!”
closeclose $file$file
2020
Basic OTclBasic OTcl
Class Person
# constructor:
Person instproc init {age} {
$self instvar age_
set age_ $age
}
# method:
Person instproc greet {} {
$self instvar age_
puts “age $age_: Hello!”
}
# subclass:# subclass:
ClassClass Child -Child -superclasssuperclass
PersonPerson
ChildChild instprocinstproc greet {} {greet {} {
$$selfself instvarinstvar age_age_
putsputs “age $age_ kid:“age $age_ kid:
Wassup!”Wassup!”
}}
setset a [a [newnew Person 45]Person 45]
setset b [b [newnew Child 15]Child 15]
$a greet$a greet
$b greet$b greet
What NS2 Can SimulateWhat NS2 Can Simulate
 •• Wired networkWired network
 Traffic model and applicationsTraffic model and applications
 Transport protocolTransport protocol
 Routing and QueuingRouting and Queuing
 QoSQoS
 LANsLANs
 •• Wireless networkWireless network
 Ad hoc routing and mobile IPAd hoc routing and mobile IP
 Sensor networkSensor network
 Propagation model/Energy modelPropagation model/Energy model
 WLAN (802.11)WLAN (802.11)
 •• SatelliteSatellite
 •• Error modulesError modules
 •• Tracing, visualization, emulation, variousTracing, visualization, emulation, various
NS2 Supported Protocols(Wired)NS2 Supported Protocols(Wired)
•• ApplicationApplication
HTTP, web cachingHTTP, web caching
telnet, FTP, RealAudiotelnet, FTP, RealAudio
CBR, on-off sourceCBR, on-off source
•• TransportTransport
UDP, TCP (almost all variants of TCP), RTPUDP, TCP (almost all variants of TCP), RTP
SRM, PLM, LMS, PGMSRM, PLM, LMS, PGM
•• RoutingRouting
Unicast (DV, LM, etc) and multicast routing (PIM etc)Unicast (DV, LM, etc) and multicast routing (PIM etc)
Hierarchical routingHierarchical routing
Manual routingManual routing
BroadcastingBroadcasting
MPLSMPLS
•• QueuingQueuing
RED, FIFO, FQ, SFQ, DRR, CBQRED, FIFO, FQ, SFQ, DRR, CBQ
Diffserv and IntServDiffserv and IntServ
ECNECN
NS2 Supported Protocols(Wireless)NS2 Supported Protocols(Wireless)
 Ad-hoc network routingAd-hoc network routing
AODV, DSR, TORA, DSDVAODV, DSR, TORA, DSDV
•• Mobile IPMobile IP
•• ARPARP
•• Radio propagation modelRadio propagation model
Friss-space attenuationFriss-space attenuation
Two-ray ground reflection modelTwo-ray ground reflection model
Shadowing modelShadowing model
•• Sensor networkSensor network
Direct diffusionDirect diffusion
SMACSMAC
•• WLANWLAN
Ad-hoc modeAd-hoc mode
Infrastructure modeInfrastructure mode
•• SatelliteSatellite
GeostationaryGeostationary
LEOLEO
• Energy model
InstallationInstallation
This Work is available at explanationThis Work is available at explanation
timetime
©Arshad Khan©Arshad Khan 2525
NS-2 Directory Structure
sim
tk8.0 otcl Tcltcl8.0 ns-2 nam-1
tcl
ex test lib
...
...
tcl code
example
validation test
C++ code
tcl code core
ArchitectureArchitecture
 LanguagesLanguages
 Internal StructureInternal Structure
 Architecture (User view)Architecture (User view)
2727
App1
Agent1
App2
Agent2
Node
From Network to SimulationFrom Network to Simulation
Application,
Agent &
Node
Lin
k
Node
App1
Agent1
App2
Agent2
Node
App1
Agent1
App2
Agent2
Node
App1
Agent1
App2
Agent2
Node
Node Node Node
Link
Link
Link Link
Link
Link
Link
Link
App1
Agent1
App2
Agent2
Node
App1
Agent1
App2
Agent2
Node
puts "$a + $b = $sum"
2828
Class Hierarchy (partial)Class Hierarchy (partial)
TclObject
NsObject
Connector Classifier
Queue Delay Agent Trace
Enq Deq Drop
AddressClassifier
TCP
SACKReno
DropTail REDTable of n slots each pointing to a TclObject
classify() identifies destination slot for packet
AddressClassifier, PortClassifier found within Nodes
Receive packets and transmit to target_
Basis for Agents and Links (~Queue + Delay)
Arshad KhanArshad Khan 2929
What is NS2?What is NS2?
 Network SimulatorNetwork Simulator
 A package of tools that simulatesA package of tools that simulates
behavior of networksbehavior of networks
• Create Network TopologiesCreate Network Topologies
• Log events that happen under any loadLog events that happen under any load
• Analyze events to understand theAnalyze events to understand the
network behaviornetwork behavior
Arshad KhanArshad Khan 3030
Creating TopologiesCreating Topologies
n1
n4
n2
n5
n6
n3
5Mbps,
10ms
2Mbps,
20ms
300Kbps,
100ms
300Kbps,
100ms
500Kbps,
50ms
Arshad KhanArshad Khan 3131
Creating TopologiesCreating Topologies
 NodesNodes
• Set properties like queue length,Set properties like queue length,
locationlocation
• Protocols, routing algorithmsProtocols, routing algorithms
 LinksLinks
• Set types of link – Simplex, duplex,Set types of link – Simplex, duplex,
wireless, satellitewireless, satellite
• Set bandwidth, latency etc.Set bandwidth, latency etc.
 Done through tcl ScriptsDone through tcl Scripts
Arshad KhanArshad Khan 3232
Observing Network BehaviorObserving Network Behavior
 Observe behavior by tracing “events”Observe behavior by tracing “events”
• Eg. packet received, packet drop etc.Eg. packet received, packet drop etc.
time
Src Dst IP
Address, Port
Step2: TracingStep2: Tracing
Basic Simulation StepsBasic Simulation Steps
1.1. Creating Simulation ObjectCreating Simulation Object
2.2. Opening a file for network animatorOpening a file for network animator
3.3. Finish ProcedureFinish Procedure
4.4. Execution Time for SimulationExecution Time for Simulation
Procedure (Calling finish Procedure)Procedure (Calling finish Procedure)
5.5. Start The SimulationStart The Simulation
Basic Simulation StepsBasic Simulation Steps
Creating Simulation ObjectCreating Simulation Object
CommandCommand
*set ns [new Simulator]**set ns [new Simulator]*
1.1. Set ns -Set ns -Declare The New Variable NameDeclare The New Variable Name nsns UsingUsing
TheThe setset Command.Command.
2.2. [new Simulator]-[new Simulator]-is indeed The Instantiation ofis indeed The Instantiation of
The ClassThe Class SimulatorSimulator Using The KeywordUsing The Keyword newnew
3.3. SoSo nsns is Theis The SimulatorSimulator ObjectObject
4.4. Now UsingNow Using nsns Variable We Can Access All TheVariable We Can Access All The
Methods of ClassMethods of Class SimulatorSimulator
Basic Simulation StepsBasic Simulation Steps
Opening a File for Network AnimatorOpening a File for Network Animator
or (Opening a NAM Trace File)or (Opening a NAM Trace File)
CommandCommand
** set tracefile1 [open out.nam w]set tracefile1 [open out.nam w]
$ns namtrace-all $tracefile1 *$ns namtrace-all $tracefile1 *
1.1. Open a Trace fileOpen a Trace file out.namout.nam for writng and give itfor writng and give it
to file handlerto file handler tracefile1tracefile1..
2.2. We Are Telling Simulator ObjectWe Are Telling Simulator Object nsns To We HaveTo We Have
Created a file To Write all The Data Related toCreated a file To Write all The Data Related to
Network animator on That FileNetwork animator on That File
3.3. With in a TCL Script file is not called by itsWith in a TCL Script file is not called by its
name(name(out.namout.nam) but Using Pointer () but Using Pointer ( tracefile1tracefile1 ) .) .
Cont….Cont….
 namtrace-all-namtrace-all-It is aIt is a SimulatorSimulator
method which takes the parametermethod which takes the parameter
as file name (as file name (tracefile1tracefile1)where trace)where trace
will go.will go.
Basic Simulation StepsBasic Simulation Steps
Finish ProcedureFinish Procedure
CODECODE
proc finish {} {proc finish {} {
global ns tracefile1global ns tracefile1
$ns flush-trace$ns flush-trace
close $tracefile1close $tracefile1
exec nam out.nam &exec nam out.nam &
exit 0exit 0
}}
CONT…CONT…
 proc finish {}-proc finish {}- The wordThe word procproc declares adeclares a
procedure nameprocedure name finishfinish without anywithout any
argumentsarguments
 global ns tracefile1-global ns tracefile1- The word global isThe word global is
used to tell we are using the variableused to tell we are using the variable
which has declared outside the procedurewhich has declared outside the procedure
((finishfinish) i.e.,) i.e.,ns, tracefile1ns, tracefile1
 $ns flush-trace-$ns flush-trace- flush-traceflush-trace is ais a SimulatorSimulator
method which is used to dump the tracesmethod which is used to dump the traces
on the respective files.on the respective files.
Cont..Cont..
 close $tracefile1-close $tracefile1- which close thewhich close the
tracefile1tracefile1
 exec nam out.nam &-exec nam out.nam &- exeexe exicuteexicute
thethe namnam for visualationfor visualation
 exit 0-exit 0- normal termination ofnormal termination of
procedureprocedure
Basic Simulation StepsBasic Simulation Steps
Execution Time for Simulation ProcedureExecution Time for Simulation Procedure
(Calling finish Procedure)(Calling finish Procedure)
CommandCommand
*$ns at 5.0 "finish“**$ns at 5.0 "finish“*
 We are telling the simulator object (We are telling the simulator object (nsns) to) to
execute theexecute the finishfinish procedure after 5procedure after 5
second ofsecond of simulationsimulation timetime
Basic Simulation StepsBasic Simulation Steps
Start the simulationStart the simulation
CommandCommand
*$ns run**$ns run*
Which is start the simulationWhich is start the simulation
Simplified SceniroSimplified Sceniro
Creating Nodes & LinksCreating Nodes & Links
1.1. Creating NodesCreating Nodes
2.2. Creating LinksCreating Links
Creating NodesCreating Nodes
CommandCommand
*set n0 [$ns node]*set n0 [$ns node]
set n1 [$ns node]*set n1 [$ns node]*
 A new node object is created withA new node object is created with
the commandthe command '$ns node''$ns node'..
 The above code creates two nodesThe above code creates two nodes
and assigns them to the handlesand assigns them to the handles 'n0''n0'
andand 'n1''n1'..
4646
Ns Node
n0 n1
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
0
1
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
1
0
set n0 [$ns node]
set n1 [$ns node]
Creating LinksCreating Links
CommandCommand
*$ns duplex-link $n0 $n1 1Mb 10ms*$ns duplex-link $n0 $n1 1Mb 10ms
Drop Tail*Drop Tail*
 Code tells the simulator object toCode tells the simulator object to
connect the nodesconnect the nodes n0n0 andand n1n1 with awith a
duplex linkduplex link with thewith the bandwidthbandwidth
1Megabit1Megabit, a, a delay of 10msdelay of 10ms and aand a
Drop Tail queue.Drop Tail queue.
4848
Network Topology - Link
n0 n1
enqT_ queue_ deqT_
drophead_ drpT_
link_ ttl_
n1
entry_head_
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
4949
Routing
n0 n1
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
0
1
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
1
0
Link n0-
n1
Link n1-
n0
Creating AgentsCreating Agents
In ns, data is always being sent fromIn ns, data is always being sent from
one 'agent' to anotherone 'agent' to another
1.1. UDPUDP
2.2. CBRCBR
3.3. TCPTCP
4.4. NULLNULL
5.5. Connecting AgentsConnecting Agents
6.6. Schedule The CBRSchedule The CBR
UDP AgentUDP Agent
CommandCommand
*set udp0 [new Agent/UDP]*set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0*$ns attach-agent $n0 $udp0*
 These lines create aThese lines create a UDP agentUDP agent
(udp0)(udp0)
 Attach Agent (Attach Agent (udp0udp0)to the node)to the node n0n0
TCP AgentTCP Agent
CommandCommand
*set tcp0 [new Agent/UDP]*set tcp0 [new Agent/UDP]
$ns attach-agent $n0 $tcp0*$ns attach-agent $n0 $tcp0*
 These lines create aThese lines create a TCP agentTCP agent
(tcp0)(tcp0)
 Attach Agent (Attach Agent (tcp0tcp0)to the node)to the node n0n0
5353
0
1
Transport
n0 n1
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
0 Agent/TCP
agents_
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
1
0
Link n0-
n1
Link n1-
n0
0 Agent/TCPSink
agents_
dst_=1.0 dst_=0.0
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
CBR AgentCBR Agent
CommandCommand
*set cbr0 [new Application/Traffic/CBR]*set cbr0 [new Application/Traffic/CBR]
$cbr0 set packet Size_ 500$cbr0 set packet Size_ 500
$cbr0 set interval_ 0.005*$cbr0 set interval_ 0.005*
 CBRCBR stands for 'constant bit ratestands for 'constant bit rate
 First line create theFirst line create the CBRCBR Agent (Agent (cbr0cbr0))
 The packet Size is being set to 500 bytesThe packet Size is being set to 500 bytes
 packet will be sent every 0.005 secondspacket will be sent every 0.005 seconds
NULL AgentNULL Agent
CommandCommand
*set null0 [new Agent/Null]*set null0 [new Agent/Null]
$ns attach-agent $n1 $null0*$ns attach-agent $n1 $null0*
 These line Creates a Null AgentThese line Creates a Null Agent
(null0)(null0) Which act as a traffic sink.Which act as a traffic sink.
 Attach AgentAttach Agent (null0)(null0) to the nodeto the node n1n1
TCP Sink AgentTCP Sink Agent
CommandCommand
set sink0 [new Agent/TCPSink]set sink0 [new Agent/TCPSink]
$ns attach-agent $n0 $sink0$ns attach-agent $n0 $sink0
 These lines creates aThese lines creates a TCPSinkTCPSink
Agent(sink0)Agent(sink0)
 Attach agentAttach agent (sink0)(sink0) to the nodeto the node n0n0
Connect The AgentsConnect The Agents
Connect The Two Agents UDP & NULLConnect The Two Agents UDP & NULL
CommandCommand
*$ns connect $udp0 $null0**$ns connect $udp0 $null0*
 Which is used to connect the twoWhich is used to connect the two
agentsagents udp0udp0 andand null0null0..
Connect The AgentsConnect The Agents
Connect The Two Agents TCP &TCP SINKConnect The Two Agents TCP &TCP SINK
CommandCommand
*$ns connect $tcp0 $sink0**$ns connect $tcp0 $sink0*
 Which is used to connect the twoWhich is used to connect the two
agentsagents tcp0tcp0 andand sink0sink0..
5959
Application
0
1
n0 n1
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
0 Agent/TCP
agents_
Addr
Classifier
Port
Classifier
classifier_
dmux_
entry_
1
0
Link n0-
n1
Link n1-
n0
0 Agent/TCPSink
agents_
dst_=1.0 dst_=0.0
Application/FTP
set ftp [new Application/FTP]
$tcp attach-agent $ftp
Schedule The CBRSchedule The CBR
To tell CBR to When to start & stopTo tell CBR to When to start & stop
the data sendingthe data sending
CommandCommand
$ns at 0.5 "$cbr0 start“$ns at 0.5 "$cbr0 start“
$ns at 4.5 "$cbr0 stop“$ns at 4.5 "$cbr0 stop“
 AfterAfter 55 simulation secondssimulation seconds cbr0cbr0 startstart
the sending packet and afterthe sending packet and after 4.54.5m itm it
stopstop
6161
Packet Flow
0
1
n0 n1
Addr
Classifier
Port
Classifier
entry_
0 Agent/TCP Addr
Classifier
Port
Classifier
entry_
1
0
Link n0-
n1
Link n1-
n0
0 Agent/TCPSink
dst_=1.0 dst_=0.0
Application/FTP
Wired Example ProgramWired Example Program
(UDP Communication)(UDP Communication)
 Two NodesTwo Nodes
 One LinkOne Link
 UDP CommunicationUDP Communication
 BandwidthBandwidth
 DelayDelay
 Drop tail QueueDrop tail Queue
Arshad KhanArshad Khan 6363
A simple Example – Creating the topologyA simple Example – Creating the topology
n1 n2
Bandwidth:1Mbps
Latency: 10ms
Arshad KhanArshad Khan 6464
Adding trafficAdding traffic
n1 n2
1Mbps,10ms
udp
null
cbr
Packet Size: 500
bytes
rate: 800Kbps
cbr traffic
0.0
0.5
5.0
4.5 time
node
agent
source
link
All at One GlanceAll at One Glance
1.1. Create Simulator ObjectCreate Simulator Object
2.2. Open a Network Animator FileOpen a Network Animator File
3.3. Finish ProcedureFinish Procedure
4.4. Create a NodesCreate a Nodes
5.5. Create a LinkCreate a Link
6.6. Create & Attach UDP agent at One NodeCreate & Attach UDP agent at One Node
7.7. Create & Attach CBR agent to UDP AgentCreate & Attach CBR agent to UDP Agent
8.8. Attach NULL agent To another NodeAttach NULL agent To another Node
9.9. Connect The Agents ( UDP & NULL)Connect The Agents ( UDP & NULL)
10.10. Schedule The Start and Stop Time To CBR AgentSchedule The Start and Stop Time To CBR Agent
11.11. Call the Finish procedure (Schedule the Simulation)Call the Finish procedure (Schedule the Simulation)
12.12. Run The SimulationRun The Simulation
Wired Example ProgramWired Example Program
(TCP Communication)(TCP Communication)
 Two nodesTwo nodes
 One linkOne link
 TCP CommunicationTCP Communication
 BandwidthBandwidth
 DelayDelay
 Drop tail QueueDrop tail Queue
All at One GlanceAll at One Glance
1.1. Create Simulator ObjectCreate Simulator Object
2.2. Open a Network Animator FileOpen a Network Animator File
3.3. Finish ProcedureFinish Procedure
4.4. Create a NodesCreate a Nodes
5.5. Create a LinkCreate a Link
6.6. Create & Attach TCP agent at One NodeCreate & Attach TCP agent at One Node
7.7. Create & Attach CBR agent to TCP AgentCreate & Attach CBR agent to TCP Agent
8.8. Attach TCPSINK agent To another NodeAttach TCPSINK agent To another Node
9.9. Connect The Agents ( TCP & TCPSINK)Connect The Agents ( TCP & TCPSINK)
10.10. Schedule The Start and Stop Time To CBR AgentSchedule The Start and Stop Time To CBR Agent
11.11. Call the Finish procedure (Schedule the Simulation)Call the Finish procedure (Schedule the Simulation)
12.12. Run The SimulationRun The Simulation
Wired Example ProgramWired Example Program
(TCP Communication)(TCP Communication)
 Two nodesTwo nodes
 One linkOne link
 TCP CommunicationTCP Communication
 BandwidthBandwidth
 DelayDelay
 Drop tail QueueDrop tail Queue
Example : TCPExample : TCP
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
n0 n1
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.2 "$ftp start"
$ns at 1.2 ”exit"
$ns run
$ns duplex-link $n0 $n1 1.5Mb
10ms DropTail
set tcp [new Agent/TCP]
set tcpsink [new
Agent/TCPSink]
$ns attach-agent $n0 $tcp
$ns attach-agent $n1 $tcpsink
$ns connect $tcp $tcpsink
Script to startScript to start namnam
set nf [open out.nam w]set nf [open out.nam w]
$ns namtrace-all $nf$ns namtrace-all $nf
proc finish {} {proc finish {} {
global ns nfglobal ns nf
$ns flush-trace$ns flush-trace
close $nfclose $nf
exec nam out.nam &exec nam out.nam &
exit 0exit 0
}}
# your code goes in here# your code goes in here
$ns at 12.0 "finish" # 12.0 is the simulation time in secs$ns at 12.0 "finish" # 12.0 is the simulation time in secs
7171
Script CodeScript Code
# Create a topology# Create a topology
Set ns [new Simulator]Set ns [new Simulator]
set n0 [$ns node]set n0 [$ns node]
set n1 [$ns node]set n1 [$ns node]
$ns duplex-link $n0 $n1 1Mb 10ms DropTail$ns duplex-link $n0 $n1 1Mb 10ms DropTail
# Add Transport agents# Add Transport agents
set tcp [new Agent/TCP]set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp$ns attach-agent $n0 $tcp
set tcpsink [new Agent/TCPSink]set tcpsink [new Agent/TCPSink]
$ns attach-agent $n1 $tcpsink$ns attach-agent $n1 $tcpsink
$tcp connect $tcpsink$tcp connect $tcpsink
# Add application# Add application
set ftp [new Application/FTP]set ftp [new Application/FTP]
$ftp attach-agent $tcp$ftp attach-agent $tcp
# Create a schedule
$ns at 0.5 "$ftp start"
$ns at 4.5 "$ftp stop"
#Run the simulation
$ns run
n0 n1
1Mb
10ms
FTP
TCP
FTP
TCP
7272
Discrete Event-Driven
Simulator
time_, uid_, next_, handler_
head_ ->
handler_ -> handle()
time_, uid_, next_, handler_insert
$ns at 0.5 “$ftp start”
$ns at 4.5 “$ftp stop”
$ns run
Packets Dropping from linkPackets Dropping from link
Cont…Cont…
 Create 4 nodes with 3 links.Create 4 nodes with 3 links.
 Bandwidth 1mbps & Delay 10ms.Bandwidth 1mbps & Delay 10ms.
 UDP Agent at node n0,n1.UDP Agent at node n0,n1.
 NULL Agent at node n3.NULL Agent at node n3.
Thank you for your patientThank you for your patient

Mais conteúdo relacionado

Mais procurados

NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
Teerawat Issariyakul
 
Device-specific Clang Tooling for Embedded Systems
Device-specific Clang Tooling for Embedded SystemsDevice-specific Clang Tooling for Embedded Systems
Device-specific Clang Tooling for Embedded Systems
emBO_Conference
 
Cracking Pseudorandom Sequences Generators in Java Applications
Cracking Pseudorandom Sequences Generators in Java ApplicationsCracking Pseudorandom Sequences Generators in Java Applications
Cracking Pseudorandom Sequences Generators in Java Applications
Positive Hack Days
 

Mais procurados (20)

Ns network simulator
Ns network simulatorNs network simulator
Ns network simulator
 
SANER 2019 Most Influential Paper Talk
SANER 2019 Most Influential Paper TalkSANER 2019 Most Influential Paper Talk
SANER 2019 Most Influential Paper Talk
 
[DSC 2016] 系列活動:李泳泉 / 星火燎原 - Spark 機器學習初探
[DSC 2016] 系列活動:李泳泉 / 星火燎原 - Spark 機器學習初探[DSC 2016] 系列活動:李泳泉 / 星火燎原 - Spark 機器學習初探
[DSC 2016] 系列活動:李泳泉 / 星火燎原 - Spark 機器學習初探
 
TensorFlow Study Part I
TensorFlow Study Part ITensorFlow Study Part I
TensorFlow Study Part I
 
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
Apache Spark - Key Value RDD - Transformations | Big Data Hadoop Spark Tutori...
 
Ns 2 Network Simulator An Introduction
Ns 2 Network Simulator An IntroductionNs 2 Network Simulator An Introduction
Ns 2 Network Simulator An Introduction
 
core.logic introduction
core.logic introductioncore.logic introduction
core.logic introduction
 
同態加密
同態加密同態加密
同態加密
 
Tracing and awk in ns2
Tracing and awk in ns2Tracing and awk in ns2
Tracing and awk in ns2
 
Network simulator 2
Network simulator 2Network simulator 2
Network simulator 2
 
Apache Spark - Basics of RDD & RDD Operations | Big Data Hadoop Spark Tutoria...
Apache Spark - Basics of RDD & RDD Operations | Big Data Hadoop Spark Tutoria...Apache Spark - Basics of RDD & RDD Operations | Big Data Hadoop Spark Tutoria...
Apache Spark - Basics of RDD & RDD Operations | Big Data Hadoop Spark Tutoria...
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
 
[系列活動] 手把手的深度學習實務
[系列活動] 手把手的深度學習實務[系列活動] 手把手的深度學習實務
[系列活動] 手把手的深度學習實務
 
A22 Introduction to DTrace by Kyle Hailey
A22 Introduction to DTrace by Kyle HaileyA22 Introduction to DTrace by Kyle Hailey
A22 Introduction to DTrace by Kyle Hailey
 
From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOS
 
Device-specific Clang Tooling for Embedded Systems
Device-specific Clang Tooling for Embedded SystemsDevice-specific Clang Tooling for Embedded Systems
Device-specific Clang Tooling for Embedded Systems
 
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
NLP on a Billion Documents: Scalable Machine Learning with Apache SparkNLP on a Billion Documents: Scalable Machine Learning with Apache Spark
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
 
Cracking Pseudorandom Sequences Generators in Java Applications
Cracking Pseudorandom Sequences Generators in Java ApplicationsCracking Pseudorandom Sequences Generators in Java Applications
Cracking Pseudorandom Sequences Generators in Java Applications
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 

Destaque (8)

IEEE 2013 NS2 Project titles
IEEE 2013 NS2 Project titles IEEE 2013 NS2 Project titles
IEEE 2013 NS2 Project titles
 
Ieee 2015 ns2 project list
Ieee 2015 ns2 project listIeee 2015 ns2 project list
Ieee 2015 ns2 project list
 
Ns2
Ns2Ns2
Ns2
 
The Project Management Process - Week 8 Conflict Management
The Project Management Process - Week 8   Conflict ManagementThe Project Management Process - Week 8   Conflict Management
The Project Management Process - Week 8 Conflict Management
 
Final Year Project Presentation
Final Year Project PresentationFinal Year Project Presentation
Final Year Project Presentation
 
Final ppt of project
Final ppt of projectFinal ppt of project
Final ppt of project
 
Final Year Project Presentation
Final Year Project PresentationFinal Year Project Presentation
Final Year Project Presentation
 
Presentation on project report
Presentation on project reportPresentation on project report
Presentation on project report
 

Semelhante a Ns2 by khan

Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
g3_nittala
 
NS2-tutorial.ppt
NS2-tutorial.pptNS2-tutorial.ppt
NS2-tutorial.ppt
Wajath
 

Semelhante a Ns2 by khan (20)

Ns2: OTCL - PArt II
Ns2: OTCL - PArt IINs2: OTCL - PArt II
Ns2: OTCL - PArt II
 
Network Simulator Tutorial
Network Simulator TutorialNetwork Simulator Tutorial
Network Simulator Tutorial
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Ns2
Ns2Ns2
Ns2
 
NS2-tutorial.ppt
NS2-tutorial.pptNS2-tutorial.ppt
NS2-tutorial.ppt
 
Tut hemant ns2
Tut hemant ns2Tut hemant ns2
Tut hemant ns2
 
Ns2 ns3 training in mohali
Ns2 ns3 training in mohaliNs2 ns3 training in mohali
Ns2 ns3 training in mohali
 
Ns tutorial
Ns tutorialNs tutorial
Ns tutorial
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Introduction to NS2 - Cont..
Introduction to NS2 - Cont..Introduction to NS2 - Cont..
Introduction to NS2 - Cont..
 
[Update] PyTorch Tutorial for NTU Machine Learing Course 2017
[Update] PyTorch Tutorial for NTU Machine Learing Course 2017[Update] PyTorch Tutorial for NTU Machine Learing Course 2017
[Update] PyTorch Tutorial for NTU Machine Learing Course 2017
 
NS2 Overview - Network Simulator Tutorial
NS2 Overview - Network Simulator TutorialNS2 Overview - Network Simulator Tutorial
NS2 Overview - Network Simulator Tutorial
 
Deep Learning in Your Browser
Deep Learning in Your BrowserDeep Learning in Your Browser
Deep Learning in Your Browser
 
ns2-training material
ns2-training materialns2-training material
ns2-training material
 
Ns2
Ns2Ns2
Ns2
 
TensorFlow in Your Browser
TensorFlow in Your BrowserTensorFlow in Your Browser
TensorFlow in Your Browser
 
Intro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.jsIntro to Deep Learning, TensorFlow, and tensorflow.js
Intro to Deep Learning, TensorFlow, and tensorflow.js
 
NvFX GTC 2013
NvFX GTC 2013NvFX GTC 2013
NvFX GTC 2013
 
Introduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlowIntroduction to Deep Learning and TensorFlow
Introduction to Deep Learning and TensorFlow
 
Mining Geo-referenced Data: Location-based Services and the Sharing Economy
Mining Geo-referenced Data: Location-based Services and the Sharing EconomyMining Geo-referenced Data: Location-based Services and the Sharing Economy
Mining Geo-referenced Data: Location-based Services and the Sharing Economy
 

Último

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Ns2 by khan

  • 1. Introduction To NS-2Introduction To NS-2 By Arshad Ahmad Khan Mohammad Part Time Research Scholar (CNIS) KL University, Andhra Pradesh India, .
  • 2. Outline Of PresentationOutline Of Presentation  IntroductionIntroduction  InstallationInstallation  ArchitectureArchitecture  Tcl & Otcl ExamplesTcl & Otcl Examples  Simulation StepsSimulation Steps  Examples (Wired)Examples (Wired)  Examples (Wireless)Examples (Wireless)
  • 3. IntroductionIntroduction  About NS2About NS2  Advantages of NS2Advantages of NS2  NS2 Supported Protocols(Wired &NS2 Supported Protocols(Wired & Wireless)Wireless)
  • 4. Arshad KhanArshad Khan 44 Network Simulation *Network Simulation * Motivation:Motivation:  Learn fundamentalsLearn fundamentals of evaluatingof evaluating networknetwork performance viaperformance via simulationsimulation • Overview:Overview:  fundamentals offundamentals of discrete eventdiscrete event simulationsimulation  ns-2 simulationns-2 simulation
  • 5. Arshad KhanArshad Khan 55 Why Simulation? *Why Simulation? *  real-system notreal-system not available, is complex/costly oravailable, is complex/costly or dangerousdangerous ((eg: space simulations, flighteg: space simulations, flight simulations)simulations)  quickly evaluate designquickly evaluate design alternativesalternatives (eg:(eg: different system configurations)different system configurations)  evaluateevaluate complex functionscomplex functions for which closedfor which closed form formulas or numerical techniques notform formulas or numerical techniques not availableavailable
  • 6. Arshad KhanArshad Khan 66 Simulation: advantages/drawbacks*Simulation: advantages/drawbacks*  advantages:advantages: • sometimes cheapersometimes cheaper • find bugs (in design) in advancefind bugs (in design) in advance • generality:generality: over analytic/numerical techniquesover analytic/numerical techniques • detail:detail: can simulate system details at arbitrarycan simulate system details at arbitrary levellevel  drawbacks:drawbacks: • caution: does model reflect realitycaution: does model reflect reality • large scale systems: lots of resources tolarge scale systems: lots of resources to simulate (especially accurately simulate)simulate (especially accurately simulate) • may be slow (computationally expensive – 1may be slow (computationally expensive – 1 min real time could be hours of simulated time)min real time could be hours of simulated time) • art: determining right level of model complexityart: determining right level of model complexity • statistical uncertainty in resultsstatistical uncertainty in results
  • 7. OverviewOverview  Ns2 is event simulator where the advanceNs2 is event simulator where the advance of time depends on the timing of eventsof time depends on the timing of events which are maintained by a scheduler.which are maintained by a scheduler.  Event – an object in C++ hierarchy.Event – an object in C++ hierarchy. unique ID, Scheduled time,unique ID, Scheduled time, pointer to an objectpointer to an object  Scheduler – maintains ordered dataScheduler – maintains ordered data structure with the events to be executedstructure with the events to be executed and fires them one by one, invoking theand fires them one by one, invoking the handler of the event.handler of the event.
  • 8. Arshad KhanArshad Khan Discrete event simulatorDiscrete event simulator  ns-2 is an discrete event driven simulationns-2 is an discrete event driven simulation • Physical activities are translated to eventsPhysical activities are translated to events • Events are queued and processed in the order of theirEvents are queued and processed in the order of their scheduled occurrencesscheduled occurrences • Time progresses as the events are processedTime progresses as the events are processed 1 2 Time: 1.5 sec Time: 1.7 sec Time: 1.8 secTime: 2.0 sec
  • 9. 99 Event Driven SimulationEvent Driven Simulation TX Pkt Event @ 1.5sec Node 1 Module Node 2 Module TX Pkt Event @ 1.5sec RX Pkt Event @ 1.7sec RX Pkt Event @ 1.7sec TX Ack Event @ 1.8sec TX Ack Event @ 1.8sec RX Ack Event @ 2.0sec RX Ack Event @ 2.0sec Event Queue Simulation Finished!
  • 10. 1010 Discrete Event ExamplesDiscrete Event Examples Consider two nodes on an Ethernet: A B simple queuing model: t=1, A enqueues pkt on LAN t=1.01, LAN dequeues pkt and triggers B detailed CSMA/CD model: t=1.0: A sends pkt to NIC A’s NIC starts carrier sense t=1.005: A’s NIC concludes cs, starts tx t=1.006: B’s NIC begins reciving pkt t=1.01: B’s NIC concludes pkt B’s NIC passes pkt to app
  • 11. 1111 ns-2 Environmentns-2 Environment Simulation Scenario Tcl Script C++ Implementation 1 2 set ns_ [new Simulator] set node_(0) [$ns_ node] set node_(1) [$ns_ node] class MobileNode : public Node { friend class PositionHandler; public: MobileNode(); • • }
  • 12. 1212 LanguagesLanguages  C++ forC++ for datadata • Per-packet processing, the core ofPer-packet processing, the core of nsns • Fast to run, detailed, complete controlFast to run, detailed, complete control  OTcl forOTcl for controlcontrol • Simulation descriptionSimulation description • Periodic or triggered actionsPeriodic or triggered actions • Manipulating existing C++ objectsManipulating existing C++ objects • Faster to write and changeFaster to write and change  (a matter of opinion)(a matter of opinion)
  • 13. Working with NSWorking with NS  NSNS an OTcl interpreter with network librariesan OTcl interpreter with network libraries InvocationInvocation  Interactive modeInteractive mode nsns % (This is the ns prom)% (This is the ns prom)  Batch modeBatch mode ns tclfile.tclns tclfile.tcl
  • 14. ““Hello World” Example (Interactive)Hello World” Example (Interactive)  nsns  % puts "Hello World!!!"% puts "Hello World!!!"  Hello World!!!Hello World!!!  % puts "Hello NS newbie"% puts "Hello NS newbie"  Hello NS newbieHello NS newbie  %exit%exit
  • 15. ““Hello World” Example (Batch)Hello World” Example (Batch)  Hello.tclHello.tcl puts "Hello World!!!"puts "Hello World!!!" puts "Hello NS newbie"puts "Hello NS newbie"  InvocationInvocation ns hello.tclns hello.tcl "Hello World!!!“"Hello World!!!“ "Hello NS newbie""Hello NS newbie"
  • 16. OTclOTcl  NS is an interpreter of OtclNS is an interpreter of Otcl  We communicate with NS by OtclWe communicate with NS by Otcl  We need to know how to use OTclWe need to know how to use OTcl Its syntaxIts syntax Basic commandsBasic commands
  • 17. OTcl BasicsOTcl Basics  set: Assign a value to a variableset: Assign a value to a variable  $x: The value of variable x$x: The value of variable x  [ … ]: Run command and return result[ … ]: Run command and return result  [expr …]: Calculate the value of expression[expr …]: Calculate the value of expression  set x $a: Assign value of a to variable xset x $a: Assign value of a to variable x  puts … : print outputs … : print out  proc: Define a procedureproc: Define a procedure  gets stdin x: Read variable x from stdingets stdin x: Read variable x from stdin Be careful about spacesBe careful about spaces
  • 18. OTcl: Example 1OTcl: Example 1 puts "Enter 1th operand"puts "Enter 1th operand" gets stdin agets stdin a puts "Enter 2th operand"puts "Enter 2th operand" gets stdin bgets stdin b set sum [expr $a + $b]set sum [expr $a + $b] set diff [expr $a - $b]set diff [expr $a - $b] puts "$a + $b = $sum"puts "$a + $b = $sum" puts "$a - $b = $diff"puts "$a - $b = $diff"
  • 19. 1919 Basic TclBasic Tcl # Variables:# Variables: setset x 10x 10 setset xx putsputs “x is $x”“x is $x” # Functions and expressions:# Functions and expressions: setset y [pow x 2]y [pow x 2] setset y [expr x*x]y [expr x*x] # Control flow:# Control flow: ifif {$x > 0} {{$x > 0} { returnreturn $x }$x } elseelse {{ returnreturn [expr -$x] }[expr -$x] } whilewhile { $x > 0 } {{ $x > 0 } { putsputs $x$x incrincr x –1x –1 }} forfor {{setset i 0} {$i<10} {i 0} {$i<10} {incrincr i} {i} { putsputs “$i == $i”“$i == $i” }} # Procedures:# Procedures: procproc pow {x n} {pow {x n} { ifif {$n == 1} {{$n == 1} { returnreturn $x }$x } setset part [part [powpow x [x [exprexpr $n-1]]$n-1]] returnreturn [[exprexpr $x*$part]$x*$part] }} # Files:# Files: setset file [file [open “open “nstrace.txt” w]nstrace.txt” w] setset line [line [getsgets $file]$file] puts –nonewlineputs –nonewline $file “hello!”$file “hello!” closeclose $file$file
  • 20. 2020 Basic OTclBasic OTcl Class Person # constructor: Person instproc init {age} { $self instvar age_ set age_ $age } # method: Person instproc greet {} { $self instvar age_ puts “age $age_: Hello!” } # subclass:# subclass: ClassClass Child -Child -superclasssuperclass PersonPerson ChildChild instprocinstproc greet {} {greet {} { $$selfself instvarinstvar age_age_ putsputs “age $age_ kid:“age $age_ kid: Wassup!”Wassup!” }} setset a [a [newnew Person 45]Person 45] setset b [b [newnew Child 15]Child 15] $a greet$a greet $b greet$b greet
  • 21. What NS2 Can SimulateWhat NS2 Can Simulate  •• Wired networkWired network  Traffic model and applicationsTraffic model and applications  Transport protocolTransport protocol  Routing and QueuingRouting and Queuing  QoSQoS  LANsLANs  •• Wireless networkWireless network  Ad hoc routing and mobile IPAd hoc routing and mobile IP  Sensor networkSensor network  Propagation model/Energy modelPropagation model/Energy model  WLAN (802.11)WLAN (802.11)  •• SatelliteSatellite  •• Error modulesError modules  •• Tracing, visualization, emulation, variousTracing, visualization, emulation, various
  • 22. NS2 Supported Protocols(Wired)NS2 Supported Protocols(Wired) •• ApplicationApplication HTTP, web cachingHTTP, web caching telnet, FTP, RealAudiotelnet, FTP, RealAudio CBR, on-off sourceCBR, on-off source •• TransportTransport UDP, TCP (almost all variants of TCP), RTPUDP, TCP (almost all variants of TCP), RTP SRM, PLM, LMS, PGMSRM, PLM, LMS, PGM •• RoutingRouting Unicast (DV, LM, etc) and multicast routing (PIM etc)Unicast (DV, LM, etc) and multicast routing (PIM etc) Hierarchical routingHierarchical routing Manual routingManual routing BroadcastingBroadcasting MPLSMPLS •• QueuingQueuing RED, FIFO, FQ, SFQ, DRR, CBQRED, FIFO, FQ, SFQ, DRR, CBQ Diffserv and IntServDiffserv and IntServ ECNECN
  • 23. NS2 Supported Protocols(Wireless)NS2 Supported Protocols(Wireless)  Ad-hoc network routingAd-hoc network routing AODV, DSR, TORA, DSDVAODV, DSR, TORA, DSDV •• Mobile IPMobile IP •• ARPARP •• Radio propagation modelRadio propagation model Friss-space attenuationFriss-space attenuation Two-ray ground reflection modelTwo-ray ground reflection model Shadowing modelShadowing model •• Sensor networkSensor network Direct diffusionDirect diffusion SMACSMAC •• WLANWLAN Ad-hoc modeAd-hoc mode Infrastructure modeInfrastructure mode •• SatelliteSatellite GeostationaryGeostationary LEOLEO • Energy model
  • 24. InstallationInstallation This Work is available at explanationThis Work is available at explanation timetime
  • 25. ©Arshad Khan©Arshad Khan 2525 NS-2 Directory Structure sim tk8.0 otcl Tcltcl8.0 ns-2 nam-1 tcl ex test lib ... ... tcl code example validation test C++ code tcl code core
  • 26. ArchitectureArchitecture  LanguagesLanguages  Internal StructureInternal Structure  Architecture (User view)Architecture (User view)
  • 27. 2727 App1 Agent1 App2 Agent2 Node From Network to SimulationFrom Network to Simulation Application, Agent & Node Lin k Node App1 Agent1 App2 Agent2 Node App1 Agent1 App2 Agent2 Node App1 Agent1 App2 Agent2 Node Node Node Node Link Link Link Link Link Link Link Link App1 Agent1 App2 Agent2 Node App1 Agent1 App2 Agent2 Node puts "$a + $b = $sum"
  • 28. 2828 Class Hierarchy (partial)Class Hierarchy (partial) TclObject NsObject Connector Classifier Queue Delay Agent Trace Enq Deq Drop AddressClassifier TCP SACKReno DropTail REDTable of n slots each pointing to a TclObject classify() identifies destination slot for packet AddressClassifier, PortClassifier found within Nodes Receive packets and transmit to target_ Basis for Agents and Links (~Queue + Delay)
  • 29. Arshad KhanArshad Khan 2929 What is NS2?What is NS2?  Network SimulatorNetwork Simulator  A package of tools that simulatesA package of tools that simulates behavior of networksbehavior of networks • Create Network TopologiesCreate Network Topologies • Log events that happen under any loadLog events that happen under any load • Analyze events to understand theAnalyze events to understand the network behaviornetwork behavior
  • 30. Arshad KhanArshad Khan 3030 Creating TopologiesCreating Topologies n1 n4 n2 n5 n6 n3 5Mbps, 10ms 2Mbps, 20ms 300Kbps, 100ms 300Kbps, 100ms 500Kbps, 50ms
  • 31. Arshad KhanArshad Khan 3131 Creating TopologiesCreating Topologies  NodesNodes • Set properties like queue length,Set properties like queue length, locationlocation • Protocols, routing algorithmsProtocols, routing algorithms  LinksLinks • Set types of link – Simplex, duplex,Set types of link – Simplex, duplex, wireless, satellitewireless, satellite • Set bandwidth, latency etc.Set bandwidth, latency etc.  Done through tcl ScriptsDone through tcl Scripts
  • 32. Arshad KhanArshad Khan 3232 Observing Network BehaviorObserving Network Behavior  Observe behavior by tracing “events”Observe behavior by tracing “events” • Eg. packet received, packet drop etc.Eg. packet received, packet drop etc. time Src Dst IP Address, Port
  • 34. Basic Simulation StepsBasic Simulation Steps 1.1. Creating Simulation ObjectCreating Simulation Object 2.2. Opening a file for network animatorOpening a file for network animator 3.3. Finish ProcedureFinish Procedure 4.4. Execution Time for SimulationExecution Time for Simulation Procedure (Calling finish Procedure)Procedure (Calling finish Procedure) 5.5. Start The SimulationStart The Simulation
  • 35. Basic Simulation StepsBasic Simulation Steps Creating Simulation ObjectCreating Simulation Object CommandCommand *set ns [new Simulator]**set ns [new Simulator]* 1.1. Set ns -Set ns -Declare The New Variable NameDeclare The New Variable Name nsns UsingUsing TheThe setset Command.Command. 2.2. [new Simulator]-[new Simulator]-is indeed The Instantiation ofis indeed The Instantiation of The ClassThe Class SimulatorSimulator Using The KeywordUsing The Keyword newnew 3.3. SoSo nsns is Theis The SimulatorSimulator ObjectObject 4.4. Now UsingNow Using nsns Variable We Can Access All TheVariable We Can Access All The Methods of ClassMethods of Class SimulatorSimulator
  • 36. Basic Simulation StepsBasic Simulation Steps Opening a File for Network AnimatorOpening a File for Network Animator or (Opening a NAM Trace File)or (Opening a NAM Trace File) CommandCommand ** set tracefile1 [open out.nam w]set tracefile1 [open out.nam w] $ns namtrace-all $tracefile1 *$ns namtrace-all $tracefile1 * 1.1. Open a Trace fileOpen a Trace file out.namout.nam for writng and give itfor writng and give it to file handlerto file handler tracefile1tracefile1.. 2.2. We Are Telling Simulator ObjectWe Are Telling Simulator Object nsns To We HaveTo We Have Created a file To Write all The Data Related toCreated a file To Write all The Data Related to Network animator on That FileNetwork animator on That File 3.3. With in a TCL Script file is not called by itsWith in a TCL Script file is not called by its name(name(out.namout.nam) but Using Pointer () but Using Pointer ( tracefile1tracefile1 ) .) .
  • 37. Cont….Cont….  namtrace-all-namtrace-all-It is aIt is a SimulatorSimulator method which takes the parametermethod which takes the parameter as file name (as file name (tracefile1tracefile1)where trace)where trace will go.will go.
  • 38. Basic Simulation StepsBasic Simulation Steps Finish ProcedureFinish Procedure CODECODE proc finish {} {proc finish {} { global ns tracefile1global ns tracefile1 $ns flush-trace$ns flush-trace close $tracefile1close $tracefile1 exec nam out.nam &exec nam out.nam & exit 0exit 0 }}
  • 39. CONT…CONT…  proc finish {}-proc finish {}- The wordThe word procproc declares adeclares a procedure nameprocedure name finishfinish without anywithout any argumentsarguments  global ns tracefile1-global ns tracefile1- The word global isThe word global is used to tell we are using the variableused to tell we are using the variable which has declared outside the procedurewhich has declared outside the procedure ((finishfinish) i.e.,) i.e.,ns, tracefile1ns, tracefile1  $ns flush-trace-$ns flush-trace- flush-traceflush-trace is ais a SimulatorSimulator method which is used to dump the tracesmethod which is used to dump the traces on the respective files.on the respective files.
  • 40. Cont..Cont..  close $tracefile1-close $tracefile1- which close thewhich close the tracefile1tracefile1  exec nam out.nam &-exec nam out.nam &- exeexe exicuteexicute thethe namnam for visualationfor visualation  exit 0-exit 0- normal termination ofnormal termination of procedureprocedure
  • 41. Basic Simulation StepsBasic Simulation Steps Execution Time for Simulation ProcedureExecution Time for Simulation Procedure (Calling finish Procedure)(Calling finish Procedure) CommandCommand *$ns at 5.0 "finish“**$ns at 5.0 "finish“*  We are telling the simulator object (We are telling the simulator object (nsns) to) to execute theexecute the finishfinish procedure after 5procedure after 5 second ofsecond of simulationsimulation timetime
  • 42. Basic Simulation StepsBasic Simulation Steps Start the simulationStart the simulation CommandCommand *$ns run**$ns run* Which is start the simulationWhich is start the simulation
  • 44. Creating Nodes & LinksCreating Nodes & Links 1.1. Creating NodesCreating Nodes 2.2. Creating LinksCreating Links
  • 45. Creating NodesCreating Nodes CommandCommand *set n0 [$ns node]*set n0 [$ns node] set n1 [$ns node]*set n1 [$ns node]*  A new node object is created withA new node object is created with the commandthe command '$ns node''$ns node'..  The above code creates two nodesThe above code creates two nodes and assigns them to the handlesand assigns them to the handles 'n0''n0' andand 'n1''n1'..
  • 47. Creating LinksCreating Links CommandCommand *$ns duplex-link $n0 $n1 1Mb 10ms*$ns duplex-link $n0 $n1 1Mb 10ms Drop Tail*Drop Tail*  Code tells the simulator object toCode tells the simulator object to connect the nodesconnect the nodes n0n0 andand n1n1 with awith a duplex linkduplex link with thewith the bandwidthbandwidth 1Megabit1Megabit, a, a delay of 10msdelay of 10ms and aand a Drop Tail queue.Drop Tail queue.
  • 48. 4848 Network Topology - Link n0 n1 enqT_ queue_ deqT_ drophead_ drpT_ link_ ttl_ n1 entry_head_ $ns duplex-link $n0 $n1 1Mb 10ms DropTail
  • 50. Creating AgentsCreating Agents In ns, data is always being sent fromIn ns, data is always being sent from one 'agent' to anotherone 'agent' to another 1.1. UDPUDP 2.2. CBRCBR 3.3. TCPTCP 4.4. NULLNULL 5.5. Connecting AgentsConnecting Agents 6.6. Schedule The CBRSchedule The CBR
  • 51. UDP AgentUDP Agent CommandCommand *set udp0 [new Agent/UDP]*set udp0 [new Agent/UDP] $ns attach-agent $n0 $udp0*$ns attach-agent $n0 $udp0*  These lines create aThese lines create a UDP agentUDP agent (udp0)(udp0)  Attach Agent (Attach Agent (udp0udp0)to the node)to the node n0n0
  • 52. TCP AgentTCP Agent CommandCommand *set tcp0 [new Agent/UDP]*set tcp0 [new Agent/UDP] $ns attach-agent $n0 $tcp0*$ns attach-agent $n0 $tcp0*  These lines create aThese lines create a TCP agentTCP agent (tcp0)(tcp0)  Attach Agent (Attach Agent (tcp0tcp0)to the node)to the node n0n0
  • 53. 5353 0 1 Transport n0 n1 Addr Classifier Port Classifier classifier_ dmux_ entry_ 0 Agent/TCP agents_ Addr Classifier Port Classifier classifier_ dmux_ entry_ 1 0 Link n0- n1 Link n1- n0 0 Agent/TCPSink agents_ dst_=1.0 dst_=0.0 set tcp [new Agent/TCP] $ns attach-agent $n0 $tcp
  • 54. CBR AgentCBR Agent CommandCommand *set cbr0 [new Application/Traffic/CBR]*set cbr0 [new Application/Traffic/CBR] $cbr0 set packet Size_ 500$cbr0 set packet Size_ 500 $cbr0 set interval_ 0.005*$cbr0 set interval_ 0.005*  CBRCBR stands for 'constant bit ratestands for 'constant bit rate  First line create theFirst line create the CBRCBR Agent (Agent (cbr0cbr0))  The packet Size is being set to 500 bytesThe packet Size is being set to 500 bytes  packet will be sent every 0.005 secondspacket will be sent every 0.005 seconds
  • 55. NULL AgentNULL Agent CommandCommand *set null0 [new Agent/Null]*set null0 [new Agent/Null] $ns attach-agent $n1 $null0*$ns attach-agent $n1 $null0*  These line Creates a Null AgentThese line Creates a Null Agent (null0)(null0) Which act as a traffic sink.Which act as a traffic sink.  Attach AgentAttach Agent (null0)(null0) to the nodeto the node n1n1
  • 56. TCP Sink AgentTCP Sink Agent CommandCommand set sink0 [new Agent/TCPSink]set sink0 [new Agent/TCPSink] $ns attach-agent $n0 $sink0$ns attach-agent $n0 $sink0  These lines creates aThese lines creates a TCPSinkTCPSink Agent(sink0)Agent(sink0)  Attach agentAttach agent (sink0)(sink0) to the nodeto the node n0n0
  • 57. Connect The AgentsConnect The Agents Connect The Two Agents UDP & NULLConnect The Two Agents UDP & NULL CommandCommand *$ns connect $udp0 $null0**$ns connect $udp0 $null0*  Which is used to connect the twoWhich is used to connect the two agentsagents udp0udp0 andand null0null0..
  • 58. Connect The AgentsConnect The Agents Connect The Two Agents TCP &TCP SINKConnect The Two Agents TCP &TCP SINK CommandCommand *$ns connect $tcp0 $sink0**$ns connect $tcp0 $sink0*  Which is used to connect the twoWhich is used to connect the two agentsagents tcp0tcp0 andand sink0sink0..
  • 59. 5959 Application 0 1 n0 n1 Addr Classifier Port Classifier classifier_ dmux_ entry_ 0 Agent/TCP agents_ Addr Classifier Port Classifier classifier_ dmux_ entry_ 1 0 Link n0- n1 Link n1- n0 0 Agent/TCPSink agents_ dst_=1.0 dst_=0.0 Application/FTP set ftp [new Application/FTP] $tcp attach-agent $ftp
  • 60. Schedule The CBRSchedule The CBR To tell CBR to When to start & stopTo tell CBR to When to start & stop the data sendingthe data sending CommandCommand $ns at 0.5 "$cbr0 start“$ns at 0.5 "$cbr0 start“ $ns at 4.5 "$cbr0 stop“$ns at 4.5 "$cbr0 stop“  AfterAfter 55 simulation secondssimulation seconds cbr0cbr0 startstart the sending packet and afterthe sending packet and after 4.54.5m itm it stopstop
  • 61. 6161 Packet Flow 0 1 n0 n1 Addr Classifier Port Classifier entry_ 0 Agent/TCP Addr Classifier Port Classifier entry_ 1 0 Link n0- n1 Link n1- n0 0 Agent/TCPSink dst_=1.0 dst_=0.0 Application/FTP
  • 62. Wired Example ProgramWired Example Program (UDP Communication)(UDP Communication)  Two NodesTwo Nodes  One LinkOne Link  UDP CommunicationUDP Communication  BandwidthBandwidth  DelayDelay  Drop tail QueueDrop tail Queue
  • 63. Arshad KhanArshad Khan 6363 A simple Example – Creating the topologyA simple Example – Creating the topology n1 n2 Bandwidth:1Mbps Latency: 10ms
  • 64. Arshad KhanArshad Khan 6464 Adding trafficAdding traffic n1 n2 1Mbps,10ms udp null cbr Packet Size: 500 bytes rate: 800Kbps cbr traffic 0.0 0.5 5.0 4.5 time node agent source link
  • 65. All at One GlanceAll at One Glance 1.1. Create Simulator ObjectCreate Simulator Object 2.2. Open a Network Animator FileOpen a Network Animator File 3.3. Finish ProcedureFinish Procedure 4.4. Create a NodesCreate a Nodes 5.5. Create a LinkCreate a Link 6.6. Create & Attach UDP agent at One NodeCreate & Attach UDP agent at One Node 7.7. Create & Attach CBR agent to UDP AgentCreate & Attach CBR agent to UDP Agent 8.8. Attach NULL agent To another NodeAttach NULL agent To another Node 9.9. Connect The Agents ( UDP & NULL)Connect The Agents ( UDP & NULL) 10.10. Schedule The Start and Stop Time To CBR AgentSchedule The Start and Stop Time To CBR Agent 11.11. Call the Finish procedure (Schedule the Simulation)Call the Finish procedure (Schedule the Simulation) 12.12. Run The SimulationRun The Simulation
  • 66. Wired Example ProgramWired Example Program (TCP Communication)(TCP Communication)  Two nodesTwo nodes  One linkOne link  TCP CommunicationTCP Communication  BandwidthBandwidth  DelayDelay  Drop tail QueueDrop tail Queue
  • 67. All at One GlanceAll at One Glance 1.1. Create Simulator ObjectCreate Simulator Object 2.2. Open a Network Animator FileOpen a Network Animator File 3.3. Finish ProcedureFinish Procedure 4.4. Create a NodesCreate a Nodes 5.5. Create a LinkCreate a Link 6.6. Create & Attach TCP agent at One NodeCreate & Attach TCP agent at One Node 7.7. Create & Attach CBR agent to TCP AgentCreate & Attach CBR agent to TCP Agent 8.8. Attach TCPSINK agent To another NodeAttach TCPSINK agent To another Node 9.9. Connect The Agents ( TCP & TCPSINK)Connect The Agents ( TCP & TCPSINK) 10.10. Schedule The Start and Stop Time To CBR AgentSchedule The Start and Stop Time To CBR Agent 11.11. Call the Finish procedure (Schedule the Simulation)Call the Finish procedure (Schedule the Simulation) 12.12. Run The SimulationRun The Simulation
  • 68. Wired Example ProgramWired Example Program (TCP Communication)(TCP Communication)  Two nodesTwo nodes  One linkOne link  TCP CommunicationTCP Communication  BandwidthBandwidth  DelayDelay  Drop tail QueueDrop tail Queue
  • 69. Example : TCPExample : TCP set ns [new Simulator] set n0 [$ns node] set n1 [$ns node] n0 n1 set ftp [new Application/FTP] $ftp attach-agent $tcp $ns at 0.2 "$ftp start" $ns at 1.2 ”exit" $ns run $ns duplex-link $n0 $n1 1.5Mb 10ms DropTail set tcp [new Agent/TCP] set tcpsink [new Agent/TCPSink] $ns attach-agent $n0 $tcp $ns attach-agent $n1 $tcpsink $ns connect $tcp $tcpsink
  • 70. Script to startScript to start namnam set nf [open out.nam w]set nf [open out.nam w] $ns namtrace-all $nf$ns namtrace-all $nf proc finish {} {proc finish {} { global ns nfglobal ns nf $ns flush-trace$ns flush-trace close $nfclose $nf exec nam out.nam &exec nam out.nam & exit 0exit 0 }} # your code goes in here# your code goes in here $ns at 12.0 "finish" # 12.0 is the simulation time in secs$ns at 12.0 "finish" # 12.0 is the simulation time in secs
  • 71. 7171 Script CodeScript Code # Create a topology# Create a topology Set ns [new Simulator]Set ns [new Simulator] set n0 [$ns node]set n0 [$ns node] set n1 [$ns node]set n1 [$ns node] $ns duplex-link $n0 $n1 1Mb 10ms DropTail$ns duplex-link $n0 $n1 1Mb 10ms DropTail # Add Transport agents# Add Transport agents set tcp [new Agent/TCP]set tcp [new Agent/TCP] $ns attach-agent $n0 $tcp$ns attach-agent $n0 $tcp set tcpsink [new Agent/TCPSink]set tcpsink [new Agent/TCPSink] $ns attach-agent $n1 $tcpsink$ns attach-agent $n1 $tcpsink $tcp connect $tcpsink$tcp connect $tcpsink # Add application# Add application set ftp [new Application/FTP]set ftp [new Application/FTP] $ftp attach-agent $tcp$ftp attach-agent $tcp # Create a schedule $ns at 0.5 "$ftp start" $ns at 4.5 "$ftp stop" #Run the simulation $ns run n0 n1 1Mb 10ms FTP TCP FTP TCP
  • 72. 7272 Discrete Event-Driven Simulator time_, uid_, next_, handler_ head_ -> handler_ -> handle() time_, uid_, next_, handler_insert $ns at 0.5 “$ftp start” $ns at 4.5 “$ftp stop” $ns run
  • 73. Packets Dropping from linkPackets Dropping from link
  • 74. Cont…Cont…  Create 4 nodes with 3 links.Create 4 nodes with 3 links.  Bandwidth 1mbps & Delay 10ms.Bandwidth 1mbps & Delay 10ms.  UDP Agent at node n0,n1.UDP Agent at node n0,n1.  NULL Agent at node n3.NULL Agent at node n3.
  • 75. Thank you for your patientThank you for your patient

Notas do Editor

  1. - The goal for us is to understand how networks work by simulating them. - we’ll be looking at the following in particulat - fundamentals of event simulation – what are events? How are they tracke? - details of a particular popular network simulator other - other examples are opnet, qualnet etc
  2. We should go ahead and observe tha actual system if possible, but we can’t do so for a variety of reasons. More importantly, Simulation can let you abstract out some of the complexity. Simulation is repeatable – When studying flash crowds, its hard to create flash crowds again and again, but its possible to simulate them as many times as needed
  3. Simulation lets you separate the design bugs from the implementation bugs (for example – a server farm - have not got enough provisioning) – estimate etc
  4. Read
  5. NS2 lets us create topologies with different nodes, different types of links in betweeb them
  6. The picture shows an example trace file: - + shows that a packet entered the queue - shows that a packet left the queue - r shows the packet was received time, type of packet etc
  7. So lets start by creating a topology is NS2, we’re just defining stuff, no packets are going through yet
  8. We are going to extend the example now: we are going to attach a udp agent to n1 and a sink at n2. (agents are abstractions – of “sockets” that are present in unix) We are going to use udp to send constant bit-rate traffic – what this means is – that the rate is constant and packet size is constant (we will set these parameters)
  9. How are you going to fit this whole thing onto one slide? Consider making one slide for the topology, one time to schedule the events.