NS Tutorial
NS Tutorial
Introduction
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
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.
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
NS is an OTcl interpreter. OTcl looks like other programming languages. Here is the
short explanation of OTcl:
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
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_“
}
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.
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.
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.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
Defining Links
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.
The buffer capacity of the queue related to each link can be determined
$ns queue-limit $n0 $n2 30
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
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]
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.
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]
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.
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
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_]
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”
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
#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
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.
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.
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
# 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 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
# Connect agents.
$ns connect $agent(2) $agent(4)
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
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
If NS wants to trace a link, some trace objects would be added to the model. These are
(EnqT, Deqt, DrpT, recvT)
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.
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.
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');
Now you have all the columns in vectors that can be processed or plotted.
More Things to Simulate
Here is an example
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:
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
}
Routing
1. Unicast Routing
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.
Set the cost of link between these two nodes to 2. Route computed bases on your
specified costs
It’s like static routing except that it re computes the route whenever there is a change
in topology
$ns rtproto session
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
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
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"
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.
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)