Monday, September 5, 2011

a simple code for ns2

following code is a good example to understand how to write a simple tcl script for ns2 simulation.

#simulator object
set ns [new Simulator]

#colouring the class 1 packet
$ns color 1 Blue
$ns color 2 Red

#open a file to write and attaching it to ns object
set nf [open out.nam w]
$ns namtrace-all $nf

#process finish called at the last
proc finish {} {
          global ns nf
          $ns flush-trace
          close $nf
          exec nam out.nam &
          exit 0
           }

#creation of node       
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#creation of link
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
#we created a stochastic fair queu between 2 and 
$ns duplex-link $n2 $n3 0.5Mb 10ms SFQ

#for layout of links
$ns duplex-link-op $n0 $n2 orient right-down     
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#setting udp agent
set udp0 [new Agent/UDP]
set udp1 [new Agent/UDP]

$ns attach-agent $n0 $udp0
$ns attach-agent $n1 $udp1

#setting traffic agent then it will attach to udp agent
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval 0.005
$udp0 set class_ 1
#attaching cbr agent to udp agent
$cbr0 attach-agent $udp0

set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval 0.005
$udp1 set class_ 2
$cbr1 attach-agent $udp1

#this is sink
set null3 [new Agent/Null]
$ns attach-agent $n3 $null3

$ns connect $udp0 $null3
$ns connect $udp1 $null3

# to make a queu at a node
$ns duplex-link-op $n3 $n2 queuePos 0.5
#monitor a queu

$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
$ns at 1.5 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
#$ns duplex-link-op $n0 $n1 orient right-down
#$ns duplex-link-op $n1 $n2 orient right
#$ns duplex-link-op $n2 $n0 orient right-up

$ns at 5.0 "finish"
$ns run

save this with any *.tcl name and run it simply #ns *.tcl
.... enjoy coding

No comments:

Post a Comment