0% found this document useful (0 votes)
106 views

NS Tutorial

Network Simulator (NS) is a tool used to simulate computer networks. It is written in C++ and uses OTcl (Object Oriented Tool Command Language) as an interface. NS uses two languages because it needs to efficiently implement network protocols (C++) and quickly configure simulations (OTcl). OTcl is used for configuration and setup, while C++ is used for detailed protocol implementation and processing packets. NS can simulate IP networks and implements protocols like TCP and UDP. It allows defining network topologies, traffic sources, and queue management mechanisms. Users write OTcl scripts to configure simulations, define the network, and run the simulation. NS outputs trace files that can be visualized in NAM and other output files containing simulation

Uploaded by

siva kumaar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

NS Tutorial

Network Simulator (NS) is a tool used to simulate computer networks. It is written in C++ and uses OTcl (Object Oriented Tool Command Language) as an interface. NS uses two languages because it needs to efficiently implement network protocols (C++) and quickly configure simulations (OTcl). OTcl is used for configuration and setup, while C++ is used for detailed protocol implementation and processing packets. NS can simulate IP networks and implements protocols like TCP and UDP. It allows defining network topologies, traffic sources, and queue management mechanisms. Users write OTcl scripts to configure simulations, define the network, and run the simulation. NS outputs trace files that can be visualized in NAM and other output files containing simulation

Uploaded by

siva kumaar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 35

Network Simulator Tutorial

Introduction

do. On one hand, a detailed simulation of protocols requires a systems programming


language which can efficiently manipulate bytes, packet headers, and implement algorithms
that run over large data sets. For these tasks run-time speed is important and turn-around time
is less important.

On the other hand, a large part of network research involves slightly varying
parameters or configurations, or quickly exploring a number of scenarios. In these cases,
iteration time is more important. Since configuration runs once, run-time of this part of the
task is less important.

NS meets both of these needs with two languages, C++ and OTcl. C++ is fast to run but
slower to change, making it suitable for detailed protocol implementation. OTcl runs
NS (Network Simulator) is a tool for Simulating Network. NS is an object oriented
simulator, written in C++, with an OTcl (Object Oriented Tool command language)
interpreter as a front end. The simulator supports a class hierarchy in C++ and a similar class
hierarchy within the OTcl interpreter. The two hierarchies are closely related to each other.

NS uses two languages because simulator has two different kinds of things it needs to
much slower but can be changed very quickly, making it ideal for simulation configuration.
NS provide glue to make objects and variables appear on both languages.

Having two languages raises the question of which language should be used for what
purpose.
OTcl is used
 for configuration, setup, and ``one-time'' stuff
 if you can do what you want by manipulating existing C++ objects

and use C++:

 if you are doing anything that requires processing each packet of a flow
 if you have to change the behavior of an existing C++ class in ways that weren't
anticipated
Commands are given to NS in OTcl scripts. You can write this script in any editor such
as Notepad and save them with tcl extension. In OTcl script you can define network topology
by using network objects and functions, traffic sources their start and stop time.

The other thing you specify is the form of outputs. If you want to see the nodes and the
flow of packets, you should command NS to create a special form of output file. This output
file is in text format and will be given to another program called “NAM” to show a view of
network.

NS can create other forms of outputs. You can record any parameter in a file or you can
command NS to create a general output file in which all the events are recorded.

Once you finish writing the OTcl script you can simply run it by writing the following
command in terminal: ns yourscript.tcl. After few minutes (depends on your simulation time)
the results will be available.

What can NS do?

NS can simulate a variety of IP networks. It implements protocols such as TCP and


UDP, traffic sources such as FTP / Telnet / Web / CBR / VBR , queue management
mechanism such as DropTail / RED / CBQ / SFQ / FQ, Routing algorithms, Multicasting and
some MAC layer protocols in LAN simulations.

How to Install?
Before writing any OTcl script you should have ns.exe and nam.exe on your
computer. NS and NAM are available for two platforms: Windows and Linux and also in two
forms. These versions can be downloaded from:
http://www.isi.edu/nsnam/dist/

In the above address you can find several versions of NS and NAM both for
windows(win32) and Linux. The steps for installation of NS in Linux are

1. Download ns-allinone-2.34.tar.gz
2. Copy ns-allinone-2.34.tar.gz into home directory
3. Extract using tar -xvf ns-allinone-2.29.tar.gz. It will extracted as ns-
allinone-2.29
4. Open the terminal and type cd ns-allinone-2.34
5. Type. /install. It will start the installation

Now if you try to run NS you may receive the error that system cannot find tcl83.dll.
Two ways to solve this problem are

1. Tcl83.dll is a dll file that will be copied in your system if you install tcl831 program. The
real job of this program is to run TCL scripts but you don’t use it for any purpose. This
program can be downloaded from many sites like the following
http://www.gkesper.de/home/download/

2. The other way is to download only Tcl83.dll (You can found it easily in internet) and
copy it in the appropriate path

Beginning to Write a Script

NS is an OTcl interpreter. OTcl looks like other programming languages. Here is the
short explanation of OTcl:

A Summery of OTCL Instructions

OTcl is an object oriented extension of Tcl and created by David Wetherall. It is used
in network simulator (NS-2) and usually run under UNIX environment.
Variable definition:
Set myvar1 “avar”
Set myvar2 12

The type is automatically set corresponding to the type of the initial value. After
defining a variable, each time you want to use it you should put $ before it’s name to indicate
that it is a predefined variable.
$myvar1=1

writing some thing to the standard output:


puts “this is myvar1 $myvar1”

finding the result of a numerical expression


set myvar3 [expr $myvar1+$myvar2]

Opening a file for writing


Set file [open filename w]

Writing an expression in a file


Puts $myfile “myvar2=$myvar2”

Repeating a task

For loop
For {set i 0}{$i<20}{incr i}
{puts “current value of i is $i”}

While loop
set i 1
while {$i<5}
{
< some commands>
incr i
}

Condition
If {condition}
{
< some commands>
else
< some commands>
}

Defining procedures
Proc myproc{p1 p2 … pm}
{
Global g1,g2,…
< commands>
return $myoutput
}
Myproc is called with a set of input argument x,y,..,z :
myproc x,y,..,z
In myproc these variables are used to do some kind of processing. They are passed by
value. When you modify the value of the formal arguments in the procedure, it does not
affect the value of the actual arguments. If you want to change the value of the actual
argument, define it as global by the same name as it was defined in the main program. Now
myproc change the value of global variable g1, g2,…, gn.

Classes

Class student
Student instproc exam{}
{
$self instvar mark_
$self instvar id_
puts “student number $id_ your mark is $mark_“
}

If we want to define an object of the type student

Set john[new student]


$john set id_ 81200000
$john set mark_ 80
$john exam

The output will be:


Student number 81200000 your mark is 80

In a class, function and variable can be defined. $self is the same as “this” pointer in
C++ and instvar checks whether the variable name is already declared in the class or supper
class. if so, the variable is referenced and if not, a new one is declared.

Comment Line Argument


#this is a comment

Using OTCL in NS
Once you learn about OTcl instructions, you can use them to write a script for NS.
Use some predefined classes and variables which are added by NS to help you to define a
network.

Here is a list of some important things:


All simulations begin with the following command:
Set ns [new simulator]
By this command you can define an object of type Simulator and give the name ns to it.

Next you should open files for output. We usually have two output files. One is the
visualization trace file for NAM. The other output file contains general results (It will be
explained later).
Set out [open out.tr w]
Set namout [open out.nam w]
$ns trace-all $out

out.tr will contain all the trace information


$ns nametrace-all $namout

out.nam will contain all the trace information in NAM input format. You can also
write set of instructions that NS should do at the time it finishes the simulation. These
instructions are written in the finish procedure. Now close the output files then open and run
NAM to show the results. Finally give exit in the last line of this procedure to come out from
NS.
proc finish{}{
$ns flush-trace
$close $namout
$close $out
exec nam out.nam &
exit 0
}
finishproc is called at the time you want to finish simulation .

$ns at 10 “finish”

After writing this initial things you come to the most important part of defining the
network
In the body of the script you should do the following tasks:
1. Create a Topology (Define Nodes and Links).
2. Set up packet losses and link dynamics.
3. Create agents and attach them to nodes.
4. Create application and attach them to agents.
5. Start events at appropriate times and save your desired outputs.

Defining Nodes

Set n0[$ns node]


n0 is the name you have given to the node

$n1 color "#ff000000ff00"


The color of a node can be changed .you can give a number to determine the color or directly
write the name of the color.

Defining Links

$ns <link-type> $n0 $n1 <bandwidth>


<delay> <queue-type>

options:
<link-type> can be simplex-link or duplex-link
<bandwidth> is a number showing the capacity of the link
<delay> is a number showing the delay of the link
<queue-type> : can be DROPTAIL, RED, CBQ, FQ, SFQ, DRR.

$ns duplex-link $n0 $n2 .2mb 1m DropTail

The buffer capacity of the queue related to each link can be determined
$ns queue-limit $n0 $n2 30

you can also specify the color for a link


$ns duplex-link-op $node(1) $node(3) color #6600cc000000

Creating an UDP Connection

To create an UDP connection between two nodes, first define an UDP agent on any
one node then define a null agent on the other node. The responsibility of the null agent is to
receive an UDP packet and discard them.
Set udp1 [new agent/UDP]
This command creates a UDP agent named udp1

Set nul1 [new agent/Null]


This command create a NULL agent named nul1

Now attach agents to nodes and connect them


$ns attach agent $n0 $udp1
$ns attach agent $n1 $nul1
$ns connect $udp1 $nul1

Some Packets to Flow

To create traffic you should have an application on the top of an UDP agent to
generate packets. There are 3 kinds of applications of UDP agents:
1. CBR (constant bit rate)
2. Exponential
3. Pareto
First step is to create an application
Set cbr1 [new application/traffic/CBR]

Then a traffic source should be attached to the agent:


$udp1 attach-agent $cbr1

Then set the size of packets and rate:


$cbr1 set packet_size_ 500
$cbr1 set rate_ 0.2mb

For exponential and pareto traffic sources, packet size, burst time (the average on time)
idle_time (the average off time) and the rate in time periods can be set.

Creating a TCP Connection

TCP is a reliable protocol and it uses the acknowledgement created by the destination
to know whether the packets are well received. So TCP connection between two nodes
requires duplex link between them for acknowledges returning.
You can define several TCP agents by commands such as following
Set tcp1 [new agent/TCP]

Here is a list of mostly used TCP agents:


TCP
TCP/Reno
TCP/Vegas
TCP/Newreno
To have a TCP connection between two nodes, the destination TCP node should have
a TCP sink on it. TCP sink receives TCP packets and sends acknowledge packets to source.
Set sink [new agent/TCPSink]
Other kinds of TCP Sink also exist in NS notes and Documentations
After defining a source you can set its parameters. Some of them are listed here.
packet size_: size of source packets in bytes
$tcp1 set packet_size_ 500
window_: The upper bound on advertised window
maxcwnd_: Maximum congestion window size
windowInit_: Initial window size in slow start

There are some state variables for a TCP source

dupack_: Number of duplicate acknowledges seen since any new data was acknowledged
seqno_: Highest sequence number for data from data source to TCP
ack_ : Highest acknowledge seen from receiver
cwnd_: Current value of congestion window
ssthresh _: Current value of threshold window size
rtt_ : Round trip time estimate

You can read these parameters from a TCP source using commands like this:
set a [$tcp1 set cwnd_]

The current congestion window size of the source $tcp1 will be saved in variable a.

Defining Traffic Type

You should put an application over a TCP agent. FTP and TELNET are the
application that can be on the top of a TCP agent.
Set ftp1 [new application/FTP]
$ftp1 attach_agent $tcp1

Finding Received and Lost Packets in a Link

Loss monitor agents task is to sink packets and also check for losses
set sink1 [new Agent/LossMonitor]
They record the number of packets received and those which are lost. This information’s
are available in the following state variables:
nlost_ Number of lost packets
n_bytes_ Number of bytes received
n_pakts_ Number of packets received
last pkttime_ Time at which the last packet was received
expected_ The expected sequence number of the next packet
for example:
set b0 [$sink1 set nlost_]

The number of lost packets for sink0 will be saved in variable b0


You can record these variables periodically and so trace the number of lost and received
packets in a node

Modeling Error on a Link

set loss_module [new ErrorModel]


$loss_module set rate_ 0.2
$loss_module ranvar [new RandomVariable/Uniform]
$loss_module drop-target [new Agent/Null]
$ns lossmodel $loss_module $n2 $n3
Now you have a noisy link between n2 and n3

Timing

You should determine the time for the applications to start and stop
$ns at 1.0 “$ftp start”
$ns at 10.0 “$ftp stop”

The general form is


$ns at <specified time> “event”
This event can be the name of a procedure that you want to run at the specified time or it can
be start or stop of an application.

To make a link to fail at a special time


$ns rtmodel-at 1.0 down $n1 $n4
The link between node1 and node4 fails at 1.0sec

$ns rtmodel-at 2.0 up $n1 $n4


The link between node1 and node4 returns at 2.0sec
The First Simple Script

Here is a simple script for creating a topology with four nodes. There is a TCP
connection between two of them and an UDP connection between the other two.
set ns [new Simulator]
set nf [open out.nam w]
#out.nam is the output file generated for NAM
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
#open NAM for showing the results
exec nam out.nam

#terminate the program


exit 0
}

#nodes are defined here


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#define link between nodes


$ns duplex-link $n0 $n1 1Mb 2ms DropTail
$ns duplex-link $n1 $n2 .5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1Mb 2ms DropTail
$ns duplex-link $n3 $n0 2Mb 1ms DropTail

#define agents over nodes


set tcp [ new Agent/TCP]
$ns attach-agent $n1 $tcp
set sink [ new Agent/TCPSink]
$ns attach-agent $n0 $sink
$ns connect $tcp $sink

#define traffic sources


set ftp [new Application/FTP]
$ftp attach-agent $tcp
set udp [ new Agent/UDP]
$ns attach-agent $n3 $udp

set null [ new Agent/Null]


$ns attach-agent $n2 $null
$ns connect $udp $null
set cbr [new Application/Traffic/CBR]
$cbr set packet_size_ 500
$cbr attach-agent $udp

#time scheduling
$ns at 0.1 "$cbr start"
$ns at 0.2 "$ftp start"
$ns at 2.0 "$ftp stop"
$ns at 2.5 "$cbr stop"
$ns at 6.0 "finish"
$ns run

How to Get the Simulation Results

NAM (network animator) is a program that shows network topology and flow of
packets. Input file for NAM is created in OTCL script and the command: exec nam out.nam
causes NAM to open at the end of simulation to show the results. In the above simulation,
after running the simulation NAM window will show you a network like following
Right click on a packet and choose monitor to see the time it was sent , its type and number
of bytes in the monitor part.

Changing Appearances of Output in NAM

There are other commands in OTCL scripts to control some parameters in NAM. For
example the layout of topology can be controlled by determining the orientation of links. If
you don’t control the orientation of links, the topology in NAM window may look a little
awkward.
For example consider the command below:
$ns duplex-link-op $n1 $n2 orient right
This makes the link between nodes $n1 and $n2 is oriented toward right.

And the other forms:


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n4 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

You can make different flows with different colors so that you can recognize them in NAM.
Here is an example to show how to do this:
First set a color for each flow id:
$ns color 1 blue
$ns color 2 purple
$ns color 3 green

Now give a flow id number to each source. The packets which are sent by this source will
have the color related to the flow id number of the source.
$udp set class_ 1
$tcp set class_ 2
In this example udp packets will be in blue color and tcp packets will be in green color.

NAM Editor

Another interesting feature in NAM is that it can create scripts from the network. Run
NAM and select new from the file menu. A page will be opened for you and you can put
nodes, links, agents, applications and other objects and determine their Properties. First put
some nodes. To specify their colors simply right click on a node to edit the properties. Then
put some agents over the nodes and put traffic sources over agents. Now connect both nodes
and agents and change the properties of an agent such as window size for a tcp agent. Also
change the start and stop time of traffic sources. Now save your work. NAM generates an
OTCL script for the network. Run ns directly from NAM editor window to run the generated
script.

The following picture shows a NAM editor window and a topology created in it

although only a small functionality of NS is currently implemented in Nam editor, it can be a


good point to start for beginners who don’t have enough knowledge of NS.

Here is a Sample Script Generated by NAM


#----------------------------------------------------------------
# This ns script has been created by the nam editor.
# If you edit it manually, the nam editor might not
# be able to open it properly in the future.

# EDITING BY HAND IS AT YOUR OWN RISK!


#-------------------------------------------------------------
# Create a new simulator object.
set ns [new Simulator]

# Create a nam trace datafile.


set namfile [open trace.nam w]
$ns namtrace-all $namfile

# Create nodes.
set node(3) [$ns node]

## node(3) at 14.387501,30.750006
$node(3) color "black"
set node(2) [$ns node]
## node(2) at 59.487499,71.450005
$node(2) color "black"
set node(1) [$ns node]

## node(1) at 9.987500,88.775002
$node(1) color "black"

# Create links between nodes.


$ns duplex-link $node(2) $node(3)
10.000000Mb 1.000000ms DropTail
$ns duplex-link-op $node(2) $node(3) queuePos 0.5
$ns duplex-link-op $node(2) $node(3) color black
$ns duplex-link-op $node(2) $node(3) orient 222.1deg
$ns duplex-link $node(1) $node(2) 10.000000Mb 1.000000ms DropTail
$ns duplex-link-op $node(1) $node(2) queuePos 0.5

$ns duplex-link-op $node(1) $node(2) color black


$ns duplex-link-op $node(1) $node(2) orient 340.7deg
$ns duplex-link $node(1) $node(3)
10.000000Mb 1.000000ms DropTail
$ns duplex-link-op $node(1) $node(3) queuePos 0.5
$ns duplex-link-op $node(1) $node(3) color black
$ns duplex-link-op $node(1) $node(3) orient 274.3deg

# Create agents.
set agent(4) [new Agent/TCPSink]
$ns attach-agent $node(3) $agent(4)
$agent(4) set packetSize_ 210
set agent(3) [new Agent/Null]
$ns attach-agent $node(3) $agent(3)
set agent(2) [new Agent/TCP]
$ns attach-agent $node(2) $agent(2)
$ns color 2 "#ff0066006600"
$agent(2) set fid_ 2
$agent(2) set packetSize_ 210
$agent(2) set window_ 20
$agent(2) set windowInit_ 1
$agent(2) set maxcwnd_ 0

# Create traffic sources and add them to the agent.


set traffic_source(2) [new Application/FTP]
$traffic_source(2) attach-agent $agent(2)
$traffic_source(2) set maxpkts_ 256
set agent(1) [new Agent/UDP]
$ns attach-agent $node(1) $agent(1)
$ns color 1 "black"
$agent(1) set fid_ 1
$agent(1) set packetSize_ 210
# Create traffic sources and add them to the agent.
set traffic_source(1) [new
Application/Traffic/CBR]
$traffic_source(1) attach-agent $agent(1)
$traffic_source(1) set packetSize_ 500
$traffic_source(1) set interval_ 0.001950

# Connect agents.
$ns connect $agent(2) $agent(4)

# Traffic Source actions.


$ns at 0.000000 "$traffic_source(2) start"
$ns at 10.000000 "$traffic_source(2) stop"
$ns connect $agent(1) $agent(3)

# Traffic Source actions.


$ns at 0.000000 "$traffic_source(1) start"
$ns at 10.000000 "$traffic_source(1) stop"

# Run the simulation


proc finish {} {
global ns namfile
$ns flush-trace
close $namfile
exec nam trace.nam &
exit 0
}

$ns at 10.000000 "finish"


$ns run

Other Ways to Get the Result of a Simulation

NAM cannot show all the results of a simulation. To get more information on packet
flow and other events, create and process the trace file.
Generate a trace file containing information on all the events using this command:
set f [open out.tr w]
$ns trace-all $f
and close this file in finish procedure:
close $f

During the simulation a file named out.tr will be created.


The out put file contains 12 columns that each of them records a parameter. The following is
a part of this file:
r 1.130687 2 0 tcp 552 ------- 1 2.0 5.0 112 365
+ 1.130687 0 1 tcp 552 ------- 1 2.0 5.0 112 365
d 1.130687 0 1 tcp 552 ------- 1 2.0 5.0 112 365
r 1.131294 1 6 tcp 552 ------- 2 3.0 6.0 36 203
+ 1.131294 6 1 ack 40 ------- 2 6.0 3.0 36 375
- 1.131294 6 1 ack 40 ------- 2 6.0 3.0 36 375
r 1.1324 6 1 ack 40 ------- 2 6.0 3.0 33 366
+ 1.1324 1 0 ack 40 ------- 2 6.0 3.0 33 366
- 1.1324 1 0 ack 40 ------- 2 6.0 3.0 33 366

Columns contain the following parameters:

Event: This field can take four values


r: receive
+:en queue
-:de queue
d :drop

time: The time at which the event occurred


from node: Number of the input node of the link at which the event occurred
to node: Number of the output node of the link at which the event occurred
packet type: Type of the packet .it can be tcp, ack or any other acceptable type.
Packet size: Size of packet in bytes
Flags: ------- means no flag has been set
Flow id: Users can specify an id for each flow. this id can be used to specify a color for
each flow.
Src address: Source address of the packet in the form: node.port
dst address: Destination address of the packet in the form: node.port
Seq number: The sequence number of packet in network layer
Packet id: A unique number given to each packet
NS Components
To understand the parameters of a trace file, let’s take a look at NS components .

Node

Node is a compound object including an entry point ,an address classifier and a port
classifier:

When the agent on a node wants to send something, packets flows through the node
entry to address classifier and then to the link. The incoming packets follow a path from node
entry to address classifier and then the port classifier to reach the agent. A node can have
several links or several agents attached to it. Port classifier acts like a demultiplexer that
sends the incoming packet to one of the agent. It selects the agent according to the port
address of the packet. Address classifier is also like a demultiplexer that selects a link among
several links attached to a node. It uses the address field of packets to do this selection. Here
is a simple example of two nodes.
Link

Link is also a compound object in NS. Output queue of a node is implemented as a


part of link attached to that node. Packets released from the node enter the queue. After
coming out of queue, packets are passed to an object which implements the delay of the link.
The packets to be dropped are passed to an internal Null agent and freed there. After the
delay object, packets enter the TTL object which calculates the time to live for each packet
and updates the TTL field of the packet.

If NS wants to trace a link, some trace objects would be added to the model. These are
(EnqT, Deqt, DrpT, recvT)

In the presence of trace objects link model is like this:


When each of trace objects receive a packet it writes the event and other parameters
in the trace file and passes the packet to the next object without consuming any time. So
these trace objects don’t have any effect on network behavior and they only record data for
the event they trace. For example EnqT objects are responsible for recording en-queue events
in the trace file.

Packet

Packets contain two parts. The first part is a stack of headers containing real network
headers such as TCP and ip headers and other header is used for tracing packets.

The data field is usually empty in normal traces but you can define new packets with Non
empty data part.

Other Forms of Output


Trace file contains detailed information about all nodes and all events and you may
need to extract some special data from it. Many programs can be used to handle the output
file to get the desired information. One of them mostly used to extract data from the output
file is perl and to plot the results NS users often use Xgraph.

Perl is an interpreter used to write several kinds of programs and is not dedicated only
for processing output files of NS, but it has good capabilities to do so. You can easily find
and download perl interpreter. Perl program files have “pl” extension .you may encounter
these files in NS package.

Xgraph is a general purpose plotter program. Xgraph is not a part of the NS package.
So download it separately and make it to get xgraph.exe in your scripts you can call it to plot
the contents of file1 and file2 with this command:
Exec xgraph file1 file2
But if you don’t want to work with perl and xgraph, another way to process the output file
and plot the results is using MATLAB, which can do both tasks.

Plotting the Desired Information Using Matlab

In MATLAB use the following command to read formatted data from the output file:
[a,b,c,…]=textread (filename, format)

This command reads data from the input file into variables a, b, c and the type of each
return argument is specified by the format string.

To read all the columns from the output file with appropriate type you should
consider the meaning of each column to find its type. For example if the second column is
time and its type is float then use %f as the second parameter in format string.

The output file contains 12 columns. To read all output file contents, specify the
variables of
suitable types:
[a,b,c,d,e,f,g,h,i,j,k,l]=textread (‘out.tr’,'%s%f%d%d%s%d%s%d%f%f%d%d');

%s is for string and %d is for integer format.

Now you have all the columns in vectors that can be processed or plotted.
More Things to Simulate

LAN (Local Area Network)


Ns can simulate LANs with IEEE_802.3 protocol in MAC layer.

set lan [$ns make-lan $nodelist $opt (bw) $opt (delay) \


-llType $opt (ll) -ifqType $opt (ifq) \
-macType $opt (mac) -chanType $opt (chan)]

Here is an example

set lan_ [$ns make-lan $nodelist 10Mb 1ms LL Queue/DropTail Mac/802_3


Channel]

By this command NS will create a LAN between the nodes specified in nodelist. The
other options such as bandwidth ,delay, data link layer, type, interface queue, MAC layer
type and type of channel (note: you cannot write CSMA/CD instead of 802_3 .it is not
supported any more).

The node is the list of nodes in the LAN. For example a LAN of five nodes are specified as:

for {set i 0} {$i 4} {incr i} {


set node($i) [$ns node]
lappend nodelist $node($i)
}

If you look at the trace file after simulation you will see another node that you haven’t
defined before. It’s like a virtual node that stands between the nodes. For sending data to
another node, each node first send it’s packet to this virtual node called LAN node then the
LAN node transfer it to the destination.

The primary purpose of LAN node is to make LANs work with ns routing. Ns
topology is stored in link array indexed by source and destination. To represent connectivity
of a LAN one can either set a mesh of links or create another virtual node. For example:

a) mesh of links to show that any node can send packets to any other node:
set link_(1:2) ...
set link_(2:3) ...
set link_(3:1) ...
set link_(2:1) ...
set link_(3:2) ...
set link_(1:3) ...

b) "virtual node": 4
set link_(1:4) ...
set link_(2:4) ...
set link_(3:4) ...
set link_(4:1) ...
set link_(4:2) ...
set link_(4:3) ...

123
Note that b scales better than a for larger number of nodes.
Aside from that, LAN node is a container for all shared LAN objects, including LAN-
Router. In the example above, suppose that there is another node 5 which is not on the
LAN, but connected by a point to point link to 1. Suppose 2 wants to send a packet to 5. It
knows that the next hop is node 4 (the virtual node). It sends it to 4 thereby handing it off to
the link layer. LL is supposed to set a mac dest address for the packet, so it needs to know
who the next hop is (which LAN node) but all it can see it the packet dest address, Since LL
by itself doesn't have any connectivity info, it goes off and asks LANRouter for the next hop,
then sets the Mac dest address and gives packet to the MAC layer.

LAN Example:
set opt(qsize) 100
set opt(bw) 10Mb
set opt(delay) 1ms
set opt(ll) LL
set opt(ifq) Queue/DropTail
set opt(mac) Mac/802_3
set opt(chan) Channel
proc finish {} {
global ns tr ntr
$ns flush-trace
close $tr
close $ntr
exec nam out.nam &
exit 0
}

set ns [new Simulator]


$ns color 1 blue
$ns color 2 green
$ns color 3 red
set tr [open out.tr w]
$ns trace-all $tr
set ntr [open out.nam w]
$ns namtrace-all $ntr
for {set i 0} {$i < 8} {incr i} {
set node($i) [$ns node]
lappend nodelist $node($i)
}

set lan [$ns newLan $nodelist $opt(bw) $opt(delay) \


-llType $opt(ll) -ifqType $opt(ifq) \
-macType $opt(mac) -chanType $opt(chan) -macTrace on]
set node0 [$ns node]
$ns duplex-link $node0 $node(0) 2Mb 2ms DropTail
$ns duplex-link-op $node0 $node(0) orient right
set source [new Agent/UDP]
$source set class_ 2

$ns attach-agent $node(1) $source


set traffic [new Application/Traffic/Exponential]
$traffic set packet_size_ 500
$traffic set rate_ 1mb
$traffic attach-agent $source

set sink0 [new Agent/LossMonitor]


$ns attach-agent $node(7) $sink0
$ns connect $source $sink0
set source1 [new Agent/UDP]
$source1 set class_ 1
$ns attach-agent $node(2) $source1

set traffic1 [new Application/Traffic/Exponential]


$traffic1 set packet_size_ 500
$traffic1 set rate_ 1mb
$traffic1 attach-agent $source1
set sink1 [new Agent/LossMonitor]
$ns attach-agent $node(7) $sink1
$ns connect $source1 $sink1

set source2 [new Agent/UDP]


$source2 set class_ 3
$ns attach-agent $node(4) $source2
set traffic2 [new Application/Traffic/Exponential]
$traffic2 set packet_size_ 500
$traffic2 set rate_ 1mb
$traffic2 attach-agent $source2

set sink2 [new Agent/LossMonitor]


$ns attach-agent $node(5) $sink2
$ns connect $source2 $sink2
$ns at 0.1 "$traffic start"
$ns at 0.2 "$traffic1 start"
$ns at 0.0 "$traffic2 start"
$ns at 2 "finish"

Routing

1. Unicast Routing

1.1 Static routing


If you didn’t specify any thing, routing will be static by default or you can write:
$ns rtproto static

The shortest path is computed from Dijkstra’s all-pairs SPF algorithm once at the
start of simulation and the routes will be used

During the rest of simulation, if a path fails, the packets will be dropped although
there are some other ways for them because the routing is independent of network conditions.

You can also define the costs for links:


$ns cost $n1 $n3 2

Set the cost of link between these two nodes to 2. Route computed bases on your
specified costs

1.2. Session routing

It’s like static routing except that it re computes the route whenever there is a change
in topology
$ns rtproto session

1.3. DVR (Distance Vector Routing)

This protocol is a kind of dynamic routing. The route gets changed when network
conditions changed. To run this protocol you need Distance Vector Routing protocol agent.
$ns rtproto DV

Now you can see small packets in NAM that are vectors transferred between nodes.
You can also see these packets in trace file. Their type is rtProtoDV and they are created and
sent in periodic intervals by each agent.
Here is a sample for DV routing:
set ns [new Simulator]
$ns color 1 Blue
$ns rtproto DV

set nf [open out.nam w]


$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace

#Close the trace file


close $nf

#Execute nam on the trace file


exec nam out.nam &
exit 0}

#Create seven nodes


for {set i 0} {$i <7} {incr i} {
set n($i) [$ns node]
}
$ns duplex-link $n(0) $n(1) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(2) 1Mb 10ms DropTail
$ns duplex-link $n(2) $n(4) 1Mb 10ms DropTail
$ns duplex-link $n(4) $n(5) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(5) 1Mb 10ms DropTail
$ns duplex-link $n(5) $n(6) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(3) 1Mb 10ms DropTail
$ns duplex-link $n(3) $n(6) 1Mb 10ms DropTail

set udp0 [new Agent/UDP]


$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
$udp0 set fid_ 1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(0) $n(5)
$ns rtmodel-at 2.0 down $n(4) $n(5)
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run
The vectors are negotiated at this time
Packets go through the shortest path between node 0 and node 5
When it fails, the packets go through another better way among the remaining ways.

When this is also fails then another one is selected.

2. Multicast Routing

In multicast there may be several multicast groups of members. The groups may
overlap. There are three types of multicast:
2.1. Dense Mode

For large number of multicast users, trees are constructed for each pair of source and
its multicast group construction of tree requires broadcasting to all nodes.
2.2. Centralized

For small number of users, routing can be handled by a single shared tree. A shared
tree is built for the group rooted at a point called RP. Packets from senders are unicast to RP
and multicast from RP to the group is done according to shortest path.
2.3. Shared Tree

Shared Tree is a simplified version of centralized routing protocol to have a multicast


routing
$ns multicast
To specify dense mode multicast
$ns mrtproto DM

To specify centralized multicast


set cen [$ns mrtproto CtrMcast]

To have a shared tree mode


$ns mrtproto ST

The other thing to do is allocating a multicast address:


set group [Node allocaddr]

Now define an agent and as a multicast source for the group


$udp1 set dst_addr_ $group
$udp1 set dst_port_ 0

Create a receiver agent


set rcvr [new Agent/LossMonitor]

Now specify which nodes join the group and when they want to join the group
$ns at 0.0 "$n1 join-group $rcvr $group"
$ns at 0.1 "$n2 join-group $rcvr $group"

You can make a node leave the group at a time


$ns at 1.6 "$n2 leave-group $rcvr $group"

example: dense mode multicasting


set ns [new Simulator]
$ns multicast

set f [open out.tr w]


$ns trace-all $f
$ns namtrace-all [open out.nam w]
$ns color 1 red

# the nam colors for the prune packets


$ns color 30 purple

# the nam colors for the graft packets


$ns color 31 green

# allocate a multicast address;


set group [Node allocaddr]

# nod is the number of nodes


set nod 11
# create multicast capable nodes;
for {set i 1} {$i <= $nod} {incr i} {
set n($i) [$ns node]
}

#Create links between the nodes


$ns duplex-link $n(1) $n(2) 0.3Mb 10ms DropTail
$ns duplex-link $n(1) $n(3) 0.3Mb 10ms DropTail
$ns duplex-link $n(1) $n(4) 0.3Mb 10ms DropTail
$ns duplex-link $n(2) $n(5) 0.3Mb 10ms DropTail
$ns duplex-link $n(4) $n(7) 0.3Mb 10ms DropTail
$ns duplex-link $n(4) $n(5) 0.3Mb 10ms DropTail
$ns duplex-link $n(3) $n(6) 0.3Mb 10ms DropTail
$ns duplex-link $n(5) $n(8) 0.3Mb 10ms DropTail
$ns duplex-link $n(6) $n(7) 0.3Mb 10ms DropTail
$ns duplex-link $n(6) $n(9) 0.3Mb 10ms DropTail
$ns duplex-link $n(7) $n(10) 0.3Mb 10ms DropTail
$ns duplex-link $n(7) $n(8) 0.3Mb 10ms DropTail
$ns duplex-link $n(10) $n(9) 0.3Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 0.3Mb 10ms DropTail
$ns duplex-link $n(8) $n(11) 0.3Mb 10ms DropTail

# configure multicast protocol;


set mproto DM

# all nodes will contain multicast protocol agents;


set mrthandle [$ns mrtproto $mproto]
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set src1 [new Application/Traffic/CBR]
$src1 attach-agent $udp1
$udp1 set dst_addr_ $group
$udp1 set dst_port_ 0

# create receiver agents


set rcvr [new Agent/LossMonitor]

# joining and leaving the group;


$ns at 0.0 "$n(1) join-group $rcvr $group"
$ns at 0.0 "$n(1) color #ff000000ff00"
$ns at 0.0 "$n(3) join-group $rcvr $group"
$ns at 0.0 "$n(3) color #ff000000ff00"
$ns at 0.0 "$n(6) join-group $rcvr $group"
$ns at 0.0 "$n(6) color #ff000000ff00"
$ns at 0.0 "$n(9) join-group $rcvr $group"
$ns at 0.0 "$n(9) color #ff000000ff00"
$ns at 0.0 "$n(4) join-group $rcvr $group"
$ns at 0.0 "$n(4) color #ff000000ff00"
$ns at 0.0 "$n(2) join-group $rcvr $group"
$ns at 0.0 "$n(2) color #ff000000ff00"
$ns at 0.3 "$n(5) join-group $rcvr $group"
$ns at 0.3 "$n(5) color #ff000000ff00"
$ns at 0.5 "$n(7) join-group $rcvr $group"
$ns at 0.5 "$n(7) color #ff000000ff00"
$ns at 0.6 "$n(9) leave-group $rcvr $group"
$ns at 0.6 "$n(9) color black"
$ns at 0.8 "$n(2) leave-group $rcvr $group"
$ns at 0.8 "$n(2) color black"
$ns at 1.0 "$n(6) leave-group $rcvr $group"
$ns at 1.0 "$n(6) color black "
$ns at 1.2 "$n(10) join-group $rcvr $group"
$ns at 1.2 "$n(10) color #ff000000ff00"
$ns at 1.5 "$n(11) join-group $rcvr $group"
$ns at 1.5 "$n(11) color #ff000000ff00"
$ns at 1.7 "$n(4) leave-group $rcvr $group"
$ns at 1.7 "$n(4) color black"
$ns at 1.9 "$n(3) leave-group $rcvr $group"
$ns at 1.9 "$n(3) color black"
$ns at 0.1 "$src1 start"
$ns at 2.0 "finish"
proc finish {} {
global ns
$ns flush-trace
exec nam out.nam &
exit 0
}
$ns run

After running the simulation, flooding occurs periodically to detect the nodes
connected to the group. The period time is given in a variable called pruneTimeout.In
addition to data packets you can see there are two other types of packets. The “prune”
packets(their color is purple) And the “graft” packets (their color is green).

Whenever a node that do not want to join the group, receives a packet from another
node addressed to that group, it sends a “prune” packet to that node says “don’t send me any
more packets, I am not a member of the group”.

Whenever a node wants to join a group it sends a “graft “on its links to say “I want to
be a member of the group”.
The nodes which are members of the group are in pink color and n0 is the one which
multicast to the group.

Flooding and prune packets


Node 4 sends a graft packet to join the group

Where to Find More

http://www.isi.edu/nsnam/ns/tutorial/
Simple tutorial written by Marc Greis.

http://nile.wpi.edu/NS/
Useful document “NS by Example”

http://www.isi.edu/nsnam/ns/
The Network Simulator - ns-2 page: this page contains some useful links

http://www.isi.edu/nsnam/nam/
This page contains links for NAM

http://www.isi.edu/nsnam/ns/ns-documentation.html
The link to the main documentation of NS (The ns Manual formerly known as ns Notes and
Documentation)

You might also like