75
Introduction To NS-2 Introduction To NS-2 By Arshad Ahmad Khan Mohammad Part Time Research Scholar (CNIS) KL University, Andhra Pradesh India, .

Ns2 by khan

Embed Size (px)

DESCRIPTION

Easy way to learn ns2

Citation preview

Page 1: Ns2 by khan

Introduction To NS-2Introduction To NS-2

ByArshad Ahmad Khan Mohammad

Part Time Research Scholar (CNIS) 

KL University, Andhra PradeshIndia,

.

Page 2: Ns2 by khan

Outline Of PresentationOutline Of Presentation

IntroductionIntroduction InstallationInstallation ArchitectureArchitecture Tcl & Otcl ExamplesTcl & Otcl Examples Simulation StepsSimulation Steps Examples (Wired)Examples (Wired) Examples (Wireless)Examples (Wireless)

Page 3: Ns2 by khan

IntroductionIntroduction

About NS2About NS2 Advantages of NS2Advantages of NS2 NS2 Supported Protocols(Wired & NS2 Supported Protocols(Wired &

Wireless)Wireless)

Page 4: Ns2 by khan

Arshad KhanArshad Khan 44

Network Simulation *Network Simulation *

Motivation:Motivation: Learn fundamentals of Learn fundamentals of

evaluating network evaluating network performance via performance via simulationsimulation

Overview:Overview: fundamentals of fundamentals of

discrete event discrete event simulationsimulation

ns-2 simulationns-2 simulation

Page 5: Ns2 by khan

Arshad KhanArshad Khan 55

Why Simulation? *Why Simulation? *

real-system not real-system not available, is complex/costly or available, is complex/costly or dangerousdangerous ( (eg: space simulations, flight eg: space simulations, flight simulations)simulations)

quickly evaluate design quickly evaluate design alternativesalternatives (eg: (eg: different system configurations)different system configurations)

evaluate evaluate complex functionscomplex functions for which closed for which closed form formulas or numerical techniques not form formulas or numerical techniques not availableavailable

Page 6: Ns2 by khan

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 techniques over analytic/numerical techniques• detail:detail: can simulate system details at arbitrary can simulate system details at arbitrary

levellevel drawbacks:drawbacks:

• caution: does model reflect realitycaution: does model reflect reality• large scale systems: lots of resources to large scale systems: lots of resources to

simulate (especially accurately simulate)simulate (especially accurately simulate)• may be slow (computationally expensive – 1 may 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

Page 7: Ns2 by khan

OverviewOverview

Ns2 is event simulator where the advance Ns2 is event simulator where the advance of time depends on the timing of events of 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 data Scheduler – maintains ordered data

structure with the events to be executed structure with the events to be executed and fires them one by one, invoking the and fires them one by one, invoking the handler of the event. handler of the event.

Page 8: Ns2 by khan

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 their Events 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

Page 9: Ns2 by khan

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!

Page 10: Ns2 by khan

1010

Discrete Event ExamplesDiscrete Event Examples

Consider two nodeson an Ethernet:

A B

simplequeuingmodel:

t=1, A enqueues pkt on LANt=1.01, LAN dequeues pkt

and triggers B

detailedCSMA/CDmodel:

t=1.0: A sends pkt to NICA’s NIC starts carrier sense

t=1.005: A’s NIC concludes cs,starts tx

t=1.006: B’s NIC begins reciving pktt=1.01: B’s NIC concludes pkt

B’s NIC passes pkt to app

Page 11: Ns2 by khan

1111

ns-2 Environmentns-2 EnvironmentSimulation 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();

••

}

Page 12: Ns2 by khan

1212

LanguagesLanguages

C++ for C++ for datadata• Per-packet processing, the core of Per-packet processing, the core of nsns• Fast to run, detailed, complete controlFast to run, detailed, complete control

OTcl for OTcl 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)

Page 13: Ns2 by khan

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

Page 14: Ns2 by khan

““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

Page 15: Ns2 by khan

““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"

Page 16: Ns2 by khan

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

Page 17: Ns2 by khan

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

Page 18: Ns2 by khan

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"

Page 19: Ns2 by khan

1919

Basic TclBasic Tcl# Variables:# Variables:setset x 10 x 10set set xxputsputs “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 $xincrincr x –1 x –1

}}for for {{set set i 0} {$i<10} {i 0} {$i<10} {incr incr i} {i} {

puts puts “$\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]

set set line [line [gets gets $file]$file]

puts –nonewline puts –nonewline $file “hello!”$file “hello!”

close close $file$file

Page 20: Ns2 by khan

2020

Basic OTclBasic OTclClass 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

Child Child 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

Page 21: Ns2 by khan

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, various Tracing, visualization, emulation, various

Page 22: Ns2 by khan

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

Page 23: Ns2 by khan

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 modelEnergy model

• • Omni-directional antenna with unity gainOmni-directional antenna with unity gainnsns

Page 24: Ns2 by khan

InstallationInstallation

This Work is available at explanation This Work is available at explanation timetime

Page 25: Ns2 by khan

©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

Page 26: Ns2 by khan

ArchitectureArchitecture

LanguagesLanguages Internal StructureInternal Structure Architecture (User view)Architecture (User view)

Page 27: Ns2 by khan

2727

App1

Agent1

App2

Agent2

Node

From Network to SimulationFrom Network to SimulationApplication,

Agent & Node

Link

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"

Page 28: Ns2 by khan

2828

Class Hierarchy (partial)Class Hierarchy (partial)TclObject

NsObject

Connector Classifier

Queue Delay Agent Trace

Enq Deq Drop

AddressClassifier

TCP

SACKReno

DropTail RED Table 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)

Page 29: Ns2 by khan

Arshad KhanArshad Khan 2929

What is NS2?What is NS2?

Network SimulatorNetwork Simulator A package of tools that simulates A 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 the Analyze events to understand the

network behavior network behavior

Page 30: Ns2 by khan

Arshad KhanArshad Khan 3030

Creating TopologiesCreating Topologies

n1

n4

n2

n5

n6

n3

5Mbps,10ms

2Mbps,20ms

300Kbps,100ms

300Kbps,100ms

500Kbps,50ms

Page 31: Ns2 by khan

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

Page 32: Ns2 by khan

Arshad KhanArshad Khan 3232

Observing Network BehaviorObserving Network Behavior

Observe behavior by tracing Observe behavior by tracing “events”“events”• Eg. packet received, packet drop etc. Eg. packet received, packet drop etc.

time

Src Dst IP Address, Port

Page 33: Ns2 by khan

Step2: TracingStep2: Tracing

Page 34: Ns2 by khan

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 Simulation Execution Time for Simulation Procedure (Calling finish Procedure)Procedure (Calling finish Procedure)

5.5. Start The SimulationStart The Simulation

Page 35: Ns2 by khan

Basic Simulation StepsBasic Simulation Steps

Creating Simulation ObjectCreating Simulation ObjectCommandCommand

*set ns [new Simulator]**set ns [new Simulator]*1.1. Set ns -Set ns -Declare The New Variable Name Declare The New Variable Name nsns Using The Using The setset Command. Command.

2.2. [new Simulator]-[new Simulator]-is indeed The Instantiation of The Class is indeed The Instantiation of The Class SimulatorSimulator Using The Using The Keyword Keyword newnew

3.3. So So nsns is The is The SimulatorSimulator Object Object

4.4. Now Using Now Using nsns Variable We Can Access All The Methods of Class Variable We Can Access All The Methods of Class SimulatorSimulator

Page 36: Ns2 by khan

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 file Open a Trace file out.namout.nam for writng and give it to file handler for writng and give it to file handler

tracefile1tracefile1..

2.2. We Are Telling Simulator Object We Are Telling Simulator Object nsns To We Have Created a file To Write To We Have Created a file To Write all The Data Related to Network animator on That Fileall The Data Related to Network animator on That File

3.3. With in a TCL Script file is not called by its name(With in a TCL Script file is not called by its name(out.namout.nam) but Using ) but Using Pointer ( Pointer ( tracefile1tracefile1 ) . ) .

Page 37: Ns2 by khan

Cont….Cont….

namtrace-all-namtrace-all-It is a It is a SimulatorSimulator method method which takes the parameter as file which takes the parameter as file name (name (tracefile1tracefile1)where trace will go.)where trace will go.

Page 38: Ns2 by khan

Basic Simulation StepsBasic Simulation Steps

Finish ProcedureFinish Procedure

CODECODEproc finish {} { proc finish {} {

global ns tracefile1 global ns tracefile1

$ns flush-trace $ns flush-trace

close $tracefile1close $tracefile1

exec nam out.nam & exec nam out.nam &

exit 0exit 0

}}

Page 39: Ns2 by khan

CONT…CONT…

proc finish {}- proc finish {}- The word The word procproc declares a declares a procedure name procedure name finishfinish without any without any argumentsarguments

global ns tracefile1- global ns tracefile1- The word global is The word global is used to tell we are using the variable used to tell we are using the variable which has declared outside the procedure which has declared outside the procedure ((finishfinish) i.e.,) i.e.,ns, tracefile1 ns, tracefile1

$ns flush-trace- $ns flush-trace- flush-traceflush-trace is a is a SimulatorSimulator method which is used to dump the traces method which is used to dump the traces on the respective files.on the respective files.

Page 40: Ns2 by khan

Cont..Cont..

close $tracefile1- close $tracefile1- which close the which close the tracefile1tracefile1

exec nam out.nam &- exec nam out.nam &- exeexe exicute exicute the the namnam for visualation for visualation

exit 0- exit 0- normal termination of normal termination of procedureprocedure

Page 41: Ns2 by khan

Basic Simulation StepsBasic Simulation Steps

Execution Time for Simulation Procedure Execution Time for Simulation Procedure (Calling finish Procedure)(Calling finish Procedure)

Command Command

*$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 finish finish procedure after 5 procedure after 5 second of second of simulationsimulation time time

Page 42: Ns2 by khan

Basic Simulation StepsBasic Simulation Steps

Start the simulationStart the simulation

CommandCommand

*$ns run**$ns run*

Which is start the simulationWhich is start the simulation

Page 43: Ns2 by khan

Simplified SceniroSimplified Sceniro

Page 44: Ns2 by khan

Creating Nodes & LinksCreating Nodes & Links

1.1. Creating NodesCreating Nodes

2.2. Creating LinksCreating Links

Page 45: Ns2 by khan

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 with A new node object is created with

the command the command '$ns node''$ns node'. . The above code creates two nodes The above code creates two nodes

and assigns them to the handles and assigns them to the handles 'n0''n0' and and 'n1''n1'..

Page 46: Ns2 by khan

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]

Page 47: Ns2 by khan

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 to Code tells the simulator object to

connect the nodes connect the nodes n0n0 and and n1n1 with a with a duplex linkduplex link with the with the bandwidth bandwidth 1Megabit1Megabit, a , a delay of 10msdelay of 10ms and a and a Drop Tail queue.Drop Tail queue.

Page 48: Ns2 by khan

4848

Network Topology - Link

n0 n1

enqT_ queue_ deqT_

drophead_ drpT_

link_ ttl_

n1 entry_head_

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

Page 49: Ns2 by khan

4949

Routing

n0 n1

Addr Classifier

Port Classifier

classifier_

dmux_

entry_

0

1

Addr Classifier

Port Classifier

classifier_

dmux_

entry_

1

0Link n0-n1

Link n1-n0

Page 50: Ns2 by khan

Creating AgentsCreating Agents

In ns, data is always being sent from In 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

Page 51: Ns2 by khan

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 a These lines create a UDP agent UDP agent

(udp0) (udp0) Attach Agent (Attach Agent (udp0udp0)to the node )to the node n0n0

Page 52: Ns2 by khan

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 a These lines create a TCP agent (tcp0) TCP agent (tcp0) Attach Agent (Attach Agent (tcp0tcp0)to the node )to the node n0n0

Page 53: Ns2 by khan

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

0Link 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

Page 54: Ns2 by khan

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 rate stands for 'constant bit rate First line create the First 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

Page 55: Ns2 by khan

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 Agent These line Creates a Null Agent

(null0) (null0) Which act as a traffic sink.Which act as a traffic sink. Attach Agent Attach Agent (null0)(null0) to the node to the node n1n1

Page 56: Ns2 by khan

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 a These lines creates a TCPSink TCPSink

Agent(sink0)Agent(sink0) Attach agent Attach agent (sink0) (sink0) to the node to the node n0n0

Page 57: Ns2 by khan

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 two Which is used to connect the two

agents agents udp0udp0 and and null0null0..

Page 58: Ns2 by khan

Connect The AgentsConnect The Agents

Connect The Two Agents TCP &TCP SINK Connect The Two Agents TCP &TCP SINK

CommandCommand

*$ns connect $tcp0 $sink0**$ns connect $tcp0 $sink0* Which is used to connect the two Which is used to connect the two

agents agents tcp0tcp0 and and sink0sink0..

Page 59: Ns2 by khan

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

0Link n0-n1

Link n1-n0

0 Agent/TCPSink

agents_

dst_=1.0 dst_=0.0Application/FTP

set ftp [new Application/FTP]$tcp attach-agent $ftp

Page 60: Ns2 by khan

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“ After After 55 simulation seconds simulation seconds cbr0cbr0 start start

the sending packet and after the sending packet and after 4.54.5m it m it stopstop

Page 61: Ns2 by khan

6161

Packet Flow

0

1

n0 n1

Addr Classifier

Port Classifier

entry_

0 Agent/TCP Addr Classifier

Port Classifier

entry_

1

0Link n0-n1

Link n1-n0

0 Agent/TCPSink

dst_=1.0 dst_=0.0Application/FTP

Page 62: Ns2 by khan

Wired Example Program Wired Example Program (UDP Communication)(UDP Communication)

Two NodesTwo Nodes One LinkOne Link UDP CommunicationUDP Communication BandwidthBandwidth DelayDelay Drop tail QueueDrop tail Queue

Page 63: Ns2 by khan

Arshad KhanArshad Khan 6363

A simple Example – Creating the topologyA simple Example – Creating the topology

n1 n2

Bandwidth:1MbpsLatency: 10ms

Page 64: Ns2 by khan

Arshad KhanArshad Khan 6464

Adding trafficAdding traffic

n1 n21Mbps,10ms

udpnull

cbr

Packet Size: 500 bytesrate: 800Kbps

cbr traffic

0.00.5 5.04.5 time

node agent

source

link

Page 65: Ns2 by khan

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

Page 66: Ns2 by khan

Wired Example Program Wired Example Program (TCP Communication)(TCP Communication)

Two nodesTwo nodes One linkOne link TCP CommunicationTCP Communication BandwidthBandwidth DelayDelay Drop tail QueueDrop tail Queue

Page 67: Ns2 by khan

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

Page 68: Ns2 by khan

Wired Example Program Wired Example Program (TCP Communication)(TCP Communication)

Two nodesTwo nodes One linkOne link TCP CommunicationTCP Communication BandwidthBandwidth DelayDelay Drop tail QueueDrop tail Queue

Page 69: Ns2 by khan

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

Page 70: Ns2 by khan

Script to start Script to start namnam

set nf [open out.nam w]set nf [open out.nam w]$ns namtrace-all $nf$ns namtrace-all $nfproc 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

Page 71: Ns2 by khan

7171

Script CodeScript Code

# Create a topology# Create a topologySet 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 agentsset tcp [new Agent/TCP]set tcp [new Agent/TCP]$ns attach-agent $n0 $tcp$ns attach-agent $n0 $tcpset 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 applicationset 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 n11Mb

10ms

FTP

TCP

FTP

TCP

Page 72: Ns2 by khan

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

Page 73: Ns2 by khan

Packets Dropping from linkPackets Dropping from link

Page 74: Ns2 by khan

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.

Page 75: Ns2 by khan

Thank you for your patientThank you for your patient