You are on page 1of 47

EXPERIMENT 1

AIM: Introduction to the Network Simulator NS-2/ NS-3, Omnet++, and its
installation Process.
Solution: NS-2 is a discrete event Network simulator program, developed at the University of
California, NS2 is an open-source discreteevent simulator used by the research community for
research in networks. It includes many network objects such as protocols, applications, and
traffic source behaviour. NS is a part of the software of the VNIT project that is supported by
DARPA since 1995. It has support for both wired and wireless networks and can simulate several
network protocols such as TCP, UDP, multicast routing, etc.
Defining the different agents and their applications like TCP, FTP overTCP, UDP, CBR, and CBR
over UDP, etc., and identifying and solving the installation error of NS2.
A network simulator is a discrete event packet-level simulator. The network simulator covers a
very large number of applications of different kinds of protocols of different network types
consisting of different network elements and traffic models. A network simulator is a package of
tools that simulates behaviour of networks such as creating network topologies, logging events
that happen under any load, analysing theevents, and understanding the network. Well, the main
aim of our first experiment is to learn how to use a network simulator and get acquainted with the
simulated objects and understand the operations of network simulation we also need to analyse
the behaviour of the simulation object using network simulation.
Objectives: It helps to increase the efficiency of the simulation. It is used to provide details of
the protocols and their operation. It is used to reducepacket and event processing time. OTcl
helps in the following way: With the help of OTcl we can describe different network topologies It
helps usto specify the protocols and their applications. It allows fast development Tcl is
compatible with many platforms, and it is flexible forintegration Tcl is very easy to use and it is
available in free OMNeT++ is an extensible, modular, component-based C++ simulation library
and framework, primarily for building network simulators. "Network" is meant in a broader
sense that includes wired and wireless communication networks, on-chip networks, queueing
networks, and so on. Domain-specific functionality such as support for sensor networks, wireless
ad-hoc networks, Internet protocols, performance modeling, photonic networks, etc., is provided
by model frameworks, developed as independent projects. OMNeT++ offers an Eclipse-based
IDE, a graphical runtime environment, and a host of other tools. There are extensions for real-
time simulation, network emulation, database integration, SystemC integration, and several other
functions. OMNeT++provides a component architecture for models. Components (modules) are
programmed in C++, then assembled into larger components and models using a high-level
language (NED). The reusability of models comes for free. OMNeT++ has extensive GUI
support, and due to its modular architecture, the simulation kernel (and models) can be
embedded easily into your applications.

1
1b) Introduction to Discrete Event Simulation
Solution: There are various network simulators available for networkingsimulation.
The general process of creating a simulation can be divided into several steps:
➢ Topology definition: to ease the creation of basic facilities and define their
interrelationships, ns-3 has a system of containers and helpers thatfacilitates this process.
➢ Model development: models are added to the simulation (for example,UDP, IPv4, point-to-
point devices and links, and applications); most of thetime this is done using helpers.
➢ Node and link configuration: models set their default values (for example, the size of
packets sent by an application or MTU of a point-to-point link); most of the time this is
done using the attributesystem.
➢ Execution: simulation facilities generate events, and data requested bythe user is logged.
➢ Performance analysis: after the simulation is finished and data isavailable as a time-
stamped event trace. This data can then be statistically analyzed with tools like R to draw
conclusions.
➢ Graphical Visualization: raw or processed data collected in a simulation can be graphed
using tools like Gnuplot, matplotlib, or XGRAPH.

1c) Downloading and installing NS-2


The NS-2 simulator has long been a widely used simulator for researchand education on the
Internet and other network Systems. Network simulations for ns-2 are composed of C++ code,
which is used to modelthe behavior of the simulation nodes, and OTcl scripts that control the
simulation and specify further aspects, for instance, the network topology.
Problems with Ns 2: There are a lot many problems found with NS2,such as it has a Split object
model (OTcl and C++) and the use of Tcl.
Step 1: Setting up the Prerequisites
1. First of all, download Network Simulator (NS-2.35) from the ISI.EDUwebsite.
2 [Optional]. Now we must update the Ubuntu with its latest components. Open up a terminal and
run these commands:
➢ sudo apt-get update.
➢ sudo apt-get dist-upgrade 3 sudo apt-get update
➢ Before installing the NS we have to install some essential packagesrequired by the NS. So
run the following commands:

➢ sudo apt-get install build-essential autoconf automake


➢ sudo apt-getinstall tcl8.5-dev tk8.5-dev
➢ sudo apt-get install perl xgraph libxt-dev libx11-dev libxmu-dev

2
Step 2: Extract and Install NS
Extract the downloaded NS package either using the right click context menu "Extract here" or
using the following commands from aterminal:
1 cd /home/user_name/Documents 2 tar -xvzf ns-allinone-2.35.tar.gz
After extracting the "ns-allinone-2.35" folder, open up the file
"/ns-allinone-2.35/ns- 2.35/linkstate/ls.h" in an editor. And make somechanges in the ls.h file else
it will show an error while installing the NS.Go to the line 137 and replace the erase with this-
>erase and save the file.
Now its time to finally install the NS. Open up a terminal and move tothe directory where we
have extracted the package,
cd /home/user_name/Documents/ns-allinone-2.35
sudo ./install
It will take around 15 minutes so have patience.

Step 3: Set the Environment Variables


There are some environment variables that need to be added to yourprofile. This can be done by
editing the .bashrc file. Open a new terminal and open the file using:
1 sudo gedit .bashrc
Add the following lines AT THE END of the file. Be sure to change"/path_to" to the path of
where you have extracted the NS (e.g.'/home/user_name/Documents').# LD_LIBRARY_PATH
OTCL_LIB=/path_to/ns-allinone-2.35/otcl-1.14/
NS2_LIB=/path_to/ns-allinone-2.35/lib/ USR_Local_LIB=/usr/local/lib/ export
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$USR_Loc
al_ LIB
# TCL_LIBRARY
TCL_LIB=/path_to/ns-allinone-2.35/tcl8.5.10/library/ USR_LIB=/usr/lib/export
TCL_LIBRARY=$TCL_LIBRARY:$TCL_LIB:$USR_LIB # PATH
XGRAPH=/path_to/ns-allinone-2.35/xgraph-12.2/:/path_to/ns-allinone- 2.35/bin/:/path_to/ns-
allinone-2.35/tcl8.5.10/unix/:/path_to/ns-allinone- 2.35/tk8.5.10/unix/
NS=/path_to/ns-allinone-2.35/ns-2.35/ NAM=/path_to/ns-allinone-2.35/nam-1.15/ export
PATH=$PATH:$XGRAPH:$NS:$NAM
Save the file and restart the system, alternatively, we can just reload the

3
.bashrc as: 1 source ~/.bashrc
now run ns from a terminal window by executing: ns If we receive the"%" sign, it means that NS
is running.

1d) Downloading and installing NS-3


The NS-3 Project started around mid-2006 add is still under heavy development NS-3 is a
discrete event network simulator written in C++with an optional Python scripting API. It allows
researchers to study Internet protocols and large-scale systems in a controlled environment.NS-3
is a new simulator (not backward-compatible with NS-2). It is a free, open-source software
project organized around research community development and maintenance. NS-3 is not an
extension ofns-2. It is a new simulator, written from scratch. The project will continue to
maintain ns-2 while NS-3 is being built and will study transition and integration mechanisms.
NS-3 is a free software simulation platform that aims at network technology and whose source
code is open. Researchers can use it easily to develop network technology.NS-3 contains an
abundance of modules, almost relating toall the aspects of network technology.
A tarball is a particular format of software archive where multiple files are bundled together, and
the archive possibly compressed. ns-3 software releases are provided via a downloadable tarball.
The processfor downloading ns-3 via tarball is simple; you just have to pick a release, download
it, and decompress it.

1e) Difference between NS-2 and NS-3


The most visible difference between NS-2 and NS-3 is the choice of scripting language. Ns-2 is
scripted in OTcl and results of simulations canbe visualized using the Network Animator
nam[10]. It is not possible to run a simulation in ns-2 purely from C++ (i.e., as a main () program
without any OTcl). Moreover, some components of ns-2 are written in C++ and others in OTcl.
In NS-3, the simulator is written entirely in C++, with optional Python bindings. User code
protocols and scenarios also in C++ . Simulation scripts can therefore be written in C++ or in
Python. Furthermore, NS-3 generates pcap packet trace files; other utilities such as Wireshark can
be used to analyze traces as well. NS-3 does not have all of the models that ns-2 currently has,
but on the other hand, NS-3 does have new capabilities. Some models from ns-2 have already
been ported from ns-2 to ns-3.

4
5
EXPERIMENT 2a

AIM: Write a program to generate wired topology.

CODE
#Execute NAM on the trace file exec nam out.nam &#Create a simulator object set ns
[new Simulator]
#Open the NAM trace file set nf [open out.nam w]
$ns namtrace-all $nfproc finish {} { global ns nf
$ns flush-trace
#Close the NAM trace file close $nfexit 0 }
#Create four nodes set n0 [$ns node] set n1 [$ns node]set n2 [$ns node] set n3 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 2Mb 10ms DropTail
$ns duplex-link $n3 $n0 2Mb 10ms DropTail#Give node position (for NAM)
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n0 $n3 orient down
$ns duplex-link-op $n3 $n2 orient right
$ns duplex-link-op $n1 $n2 orient down
$ns at 5.0 "finish"
$ns run

6
OUTPUT:

7
EXPERIMENT 2b

AIM: Write a program to generate a wired topology with traffic.

CODE
set ns [new Simulator] set nf [open out.nam w]
$ns namtrace-all $nf proc finish {} {global ns nf f
$ns flush-trace close $nf exec nam out.nam & exit 0}
set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]
$ns duplex-link $n0 $n1 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 2Mb 10ms DropTail
$ns duplex-link $n3 $n0 2Mb 10ms DropTail
$ns queue-limit $n2 $n3 10
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n0 $n3 orient down
$ns duplex-link-op $n3 $n2 orient right
$ns duplex-link-op $n1 $n2 orient down
$ns duplex-link-op $n2 $n3 queuePos 0.5
#Setup a UDP connection set udp [new Agent/UDP]
$ns attach-agent $n0 $udp set null [new Agent/Null]
$ns attach-agent $n2 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection set cbr [newApplication/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000

8
$cbr set rate_ 1mb
$cbr set random_ false
#Schedule events for the CBR and FTP agents
$ns at 0.1 "$cbr start" #$ns at 1.0 "$ftp start" #$ns at 6.0 "$ftp stop"
$ns at 4.5 "$cbr stop"
#Detach tcp and sink agents (not really necessary)
#$ns at 6.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"#Call the finish
procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Print CBR packet size and interval
puts "CBR packet size = [$cbr set packet_size_]" puts "CBR interval =[$cbr set interval_]"
#Run the simulation
$ns run

9
OUTPUT:

10
EXPERIMENT 3

AIM: Write a program to create a more complex topology & simulate anode failure.

CODE
set ns [new Simulator]

$ns rtproto DV

set nf [open out.nam w] set f [open out.tr w]

$ns namtrace-all $nf

$ns trace-all $f

proc finish {} { global ns nf f

$ns flush-trace close $nfclose $f

exec nam -a out.nam & exit 0}

for {set i 0} {$i<7} {incr i} {set n($i) [$ns node]}

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

$ns duplex-link $n($i) $n([expr ($i+1)%7]) 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 $udp0set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)

11
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run

12
EXPERIMENT 4

AIM: Write a program to create a wireless network simulation using ns2

CODE
#Filename: exp4.tcl
#TCL – Tool Command Language # Simulator Instance Creationset ns [new Simulator]
#Fixing the co-ordinate of simulation area set val(x) 500set val(y) 500
# Define options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagationmodel set val(netif)
Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type setval(ll) LL ;# link layer
type
set val(ant) Antenna/OmniAntenna ;# antenna model set val(ifqlen)50 ;# max packet in ifq
set val(nn) 2 ;# number of mobilenodes set val(rp) AODV ;# routingprotocol
set val(x) 500 ;# X dimension of topography set val(y) 400 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end #
set up topography object
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
#Nam File Creation nam – network animator set namfile openexp3.namw
#Tracing all the events and configuration
$ns namtrace-all-wireless $namfile $val(x) $val(y) #Trace Filecreation
set tracefile [open exp3.tr w]
#Tracing all the events and configuration
$ns trace-all $tracefile

13
# general operational descriptor- storing the hop details in thenetwork create-god $val(nn)
# configure the nodes
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \

-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON # Node Creationset node1 [$ns node]
# Initial color of the node
$node1 color black
#Location fixing for a single node
$node1 set X_ 200
$node1 set Y_ 100
$node1 set Z_ 0
set node2 [$ns node]
$node2 color black
$node2 set X_ 200
$node2 set Y_ 300
$node2 set Z_ 0

14
# Label and coloring
$ns at 0.1 "$node1 color blue"
$ns at 0.1 "$node2 color blue"
$ns at 0.1 "$node1 label Node1"
$ns at 0.1 "$node2 label Node2" #Size of the node
$ns initial_node_pos $node1 30
$ns initial_node_pos $node2 30 # ending nam and the simulation
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "stop" #Stopping the scheduler
$ns at 10.01 "puts \"end simulation\" ; $ns halt" #$ns at 10.01 "$nshalt"
proc stop {} {
global namfile tracefile ns
$ns flush-trace close $namfile
close $tracefile #executing nam file exec nam exp3.nam &
}
#Starting scheduler
$ns run #############################################################
Execution: ns exp3.tcl

15
OUTPUT:

16
EXPERIMENT 5

AIM: To perform Wireless network simulation using setdest and cbrgen.

THEORY:-
Node Movement and Topology Generation
Instead of specifying and controlling each nodes' position and movementpattern, we use a
CMU tool "setdest" to generate large number of nodes and their movements. The tool
uses a random waypoint model.
Setdest
Setdest tool is used to generate the positions of nodes and their movingspeed and moving
directions.
The syntax is: setdest -v 1 -n $numnodes -p $pt -M $maxspeed -t
$simtime -x $maxx -y $maxyfor example: setdest -v 1 -n 50 -p 0 -M 20 -t900 -x 1500 -y
300
will generate a 1500*300 topology with 50 nodes random distributedlabeled by a XY(Z)
coordinates. ( Note that, there is a bug in the README file, which gives a wrong option
for specifying the speed, weshould use "-M" instead of "-s" ).
setdest is used to
• Create hops between the nodes using the GOD (General OperationsDirector)
object.
• Create mobility for nodes in terms of metres/second
• Move from one place to another place using setdest (Set destination)with speed
• To execute, use ./setdest

cbrgen
Random traffic connections of TCP and CBR can be setup between mobilenodes using a
traffic- scenario generator script. This traffic generator script is available under ~ns/indep-
utils/cmu- scen-gen and iscalled cbrgen.tcl. It can be used to create CBR and TCP traffics
connections between wireless mobilenodes. In order to create a
traffic-connection file, we need to define the type of traffic connection(CBR or TCP), the
number of nodes and maximum number of connections to be setup between them, a
random seed and incase of CBR connections, a rate whose inverse value is used to

17
compute the interval time between the CBR pkts. So the command line looks like the
following:
ns cbrgen.tcl [-type cbr|tcp] [-nn nodes] [-seed seed] [-mcconnections][- rate rate]
>output.tcl
cbrgen.tcl
• create connections between the nodes , one can specify the maximum number of
connections to be made for all the nodes in thenetwork
• to create the type of agents between the nodes (cbr or tcp)
• rate at which the packets are transmitted.
• to execute this, ns cbrgen.tcl

18
SETDEST EXAMPLE

CBRGN EXAMPLE

19
EXPERIMENT 6

AIM: To simulate a wireless topology using setdest and clrgen

CODE
#Tcl script for simulating Blackhole node in Manets (Ns2)#Aodv.tel
# Define options
set val(chan) Channel/WirelessChannel set val(prop)
Propagation/TwoRayGround set val(netif) Phy/WirelessPhyset val(mac)
set val(ifq) Queue/DropTail/PriQueue
;#Channel Type
;# radio-propagation model
;# network interface type
;# MAC type
;# interface queue typeset val(II)
set val(ant) Antenna/OmniAntennaset val(ifqlen)
set val(nn)
;# link layer type
;# antenna model
;# max packet in ifq
;# total number of mobilenodesset val(rp) set val(x) set val(y)
set val(cstop) set val(stop) set val(cp) set val(cc) set val(seed)AODV
”./set50"
”./cbr50"1.0
;# routing protocol
;# X dimension of topography
;# Y dimension of topography
;# time of connections end

20
;# time of simulation end
;#Connection Pattern
;#CBR Connections
# Initialize Global Variables set ns [new Simulator]
Mac/802 11
#$ns_ use-newtrace
set tracefd [open aodv50.tr w]
$ns trace-all $tracefd
set namtrace [open aodv50.nam w]
$ns namtrace-all-wireless $namtrace $val(x) $val(y)
# set up topography object
set topo [new Topography]
$topo load flatgrid $val(x) $val(y)# Create God
create-god $val(nn)
# Create channel #1 and #2 set chan 1 [new $val(chan)] set chan 2[new $val(chan)]
# configure node, please note the change below.
$ns node-config -adhocRouting $val(rp) \
—llType $val(II) }
—macType $val(mac) \
—ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
—propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-agentTrace ON \
—routerTrace OFF \
—macTrace ON \

21
-movementTrace ON \
-channel $chan 1
# Creating mobile AODV nodes for simulation puts ”Creating Nodes…”
for {set i 0} {$i < $val(nn)} {incr i} {set node ($i) [$ns node]
$node ($i) random-motion 0 ;#disable random motion
# Adding connection pattern which is created using setdest,parameters shown below
#Aome/ashish/Documents/ns-allinone-2.35/ns-2.35/indep-utils/cmu-scen-
gen/setdest/setdest -n 20 -p 1.0 -M 20.0 -t
500 -x 750 -y 750 > mobsin
puts ”Loading random connection pattern..."set god [God instance]
source $val(cp)
# ################### CBRGEN GENERATE SAME CODE###########
# CBR Connections generated by cbrgen source $val(cc)# Define initial node position
for {set i 0} {$i < $val(nn) } {incr i) {
$ns initial node pos $node ($i) 30
# Tell all nodes when the simulation endsfor {set i 0} {$i < $val(nn) } {incr i) {
$ns at $val(stop).000000001 "$node ($i) reset";
#$ns at $opt(stop).00000001 "puts \"NS EXITING...\" ; $ns halt"
puts $tracefd "M 0.0 time $val(stop) nn $val(nn) x $val(x) y $val(y)rp $val(rp)" #puts
$tracefd "M 0.0 nn $opt(nn) x $opt(x) y $opt(y) rp
$opt(rp)"
puts $tracefd "M 0.0 sc $val(cc) cp $val(cp) seed $val(seed)"puts $tracefd "M 0.0 prop
$val(prop) ant $val(ant)"
# Ending nam and simulation
$ns at $val(stop) "finish"
$ns at $val(stop).0 "$ns trace-annotate \”Simulation has ended\”"
$ns at $val(stop).00000001 "puts \"NS EXITING...\" ; $ns halt"proc finish { } {
global ns tracefd namtrace
$ns flush-trace close $tracefd close $namtrace#exec nam aodv20.nam &

22
exit 0
puts "Starting Simulation..."
$ns run
#Tcl script for simulating Blackhole node in Manets (Ns2)#dsdv.tel
# Define options
set val(chan) Channel/WirelessChannel set val(prop) Propagation/TwoRayGround
;#Channel Type
;# radio-propagation model set val(netif) Phy/WirelessPhyset val(mac)
set val(ifq) Queue/DropTail/PriQueueset val(II)
set val(ant) Antenna/OmniAntenna set val(ifqlen)set val(nn)
;# network interface type
;# MAC type
;# interface queue type
;# link layer type
;# antenna model
;# max packet in ifq
;# total number of mobilenodesset val(rp) set val(x) set val(y)
set val(cstop) set val(stop) set val(cp) set val(cc) set val(seed)DSDV
"./set50"
"./cbr50"1.0
;# routing protocol
;# X dimension of topography
;# Y dimension of topography
;# time of connections end
;# time of simulation end
;#Connection Pattern
;#CBR Connections
# Initialize Global Variables set ns [new Simulator] #$nsuse-newtrace

23
set tracefd [open dsdv50.a w]
$ns trace-all $tracefd
set namtrace [open dsdv50.nam w]
$ns namtrace-all-wireless $namtrace $val(x) $val(y)# set up topography object
set topo [new Topography]Mac/802 11
$topo load flatgrid $val(x) $val(y)# Create God
create-god $val(nn)
# Create channel #1 and #2 set chan 1 [new $val(chan)] set chan 2[new $val(chan)]
# configure node, please note the change below.
$ns node-config -adhocRouting $val(rp) \
—llType $val(II) \
—macType $val(mac) \
—ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
—propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-agentTrace ON \
—routerTrace OFF \
—macTrace ON \
-movementTrace ON \
-channel $chan 1
# Creating mobile AODV nodes for simulationputs ”Creating nodes..."
for {set i 0} {$i < $val(nn) } {incr i} { set node ($i) [$ns node]
$node ($i) random-motion 0 ;#disable random motion
# Adding connection pattern which is created using setdest,parameters shown below
#Aome/ashish/Documents/ns-allinone-2.35/ns-2.35/indep-utils/emu-seen-
gen/setdest/setdest -n 20 -p 1.0 -M 20.0 -t
24
500 -x 750 -y 750 > mobsin
puts "Loading random connection pattern..."
set god [God instance]source $val(cp)
# ################### CBRGEN GENERATE SAME CODE###########
# CBR Connections generated by cbrgen source $val(cc)# Define initial node position
for {set i 0} {$i < $val(nn) } {incr i} {
$ns initial node pos $node ($i) 30
# Tell all nodes when the simulation endsfor {set i 0} {$i < $val(nn) } {incr i) {
$ns at $val(stop).000000001 "$node ($i) reset";
#$ns at $opt(stop).00000001 "puts \"NS EXITING...\" ; $ns halt" puts $tracefd "M 0.0
time $val(stop) nn $val(nn) x $val(x) y $val(y)
rp $val(rp)"
#puts $tracefd "M 0.0 nn $opt(nn) x $opt(x) y $opt(y) rp $opt(rp)"puts $tracefd "M 0.0 sc
$val(cc) cp $val(cp) seed $val(seed)"
puts $tracefd "M 0.0 prop $val(prop) ant $val(ant)"# Ending nam and simulation
$ns at $val(stop) "finish"
$ns at $val(stop).0 "$ns trace-annotate \”Simulation has ended\”"
$ns at $val(stop).00000001 "puts \"NS EXITING...\" ; $ns halt"proc finish { } {
global ns tracefd namtrace
$ns flush-trace close $tracefd close $namtrace#exec nam aodv20.nam & exit 0
puts "Starting Simulation..."
$ns run

25
TABLE

SETDEST

CBRGEN

OUTPUT

26
27
EXPERIMENT 7

AIM: Show and analyze the old legacy all results wired & wireless and the New
Trace Format.

CODE:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Event Time From
To PktPkt
Flags FlgSrc
Dst Seq. Pkt NodeNodeType Size Id AddrAddrNo. id
+ 0.2 0 1 Tcp 40 ------- 1 0.0 1.0 0 0 - 0.2 0 1 Tcp 40 1 0.0 1.0 0 0 r
0.210032
0 1 Tcp 40 ------- 1 0.0 1.0 0 0 + 0.210032 1 0 Ack 40 1 1.0 0.0 0 1 -
0.210032
1 0 Ack 40 ------- 1 1.0 0.0 0 1 r 0.220064 1 0 Ack 40 ------- 1 1.0 0.0 0 1 +
0.220064
0 1 Tcp 1040 ------- 1 0.0 1.0 1 2 - 0.220064 0 1 Tcp 1040 1 0.0 1.0
12+
0.220064 0 1 Tcp 1040 ------- 1 0.0 1.0 2 3 - 0.220896 0 1 Tcp 1040 -------
1 0.0 1.0
2 3 r 0.230896 0 1 Tcp 1040 1 0.0 1.0 1 2
The first field is the event type. It is given by one of four possiblesymbols r, +, —& d
which correspond respectively to receive, enqueued, dequeued anddropped.
The second field gives the time at which the event occurs.
Gives the input node of the link at which the event occurs. 4 Givesthe output node of the
link at which the event occurs.
Gives the packet size.
Some flags .

28
This is the flow id (fid) of IPv6 that a user can set for each flow at theinput OTcl script.
One can further use this field for analysis purposes; it is also used when specifying stream
color for the NAM display.

This is the source address given in the form of “node.port”.


This is the destination address, given in the same form.
This is the network layer protocol’s packet sequence number. Eventhough UDP
implementations in a real network do not use sequence number, ns keeps track of UDP
packet sequence number for analysis purposes.
The last field shows the unique id of the packet.
Event type: In the traces above, the first field describes the type ofevent taking place at the
node and can be one of the four types:
s send
r received drop
f forward
General tag: The second field starting with "-t" may stand for time orglobal setting -t time
-t * (global setting)
Node property tags: This field denotes the node properties like node-id,the level at which
tracing is being done like agent, router or MAC. The tags start with a leading "-N" and
are listed as below:
-Ni: node id
-Nx: node's x-coordinate
-Ny: node's y-coordinate
-Nz: node's z-coordinate
-Ne: node energy level
-Nl: trace level, such as AGT, RTR, MAC
-Nw: reason for the event. The different reasons for dropping a packetare given below:
"END" DROP_END_OF_SIMULATION "COL" DROP_MAC_COLLISION"DUP"
DROP_MAC_DUPLICATE "ERR" DROP_MAC_PACKET_ERROR"RET"
DROP_MAC_RETRY_COUNT_EXCEEDED
"STA" DROP_MAC_INVALID_STATE"BSY" DROP_MAC_BUSY

29
"NRTE” DROP_RTR_NO_ROUTE i.e no route is available.
"LOOP" DROP_RTR_ROUTE_LOOP i.e there is a routing loop "TTL"DROP_RTR_TTL
i.e TTL has reached zero.
"TOUT" DROP_RTR_QTIMEOUT i.e packet has expired."CBK"
DROP_RTR_MAC_CALLBACK
"IFQ" DROP_IFQ_QFULL i.e no buffer space in IFQ."ARP" DROP_IFQ_ARP_FULL
i.e dropped by ARP
"OUT" DROP_OUTSIDE_SUBNET i.e dropped by base stations onreceiving routing
updates from nodes outside its domain.
Packet information at IP level: The tags for this field start with a leading"-I" and are listed
along with their explanations as following:
-Is: source address.source port number
-Id: dest address.dest port number
-It: packet type
-Il: packet size
-If: flow id
-Ii: unique id
-Iv: ttl value
Next hop info: This field provides next hop info and the tag starts with aleading "-H". -Hs:
id for this node
-Hd: id for next hop towards the destination.
Packet info at MAC level: This field gives MAC layer information andstarts with a leading
"-M" as shown below:
-Ma: duration
-Md: dst's ethernet address
-Ms: src's ethernet address
-Mt: ethernet type
Packet info at Application level: The packet information at application level consists of
the type of application like ARP, TCP, the type of ad-hoc routing protocol like DSDV,
DSR, AODV etc being traced. This field consists of a leading "-P" and list of tags for
different application is listedas below:
-P arp: Address Resolution Protocol. Details for ARP are given by these

30
tags: -Po: ARP Request/Reply
-Pm: src mac address
-Ps: src address
-Pa: dst mac address
-Pd: dst address
-P dsr: This denotes the adhoc routing protocol called Dynamic sourcerouting.
Information on DSR is represented by the following tags:
-Pn: Number of nodes traversed
-Pq: routing request flag
-Pi: route request sequence number
-Pp: routing reply flag
-Pl: reply length
-Pe: src of srcrouting->dst of the source routing
-Pw: error report flag
-Pm: number of errors
-Pc: report to whom
-Pb: link error from linka->linkb
-P cbr : Constant bit rate. Information about the CBR application isrepresented by the
following tags:
-Pi: sequence number
-Pf: how many times this pkt was forwarded
-Po: optimal number of forwards
-P tcp: Information about TCP flow is given by the following subtags:
-Ps: seq number
-Pa: ack number
-Pf: how many times this pkt was forwarded
-Po: optimal number of forwards

31
EXPERIMENT 8

AIM: Calculate throughput, average delay, normalized routing load and PDR of
the network using AWK script.

THEORY:
AWK, one of the most prominent text-processing utility on GNU/Linux. It is very
powerful and uses simple programming language. It can solve complex text processing
tasks with a few lines of code.
THROUGHPUT
When used in the context of communication networks, such as Ethernetor packet radio,
throughput or network throughput is the rate of successful message delivery over a
communication channel. The data these messages belong to may be delivered over a
physical or logical link, or it can pass through a certain network node. Throughput is
usually measured in bits per second (bit/s or bps), and sometimes in data packets per
second (p/s or pps) or data packets per time slot.

Formula: (Received_Size/(Stop_Time-Start_Time))*8/(10^3)
AWK script to calculate Throughput
BEGIN {
recvdSize = 0
startTime = 400
stopTime = 0
}
{
event = $1 time = $2 node_id = $3 pkt_size = $8 level = $4# Store start time
if (level == "AGT" && event == "s" && pkt_size >= 512) { if (time <startTime)
{
startTime = time
}
}

32
# Update total received packets' size and store packets arrival time if(level == "AGT"
&& event == "r" && pkt_size >= 512) {
if (time > stopTime) { stopTime = time
}
# Rip off the header hdr_size = pkt_size % 512 pkt_size -= hdr_size# Store received
packet's size400 recvdSize += pkt_size
}
} END {
printf("Average Throughput[kbps] = %.2f\t\t
StartTime=%.2f\tStopTime=%.2f\n",(recvdSize/(stopTime-startTime))*8
/(1000),startTime,stopTime)}
Average Delay
Network delay is an important design and performance characteristic ofa computer
network or telecommunications network. The delay of a network specifies how long it
takes for a bit of data to travel across the network from one node or endpoint to another.
It is typically measuredin multiples or fractions of seconds. Delay may differ slightly,
dependingon the location of the specific pair of communicating nodes. Although users
only care about the total delay of a network, engineers need to perform precise
measurements. Thus, engineers usually report both themaximum and average delay.
Formula:Ʃ(i 0->N){(recvTime(i) - sendTime(i))/ N}*10^3
AWK script to calculate Average Delay
BEGIN{
}
{
if ($2 != "-t") {
event = $1 time = $2
if (event == "+" || event == "-") node_id = $3 if (event == "r" || event =="D") node_id = $3
flow_id = $9pkt_id = $6

pkt_size = $8 level = "AGT"

if (level == "AGT" && sendTime[pkt_id] == 0 && (event == "+" || event

== "s") ) { if (time < startTime) {startTime = time

33
}

sendTime[pkt_id] = time

if (level == "AGT" && event == "r" ) {if (time > stopTime) {

stopTime = time

recvdSize += pkt_size recvTime[pkt_id] = time

} END{

delay = avg_delay = recvdNum = 0 for (i in recvTime) {if (sendTime[i] == 0) {

printf("\nError in delay.awk: receiving a packet that wasn't sent %g\n",i)

delay += recvTime[i] - sendTime[i] recvdNum ++


}
if (recvdNum != 0) {
avg_delay = delay / recvdNum
}
else { avg_delay = 0
}
printf(" %15s: %g\n", "avgDelay[ms] overall", avg_delay*1000)
}
Normalized Routing Load
Normalized routing load is the number of routing packets transmitted per data packet sent
to the destination. Also, each forwarded packet is counted as one transmission. This
metric is also highly correlated with the number of route changes occurred in the
simulation.
Formula:(routing_packets/received)*10^2
AWK script to calculate Normalized Routing Load
# AWK Script to calculate Normalized Routing Load #

34
# Works with AODV, DSDV, DSR and OLSR #
##########################################################
##########BEGIN{

recvd = 0;#################### to calculate total number of data packets received


rt_pkts = 0;################## to calculate total number of routing packets received
}
{
##### Check if it is a data packet
if (( $1 == "r") && ( $7 == "cbr" || $7 =="tcp" ) && ( $4=="AGT" ))recvd++;
##### Check if it is a routing packet
if (($1 == "s" || $1 == "f") && $4 == "RTR" && ($7 =="AODV" || $7
=="message" || $7 =="DSR" || $7
=="udp")) rt_pkts++;
} END{
printf("####################################################
########################### ###\n");
printf("\n");
printf(" Normalized Routing Load= %.3f\n", rt_pkts/recvd*100);
printf("\n"); printf("####################################################
########################### ###\n");

Packet Delivery Ratio


The calculation of Packet Delivery Ratio (PDR) is based on the received and generated
packets as recorded in the trace file. In general, PDR is defined as the ratio between the
received packets by the destination and the generated packets by the source. Packet
Delivery Ratio is calculated using awk script which processes the trace file and produces
the result.

AWK script to calculate PDR


BEGIN {

35
sendLine = 0;
recvLine = 0;
fowardLine = 0;
}
$0 ~/^s.* AGT/ { sendLine ++ ;
}
$0 ~/^r.* AGT/ { recvLine ++ ;
}
$0 ~/^f.* RTR/ { fowardLine ++ ;
} END {
print "\n";
printf "r RecLine:%.4f/n", (recvLine); print "\n"; printf "s
SendLine:%.4f/n", (sendLine); print "\n";
printf "r/s Ratio:%.4f/n", (recvLine/sendLine); print "\n"; printf "cbroptimal path
length=:%.4f ",(recvLine/fowardLine);
}

36
OUTPUT:

37
EXPERIMENT 9

AIM: Study x-graph in ns2.

THEORY:

XGraph
The xgraph program draws a graph on an X display given data read from either data files
or from standard input if no files are specified. It can display up to 64 independent data
sets using different colors and/or line styles for each set. It annotates the graph with a
title, axis labels, grid lines or tick marks, grid labels, and a legend. There are options to
control the appearance of most components of the graph.

Syntax: Xgraph [options] file-nameOptions are listed here


/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg <color> (Background)
This specifies the background color of the xgraph window.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf <fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
This string is centered at the top of the graph.
/-x <unit name> (XunitText)
This is the unit name for the x-axis. Its default is ―Xǁ.
/-y <unit name> (YunitText)
This is the unit name for the y-axis. Its default is ―Yǁ.
A data set consists of an ordered list of points of the form “directive X Y”. For directive
“draw”, a line will be drawn between the previous pointand the current point. Specifying a
“move” directive tells xgraph not to draw a line between the points. “draw” is the default

38
directive. The name of a data set can be specified by enclosing the name in double
quotes.
The interface used to specify the size and location of this window depends on the
window manager currently in use. Once the window has been opened, all of the data sets
will be displayed graphically with alegend in the upper right corner of the screen.
Xgraph also presents three control buttons in the upper left corner of each window:
Hardcopy, Close and about xgraph accepts a large number of options most of which can
be specified either on the command line, in the user’s .Xdefaults or .Xresources file, or in
the data files themselves. The xgraph can be installed to your linux by using the below
code on the terminal window; In Ubuntu 10.10 you can now install ns,nam and
xgraph by just a single command in the Terminal:
$ sudo apt-get install ns2 nam xgraph
You will be prompted for the user password. Enter it and watch Ubuntu
10.10 do the things for You!
The following program shows how XGraph can be used to plot thebandwidth of
two nodes connected through full duplex wired link.
Example
"NEAODV" "AODV" 200 100 100 50
400 350 300 250
600 800 400 500
800 1200 500 1000

39
OUTPUT:

40
EXPERIMENT 10

AIM: Discuss Routing Protocols (Theory+ Example):


• Distance Vector Routing
• Link state Protocol

A distance-vector routing (DVR) protocol requires that a router inform its neighbors of
topology changes periodically. Historically known as theold ARPANET routing algorithm
(or known as Bellman-Ford algorithm).

Bellman Ford Basics – Each router maintains a Distance Vector tablecontaining the
distance between itself and ALL possible destination nodes. Distances,based on a chosen
metric, are computed using information from the neighbors’ distance vectors.
Information kept by DV router -
Each router has an ID
Associated with each link connected to a router,
there is a link cost (static or dynamic).
Intermediate hops
Distance Vector Table Initialization -
Distance to itself = 0

Example – Consider 3-routers X, Y and Z as shown in figure. Eachrouter have their


routing table. Every routing table will contain distance to the destination nodes.

41
Consider router X , X will share it routing table to neighbors and neighbors will share it
routing table to it to X and distance from node Xto destination will be calculated using
bellmen- ford equation.

Dx(y) = min { C(x,v) + Dv(y)} for each node y ∈ N


As we can see that distance will be less going from X to Z when Y isintermediate node(hop)
so it will be update in routing table X.

42
Advantages of Distance Vector routing –
It is simpler to configure and maintain than link state routing.

Disadvantages of Distance Vector routing –


It is slower to converge than link state.
It is at risk from the count-to-infinity problem.
It creates more traffic than link state since a hop count change mustbe propagated to all routers
and processed on each router. Hop countupdates take place on a periodic basis, even if there
are no changes inthe network topology, so bandwidth-wasting broadcasts still occur.
For larger networks, distance vector routing results in larger routingtables than link state since
each router must know about all other routers. This can also lead to congestion on WAN links.
Link state routing is a technique in which each router shares theknowledge of its
neighbourhood with every other router in the internetwork.

Link state routing is a technique in which each router shares theknowledge of its
neighbourhood with every other router in the internetwork.
The three keys to understand the Link State Routing algorithm: Knowledge about the
neighbourhood: Instead of sending its routing table, a router sends the information about its
neighborhood only. A router broadcast its identities and cost of the directly attached links to
other routers.

Flooding: Each router sends the information to every other router on the internetwork except
its neighbors. This process is known as Flooding. Every router that receives the packet sends

43
the copies to all its neighbors. Finally, each and every router receives a copy of the same
information.
Information sharing: A router sends the information to every otherrouter only when the
change occurs in the information.
Link State Routing has two phases:
Reliable Flooding
Initial state: Each node knows the cost of its neighbors.
Final state: Each node knows the entire graph.
Route Calculation
Each node uses Dijkstra's algorithm on the graph to calculate theoptimal routes to all nodes.
The Link state routing algorithm is also known as Dijkstra's algorithmwhich is used to find the
shortest path from one node to every othernode in the network.
The Dijkstra's algorithm is an iterative, and it has the property that after kth iteration of the
algorithm, the least cost paths are well known for k iteration of the algorithm, the least cost
paths are well known for kdestination nodes.

In the above figure, source vertex is A.

Step 1:
The first step is an initialization step. The currently known least cost path from A to its
directly attached neighbors, B, C, D are 2,5,1 respectively. The cost from A to B is set to 2,

44
from A to D is set to 1 andfrom A to C is set to 5. The cost from A to E and F are set to
infinity as they are not directly linked to A.

Step 2:
In the above table, we observe that vertex D contains the least cost path in step 1. Therefore, it
is added in N. Now, we need to determine aleast-cost path through D vertex.
Calculating shortest path from A to B

v = B, w = D
D(B) = min( D(B) , D(D) + c(D,B) )
= min( 2, 1+2)>
= min( 2, 3)
The minimum value is 2. Therefore, the currently shortest path from Ato B is 2.

Calculating shortest path from A to C

v = C, w = D
D(B) = min( D(C) , D(D) + c(D,C) )
= min( 5, 1+3)
= min( 5, 4)
The minimum value is 4. Therefore, the currently shortest path from Ato C is 4.</p>
Calculating shortest path from A to E
v = E, w = D
D(B) = min( D(E) , D(D) + c(D,E) )
= min( ∞, 1+1)
= min(∞, 2)
The minimum value is 2. Therefore, the currently shortest path from Ato E is 2.

Step 3:
In the above table, we observe that both E and B have the least cost path in step 2. Let's
consider the E vertex. Now, we determine the leastcost path of remaining vertices through E.

45
Calculating the shortest path from A to B.v = B, w = E
D(B) = min( D(B) , D(E) + c(E,B) )
= min( 2 , 2+ ∞ )
= min( 2, ∞)
The minimum value is 2. Therefore, the currently shortest path from Ato B is 2.

Calculating the shortest path from A to C.


v = C, w = E
D(B) = min( D(C) , D(E) + c(E,C) )
= min( 4 , 2+1 )
= min( 4,3)
The minimum value is 3. Therefore, the currently shortest path from Ato C is 3.

Calculating the shortest path from A to F.


v = F, w = E
D(B) = min( D(F) , D(E) + c(E,F) )
= min( ∞ , 2+2 )
= min(∞ ,4)
The minimum value is 4. Therefore, the currently shortest path from Ato F is 4.
Step 4:
In the above table, we observe that B vertex has the least cost path instep 3. Therefore, it is
added in N. Now, we determine the least cost path of remaining vertices through B.
Calculating the shortest path from A to C.
v = C, w = B
D(B) = min( D(C) , D(B) + c(B,C) )
= min( 3 , 2+3 )
= min( 3,5)
The minimum value is 3. Therefore, the currently shortest path from Ato C is 3.
Calculating the shortest path from A to F.
v = F, w = B

46
D(B) = min( D(F) , D(B) + c(B,F) )
= min( 4, ∞)
The minimum value is 4. Therefore, the currently shortest path from Ato F is 4.

Step 5:
In the above table, we observe that C vertex has the least cost path instep 4. Therefore, it is
added in N. Now, we determine the least cost path of remaining vertices through C.
a) Calculating the shortest path from A to F.
v = F, w = C
D(B) = min( D(F) , D(C) + c(C,F) )
= min( 4, 3+5)
= min(4,8)
The minimum value is 4. Therefore, the currently shortest path from Ato F is 4.

47

You might also like