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

Manual For Network Simulator

The document discusses several network simulation tools including NS-2, NS-3, OPNET, GloMoSim, OMNeT++ and their key features. It provides details on the graphical user interface, programming languages, advantages and applications of these different network simulators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Manual For Network Simulator

The document discusses several network simulation tools including NS-2, NS-3, OPNET, GloMoSim, OMNeT++ and their key features. It provides details on the graphical user interface, programming languages, advantages and applications of these different network simulators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Ex.

No: 1: Date :
Study of Network Simulator Tools

Aim:
To study of different Network Simulation Tools for constructing and performance
testing in different network.

Introduction:
Simulation is a very important modern technology. It can be applied to different
science, engineering, or other application fields for different purposes. Computer assisted
simulation can model hypothetical and real-life objects or activities on a computer so that it
can be studied to see how the system function. Different variables can be used to predict
the behavior of the system. Computer simulation can be used to assist the modeling and
analysis in many natural systems. Typical application areas include physics, chemistry,
biology, and human-involved systems in economics, finance or even social science. Other
important applications are in the engineering such as civil engineering, structural
engineering, mechanical engineering, and computer engineering. Application of simulation
technology into networking area such as network traffic simulation.

Basic concepts in network simulation


In the area of computer and communications networks, simulation is a useful
technique since the behavior of a network can be modeled by calculating the interaction
between the different network components (they can be end-host or network entities such
as routers, physical links or packets) using mathematical formulas. They can also be
modeled by actually or virtually capturing and playing back experimental observations
from a real production networks. After we get the observation data from simulation
experiments, the behavior of the network and protocols supported can then be observed
and analyzed in a series of offline test experiments. All kinds of environmental attributes
can also be modified in a controlled manner to assess how the network can behave under
different parameters combinations or different configuration conditions. Another
characteristic of network simulation that worth noticing is that the simulation program can
be used together with different applications and services in order to observe end-to-end or
other point-to-point performance in the networks.

Type of network simulators


For network protocol designers, it is often difficult to decide which simulator to
choose for a particular task. Therefore, we conduct a survey to find a network simulator
that provides a good balance between availability of ready to use models, scripting and
language support, extendibility, graphical support, easiness of use, etc. The survey is based
on a collection of a number of criteria including published results, interesting
characteristics and features. From our survey results, we broadly categories network
simulators as: “Widely Used” simulators and “Other” simulators. The network simulators
taken into consideration as “Widely Used” are Ns-2, Ns-3, GloMoSim, J-Sim, OMNet++,
OPNet, and QualNet.

Page 1 of 80
• OPNET (Optimized Network Evaluation Tool):

OPNET 's software environment is called Modeler, which is specialized for network
research and development. It can be flexibly used to study communication networks,
devices, protocols, and applications. Because of the fact of being a commercial software
provider, OPNET offers relatively much powerful visual or graphical support for the users.
The graphical editor interface can be used to build network topology and entities from the
application layer to the physical layer. Object-oriented programming technique is used to
create the mapping from the graphical design to the implementation of the real systems. An
example of the graphical GUI of OPNET can be seen in Figure 1. We can see all the topology
configuration and simulation results can be presented very intuitively and visually. The
parameters can also be adjusted and the experiments can be repeated easily through easy
operation through the GUI.

Figure 1. OPNET GUI

Main features:
OPNET inherently has three main functions: modeling, simulating and analysis. For
modeling, it provides intuitive graphical environment to create all kinds of models of
protocols. For simulating, it uses three different advanced simulations technologies and
can be used to address a wide range of studies. For analysis, the simulation results and
data can be analyzed and displayed very easily. User friendly graphs, charts, statistics, and
even animation can be generated by OPNET for users ' convenience.

Page 2 of 80
• Network Simulator 2 (NS2)
NS2 is one of the most popular open source network simulators. The original NS is a
discrete event simulator targeted at networking research. NS2 is the second version of NS
(Network Simulator). NS is originally based on REAL network simulator. The first version
of NS was developed in 1989 and evolved a lot over the past few years. The current NS
project is supported through DARPA. The current second version NS2 is widely used in
academic research and it has a lot of packages contributed by different non-benefit
groups. An example of the graphical GUI of NS2 can be seen in Figure 2.

Figure 2. NS2 GUI

Main features:
First and foremost, NS2 is an object-oriented, discrete event driven network
simulator which was originally developed at University of California-Berkely. The
programming it uses is C++ and OTcl (Tcl script language with Object-oriented extensions
developed at MIT). The usage of these two programming language has its reason. The
biggest reason is due to the internal characteristics of these two languages. C++ is efficient
to implement a design but it is not very easy to be visual and graphically shown. It's not
easy to modify and assembly different components and to change different parameters
without a very visual and easy-to-use descriptive language. Moreover, for efficiency reason,
NS2 separates control path implementations from the data path implementation. The event
scheduler and the basic network component objects in the data path are written and
compiled using C++ to reduce packet and event processing time. OTcl happens to have the
feature that C++ lacks. So the combination of these two languages proves to be very
effective. C++ is used to implement the detailed protocol and OTcl is used for users to
control the simulation scenario and schedule the events. A simplified user's view of NS2 is
shown in Figure 3. The OTcl script is used to initiate the event scheduler, set up the

Page 3 of 80
network topology, and tell traffic source when to start and stop sending packets through
event scheduler. The scenes can be changed easily by programming in the OTcl script.
When a user wants to make a new network object, he can either write the new object or
assemble a compound object from the existing object library, and plumb the data path
through the object. This plumbing makes NS2 very powerful.

Figure 3. Simplified User's View o f NS2

• Network Simulator 3 (NS3)


Similar to NS2, NS3 is also an open sourced discrete-event network simulator which
targets primarily for research and educational use. NS3 is licensed under the GNU GPLv2
license, and is available for research and development. NS3 is designed to replace the
current popular NS2. However, NS3 is not an updated version of NS2 since that NS3 is a
new simulator and it is not backward-compatible with NS2.

• OMNeT++
OMNeT++ has generic and flexible architecture which makes it successful also in
other areas like the IT systems, queuing networks, hardware architectures, or even
business processes as well. It is similar with NS2 and NS3, OMNeT++ is also a public-
source, component-based network simulator with GUI support. Its primary application
area is communication networks. Like NS2 and NS3, OMNeT++ is also a discrete event
simulator. It is a component-based architecture. Components are also called modules and
are programmed in C++. The components are then assembled into larger components and
models by using a high-level language. Its function is similar to that of OTcl in NS2 and
Python in NS3. OMNeT++ also provides GUI support, and due to its modular architecture,
the simulation kernel can be embedded into all kinds of different user s' applications.
Figure 5 is an OMNeT++ GUI screenshot.

Page 4 of 80
Figure 5. OMNeT++ GUI

Main features:
Since OMNeT++ is designed to provide a component-based architecture, the models
or modules of OMNeT++ are assembled from reusable components. Modules are reusable
and can be combined in various ways which is one of the main features of OMNeT++.

• Global Mobile Information System Simulator (Glo-MoSim)


It is a parallel discrete event simulation soft-ware[4] that simulates wireless and
wired network sys-tems. It is designed as a set of library modules, each of which simulates
a specific wireless communication pro-tocol in the protocol stack. It assumes that the
network is decomposed into a number of partitions and a single entity is defined to
simulate a single layer of the com-plete protocol stack for all the network nodes that be-
long to the partition. The parallel implementation of GloMoSim can be executed using
variety of conservative synchronization protocols, which include the null mes-sage and
conditional event algorithm. The library has been developed using PARSEC, a C based
parallel simulation language. It uses the Parsec compiler to com-pile the simulation
protocols. It has been designed to be extensible and comprehensible. GloMoSim aims to de-
velop a modular simulation environment for protocol stack that is capable of scaling up
networks with thou-sands of heterogeneous nodes. GloMoSim currently supports protocols
for a purely wireless network.
Features:
• GloMoSim is a library-based sequential and parallel simulator for wireless
networks.

Page 5 of 80
• GloMoSim facilitates the ability to use in a parallel environment which distinguishes
it from most other wireless network simulators.
• It allows the simulation Scalability to simulate net-works with a hundred and
thousand of nodes.
• It supports various layers like Mobility, Radio Propagation, Radio Model, Packet
reception models, Data Link, Network (Routing), Transport and Ap-plication. i.e. (It
supports almost all the OSI layers with limited benefits).
• GloMoSim supports direct satellite communication, multi-hop wireless
communication and most of the traditional internet protocols.
• It facilitates to build a library of parallelized mod-els that can be used for the
evaluation of a varie-ty of wireless network protocols.

• NetSim
NetSim is a stochastic discrete event network simula-tiontool used for network lab
experimentation and research. Its leading network simulation software for protocol
modeling and simulation, allowing us to ana-lyze computer networks with unmatched
depth, power and flexibility. NetSim comes with an in-built develop-ment environment,
which serves as the interface be-tween User’s code and NetSim’s protocol libraries and
simulation kernel. It provides network performance metrics at various abstraction levels
such as Network, sub-network, Node and a detailed packet trace. It has unique features and
functionality. NetSimis available as Standard or Academic versions and is built on a com-
mon design framework of high level architecture and code. In a word, NetSim is truly a
fantastic product that is not only versatile, but also robust and provides those features that
are hard to come with any simulators.
Features:
• NetSim modeling and simulation are supported for Aloha, Slotted Aloha, Token
Ring/Bus, Ethernet CSMA/CD, Fast and Gigabit Ethernet, WLAN - IEEE 802.11
a/b/g/n and e, X.25, Frame Relay, TCP, UDP, IPv4 and IPv6, Routing - RIP, OSPF,
BGP,MPLS, Wi-Max, MANET, GSM, CDMA, Wire-less Sensor Network, Zigbee,
Cognitive radio.
• It simulates a wide variety of Cisco routers, including 2500 series, 2600 series, 2800
series, and 3600 series routers, as well as the Cisco Catalyst 1900 series, 2900
series, and 3500 series switches.
• Protocol libraries are available as open C code for user modification. This can help
avoid the time consuming process of programming, customization and configuration
commercial simulators to meet customer specific needs.
• Along with the Boson Virtual Packet Technology engine NetSim utilizes Boson’s
proprietary Network Simulator, Router Simulator, and EROUTER soft-ware
technologies, to create individual packets. These packets are routed and switched
through the simulated network, allowing NetSim to build an appropriate virtual
routing table and simulate true networking. Other simulation products on the mar-
ket do not support this level of functionality.
• It can be used to create a simulation of the topology of corporate network and help
practice trouble-shooting without using devices on the production network.

Page 6 of 80
Comparison of simulators based on General Information

SI.
Name LicenseType Language SupportedOperating GUI port
1 Ns2 Open source C++ and OTCL GNU/Linux,FreeBS Limited
D, Mac OS X, Win-
dows XP, Windows
Vista and Win. 7.
2 Ns3 Open source C++and GNU/Linux,FreeBS Yes
Optional D, Mac OS X, Win-
Python dows XP, Windows
Bindings Vista and Win. 7.
3 QualNet Commercial C++ UNIX, Window, MAC, Yes
(Separatelicenseforacademi Linux
ciansand others)
4 GloMoSim Open source C Windows, Linux, Limited
SunSPARCSolaris
5 NetSim Proprietary C and Windows (7, Vista) Yes
Java and windowsXP
6 OMNET++ Open source(for studyand C++ WindowsXPorLater,Linu Yes
research x,MacOSX,

Comparison of simulators based on the properties of simulators

Number of
Simulation Event
SI. Name Available Module Scalability node Parallelism
Type
support
Wired,Wireless, Up
Discrete-
1 NS2 AdHoc and Wireless Limited to No
event
Sensor Networks 3000
Wired,Wireless, Up
Discrete-
2 NS3 Adhoc and Wireless Limited to No
event
Sensor Networks 3000
Wired
&Wireless(like WiFi,
Yes(S MP/Be
3 QualNet Discrete- event Sensor net- Large 500-20000
owulf
work,MANET,WI
MAX)network
Wired, Wireless &
Yes(S
Discrete- Ad-Hoc Networks. Up to
4 GloMoSim Large MP/Be
event But currently pure 10,000
owulf
wireless support
5 NetSim Stochastic Wired &Wireless, Large ------- -------

Page 7 of 80
Discrete- sensor network Enough
Event
Discrete- Wired, Wireless, Ad-
6 OMNET++ (wireless LAN, hoc and WSN. Enough -------- MPI/P
WiMAX)

Result:

Various Network Simulators has been successfully studied.

Page 8 of 80
Ex. No: 2 Date:

Installation of Network Simulator (NS2)

Aim:
To install the NS2 software and test it with simple example on Ubuntu Operating
System.

Steps for Installing Network Simulator 2 (NS2) on Ubuntu

Step 1: Download and Extract ns2

Download the all in one package for ns2 from internet. The package downloaded
will be named "ns-allinone-2.35.tar.gz". Copy it to the home folder. Then in a terminal use
the following two commands to extract the contents of the package:

tar -xvzf ns-allinone-2.35.tar.gz

All the files will be extracted into a folder called "ns-allinone-2.35".

Step 2: Building the dependencies

• Ns2 requires a few packages to be pre installed. It also requires the GCC- version
4.3 to work correctly. So install all of them by using the following command:

sudo apt-get install build-essential autoconf automake libxmu-dev

• One of the dependencies mentioned is the compiler GCC-4.3, which is no longer


available, and thus we have to install GCC-4.4 version. The version 4.4 is the
oldest we can get. To do that, use the follwoing command:

sudo apt-get install gcc-4.4

• Once the installation is over, we have to make a change in the "ls.h" file. Use the
following steps to make the changes: Navigate to the folder "linkstate", use the
following command. Here it is assumed that the ns folder extracted is in the
home folder of your system.

cd ~/ns-allinone-2.35/ns-2.35/linkstate

• Now open the file named "ls.h" and scroll to the 137th line. In that change the
word "error" to "this->error". The image below shows the line 137
(highlighted in the image below) after making the changes to the ls.h file. To
open the file use the following command:
Page 9 of 80
gedit ls.h

• Save that file and close it.


• Now there is one more step that has to be done. We have to tell the ns which
version of GCC will be used. To do so, go to your ns folder and type the following
command:

sudo gedit ns-allinone-2.34/otcl-1.13/Makefile.in

• In the file, change Change CC= @CC@ to CC=gcc-4.4, as shown in the image
below:

Page 10 of 80
• Save that file and close it.

Step 3: Installation

• Now we are ready to install ns2. To do so we first require root privileges and
then we can run the install script. Use the following two commands:

cd ns-allinone-2.35
./install
• After successful installation following message will be shown on the screen.
Ns-allinone package has been installed successfully.
Ns-allinone package has been installed successfully.
Here are the installation places:
tcl8.5.10: /home/sitams/ns-allinone-2.35/{bin,include,lib}
tk8.5.10: /home/sitams/ns-allinone-2.35/{bin,include,lib}
otcl: /home/sitams/ns-allinone-2.35/otcl-1.14
tclcl: /home/sitams/ns-allinone-2.35/tclcl-1.20
ns: /home/sitams/ns-allinone-2.35/ns-2.35/ns
nam: /home/sitams/ns-allinone-2.35/nam-1.15/nam
xgraph: /home/sitams/ns-allinone-2.35/xgraph-12.2
gt-itm: /home/sitams/ns-allinone-2.35/itm, edriver, sgb2alt, sgb2ns,
sgb2comns, sgb2hierns
----------------------------------------------------------------------------------
Please put /home/sitams/ns-allinone-2.35/bin:/home/sitams/ns-
allinone-2.35/tcl8.5.10/unix:/home/sitams/ns-allinone-
2.35/tk8.5.10/unix

Page 11 of 80
into your PATH environment; so that you'll be able to run
itm/tclsh/wish/xgraph.

IMPORTANT NOTICES:

(1) You MUST put /home/sitams/ns-allinone-2.35/otcl-1.14,


/home/sitams/ns-allinone-2.35/lib,
into your LD_LIBRARY_PATH environment variable.
If it complains about X libraries, add path to your X libraries
into LD_LIBRARY_PATH.
If you are using csh, you can set it like:
setenv LD_LIBRARY_PATH
If you are using sh, you can set it like:
export LD_LIBRARY_PATH=

(2) You MUST put /home/sitams/ns-allinone-2.35/tcl8.5.10/library into


your TCL_LIBRARY environmental variable. Otherwise ns/nam will
complain during startup.

After these steps, you can now run the ns validation suite with
cd ns-2.35; ./validate

For trouble shooting, please first read ns problems page


http://www.isi.edu/nsnam/ns/ns-problems.html. Also search the ns
mailing list archive for related posts.

Step 4: Setting the Environment Path


• The final step is to tell the system, where the files for ns2 are installed or
present. To do that, we have to set the environment path using the ".bashrc" file.
In that file, we need to add a few lines at the bottom. The things to be added are
given below:
sudo gedit ~/.bashrc

• Lines to be added:
# LD_LIBRARY_PATH
OTCL_LIB=/home/sitams/ns-allinone-2.35/otcl-1.14
NS2_LIB=/home/sitams/ns-allinone-2.35/lib
X11_LIB=/usr/X11R6/lib
USR_LOCAL_LIB=/usr/local/lib
export
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$X11_LIB:$USR_
LOCAL_LIB
# TCL_LIBRARY
TCL_LIB=/home/sitams/ns-allinone-2.35/tcl8.5.10/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB
Page 12 of 80
# PATH
XGRAPH=/home/sitams/ns-allinone-2.35/bin:/home/sitams/ns-allinone-
2.35/tcl8.5.10/unix:/home/sitams/ns-allinone-2.35/tk8.5.10/unix
#the above two lines beginning from xgraph and ending with unix should
come on the same line
NS=/home/sitams/ns-allinone-2.35/ns-2.35/
NAM=/home/sitams/ns-allinone-2.35/nam-1.15/
PATH=$PATH:$XGRAPH:$NS:$NAM

• Once the changes have been made, save the file and restart the system.

Step 5: Running ns2


• Once the system has restarted, open a terminal and start ns2 by using the
following command:

ns

• System returns

%
Step 6: Testing ns2
Test the addition of two integer numbers.
% set a 10
10
% set b 20
20
% expr $a+$b
30
%

Result :

NS2 software has been successfully installed and it’s tested with simple example on
Ubuntu Operating System.

Page 13 of 80
Ex. No: 3 Date:
Study of TCL Commands

Aim:
To study the various TCL Commands.

Introduction:
TCL is an interpreted language. Each instruction is a command in tcl program. TCL
programming is used to write simulation script in ns2. Following are the topics which you
need to learn in order to write simulation script.
Topics:
• Variables in TCL
• Basic Operations
• If-else
• Loop
• Array
• Procedure
• File Handling

• Variables in TCL
• set command
set command is used to make a variable and assign value to them. This
command is also used to fetch value of variable.
Syntax :

set <variable_name><variable_value>

Example for store the value into variable:

set x 100
//creating a integer variable with name ‘x’ and value ‘10’
set name "sitams"
//creating a string variable with name ‘name’ and value ‘sitams’
set price 120.5
//creating a float variable with name ‘price’ and value ‘120.5’

Example for read the value from variable:

set x // The system returns value of x, i.e 100


set name // The system returns value of name, i.e sitams
set price // The system returns value of price, i.e 120.5

• unset command
unset command is used to delete a variable.

Page 14 of 80
Syntax :

unset <variable_name>

Example:

unset x

Before unset x:
set x
100

After unset x:
set x
can't read "x": no such variable

• Read values from keyboard and store into variable


gets stdin command is used to read the values for keyboard and store into variable.
Syntax :

gets stdin <variable_name>

Example:

gets stdin x
Enter the value of x: 20

• Use variable's value


Value of any variable can be used by using $ symbol.
Syntax :

set <new_variable_name> $<source_variable_name>

Example:

set x 20 // creating a integer variable with name ‘x’ and value ‘20’
set y $x // assign value of x variable to another variable y.
set y // The system returns value of y, i.e 20

• Print variable's value


puts or echo command is used to print the message or variable value.
Syntax :

puts “message” or $<variable_name>


echo “message” or $<variable_name>

Page 15 of 80
Example:

puts “hello” or echo “hello”


// print hello message on the screen and take cursor to new line.
puts -nonewline "welcome"
// print welcome message on the screen in same line
set x 20 // creating a integer variable with name ‘x’ and value ‘20’
puts $x or echo $x // print x value on the screen.

Simple Program:
set x 10
set y 20
puts "value of x is $x"
puts "value of y is $y"

Output:
value of x is 10
value of y is 20

• Basic Operations
In tcl expr command used to perform operations. expr command takes entire
expression as arguments.
Syntax :
expr $<variable_name> + $<variable_name>

Example for result printing on the screen:


set x 10
set y 20
expr $x + $y

Output: 30

Example for result store into variable:


set x 10
set y 20
set z [expr $x + $y]
puts "Result of addition: $z"

Output: Result of addition: 30

Program for Area of Circle:


Open editor and type the program and save it. (example gedit filename.tcl)
puts "Enter the radius :"

Page 16 of 80
gets stdin r
set pie [expr 22/7]
set area [expr $r*$r*$pie]
puts "Area of circle: $area"

Run the program ($ns filename.tcl):


$ns circle.tcl

Ouput:
csm@ubuntu:~$ ns ss.tcl
Enter the radius :
2
Area of circle: 12

• If statements:
TCL also has construct for if statements.

• Simple if statement
Syntax:

if {condition} {
statement_block
}
statement_x

Another syntax:

if [ expr condition] {
statement_block
}
statement_x

In this syntax if condition is true, the statement_block will be


executed; otherwise the statement block skipped and execution will jump to
the statement_x. If condition true both statements are executed in sequence.

Program for condition is true:


set x 30
if { $x < 50 } {
puts "x is less than 50"
}
puts "x is greater than 50"

Output:

Page 17 of 80
csm@ubuntu:~$ ns ss1.tcl
x is less than 50
x is greater than 50

Program for condition is false:


set x 60
if { $x < 50 } {
puts "x is less than 50"
}
puts "x is greater than 50"

Output:
csm@ubuntu:~$ ns ss1.tcl
x is greater than 50

• if –else statement
Syntax:

if {condition} {
statement_true_block
} else {
statement_false_block
}

In this syntax if condition is true, the true block statements will be


executed; otherwise false block statement will be executed.

Program:

gets stdin x
if { $x < 50 } {
puts "x is less than 50"
} else {
puts "x is greater than 50"
}

Output:

csm@ubuntu:~$ ns ss1.tcl
10
x is less than 50

Page 18 of 80
csm@ubuntu:~$ ns ss1.tcl
100
x is greater than 50

• if-elseif statement

Syntax:

if {condition1} {
statement_true_block 1
} elseif {condition2} {
statement_false_block2
} else {
statement_false_block
}

In this syntax if condition is true, the first True block statements will
be executed; otherwise check the another condition, if condition2 is true, the
second true block statements will be executed, otherwise False block
statement will be executed.

Program:
gets stdin a
gets stdin b
gets stdin c
if { $a>=$b && $a>=$c} {
puts "A is Biggest"
} elseif {$b>=$a && $b>=$c} {
puts "B is Biggest"
} else {
puts "C is Biggest"
}

Output:
csm@ubuntu:~$ ns ss1.tcl
4
3
2
A is Biggest

• switch statement

Page 19 of 80
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for
each switch case.
Syntax:
switch switchingString {
matchString1 { body1 }
matchString2 { body2 }
...
matchStringn { bodyn }
}

Program:
gets stdin grade
switch $grade {
A { puts "Well done!" }
B { puts "Excellent!" }
C {puts "You passed!" }
F {puts "Better try again"}
default {puts "Invalid grade" }
}
puts "Your grade is $grade"

Output:

csm@ubuntu:~$ ns ss1.tcl
A
Well done!
Your grade is A
csm@ubuntu:~$ ns ss1.tcl
B
Excellent!
Your grade is B
csm@ubuntu:~$ ns ss1.tcl
R
Invalid grade
Your grade is R

• Loop Statements
• while loop
A while loop statement in Tcl language repeatedly executes a target
statement as long as a given condition is true.
Syntax:
while {condition} {
statement(s)

Page 20 of 80
}

Program:
set a 0

while { $a < 10 } {
puts "value of a: $a"
incr a
}

Output:

csm@ubuntu:~$ ns ss1.tcl
value of a: 0
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9

• for loop
A for loop is a repetition control structure that allows you to efficiently write
a code that needs to be executed for a specific number of times.

Syntax:
for {initialization} {condition} {increment} {
statement(s);
}

Program:
for { set a 0} {$a < 10} {incr a} {
puts "value of a: $a"
}

Output:

csm@ubuntu:~$ ns ss1.tcl
value of a: 0
value of a: 1
value of a: 2

Page 21 of 80
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
• Array

Array is a collection of homogeneous data. TCL also support named array in which
string is given as named variable.
Syntax:
set ArrayName(Index) value

Program:
set a(0) 10
set a(1) 30
puts $a(0)

// Another Way
array set b {10,30}
puts $b(0)

Output: 10

• Procedure
Multiple commands can be combined to make a new command. This can be done by
making a procedure.
Syntax:
proc <procedure name> { } {
procedure-body
}
Program:
proc fact { a } {
set fact 1
for {set i 1} {$i <= $a} {incr i} {
set fact [expr $fact * $i]
}
puts "factorial Value is :$fact"
}
fact 5

Output: factorial Value is :120

Page 22 of 80
• File Handling
Before performing any operation on file, that file needs to be opened. In tcl open
command is used to open a channel with file to perform read/write operation. File can
be opened in various modes which allow which operation is allowed. These modes are
• Read only Mode (r)
• Write Only Mode (w)
• Append Mode (a)
• Read and Write (r+)
• Write and Read (w+)

• Opening File
Syntax:
open <file_name><acc_type>
Example:
open one.txt r

# For assigning open file handle to variable.


set file1 [open one.txt r]

• Writing File - puts command is used for writing data in file.


Syntax:
puts <file_handle><data|variable_value>

Example:
set f [open one.txt w]
puts $f "welcome to tcl"
close $f

• Reading File - gets command is used for reading data from file.
Syntax:
gets <file_handle><variable_value>
Example:
set f [open one.txt r]
gets $f data
puts $data
close $f

Result:

Various Tcl commands have been studied successfully

Page 23 of 80
Ex No:4 Date:

NS SIMULATION SCENARIO FOR 4 NODES


AIM:
To write tcl script to simulate a simple wired netork with four nodes

ALGORITHM:
1.start
2.create a simulator object with name ns
3.create a trace objects with name nt
4. create a nam object nf
5.create 4 nodes with names n0,n1,n2,n3
6.connect the link between nodes n0 n2, n1 n2, and n2 n3
7.give the nodes a standard position
8.create a udp agent udp0 and udp1 and attach it to n0 and n1
9.a CBR traffic source cbr0 and cbr1 are created and attach it to udp0 and udp1
10.a null agent is created n0 and attach it nodes n2 and n3
11.connect the traffic source with traffic sink
12.schedule events for cbr agent
13.write finish procedure
14.call the finish procedure
15.now run the simulation
16. stop

PROGRAM:

#create a simulator object


set ns [new Simulator]
#creating trace object
set nt [open test2.tr w]
$ns trace-all $nt
#creating nam objects
set nf [open test2.nam w]
$ns namtrace-all $nf
#creating nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#creating links between nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail #bandwidth , delay, queue type
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 2Mb 10ms DropTail
#node orientation
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
Page 24 of 80
$ns duplex-link-op $n2 $n3 orient right
#create a udp agent and attach it to n0 and n1
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
#create a cbr traffic source and attach it to udp0 and udp1
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetsize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set cbr1[new Application/Traffic/CBR]
$cbr1 set packetsize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
#create a null agent ( a traffic sink ) and attach it to node n2 and n3
set null0 [new Agent/Null]
$ns attach-agent $n2 $null0
$ns attach-agent $n3 $null0
#connect the traffic source with the traffic sink
$ns connect $udp0 $null0
$ns connect $udp1 $null0
# schedule events for the CBR agent
$ns at 0.7 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
$ns at 0.5 "$cbr1 start"
$ns at 4.5 "$cbr1 stop"
#define finish procedure
proc finish {} {
global ns nf
$ns flush-trace
#close the NAM tracefile
close $nf
#execute NAM on the trace file
exec nam test2.nam &
exit 0
}
#call finish procedure
$ns at 5.0 "finish"
#run the simulation
$ns run

Page 25 of 80
OUTPUT:

RESULT:

Thus the program for creating simple scenario of creating four nodes had been
executed successfully.

Page 26 of 80
Ex No: 5 Date:

TCP SCENARIO WITH DROPTAIL QUEUE MECHANISM

AIM:
To create a simple TCP scenario with droptail queue mechanism on the gateway

ALGORITHM:
1.start
2.create a simulator object ns
3.create a trace object nt
4.create a nam object nf
5.create a 4 nodes
6.create link between nodes and create node orientation
7.create a queue between n2 and n3
8.set a TCP coonection for n0 over ftp
9.set up a UDP connection for n2 over CBR
10.set up a null agent for n3
11.write finish procedure
12.run the program

PROGRAM:

#create a simulator object


set ns [new Simulator]
#creating trace object
set nt [open test4.tr w]
$ns trace-all $nt
#creating nam objects
set nf [open test4.nam w]
$ns namtrace-all $nf
#creating nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#creating links between nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 2Mb 10ms DropTail
#node orientation
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#monitor the queue file link
$ns duplex-link-op $n2 $n3 queuePos 0.5
Page 27 of 80
$ns color 1 Blue
$ns color 2 Red
# set a TCP connection
set tcp0 [new Agent/TCP]
$tcp0 set class-2
$ns attach-agent $n0 $tcp0
set Sink [new Agent/TCPSink]
$ns connect $tcp0 $sink
$tcp0 set fid_1
#set up a ftp connection over tcp
set ftp [new Agent/FTP]
$ftp attach-agent $tcp0
$ftp set type_ ftp
#set up a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n2 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2
#set up a cbr over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set PacketSize_ 300
$cbr set rate_ 1Mb
$cbr set random_ false

# schedule events for the CBR agent and FTP agent


$ns at 0.1 "$cbr start"
$ns at 0.5 "$ftp start"
$ns at 3.5 "$cbr stop"
$ns at 2.5 "$ftp stop"
#set queue
$ns queue-link $n2 $n3 10
#detach TCP and Sink agents
$ns at 4.5 "$ns detach-agent $n0 $tcp0;$ns detach-agent $n3 $sink"
#define finish procedure
proc finish {} {
global ns nf
$ns flush-trace
#close the NAM tracefile
close $nf
#execute NAM on the trace file
exec nam test4.nam &
exit 0
Page 28 of 80
}
#call finish procedure
$ns at 5.0 "finish"
#run the simulation
$ns run

OUTPUT:

Page 29 of 80
RESULT:

Thus the program for simple TCP scenario with dropTail queue mechanism had
been executed successfully.

Page 30 of 80
Ex No:6 Date:

NEW AGENT USING C++ AND TCL

AIM:
To write a program to create a new agent called MyAgent.

Algorithm:
1.create a class MyAgent and take n1,n2 as private and methods such as
command,multiply,show as protected and a constructor MyAgent as public.
2.create a class MyAgentclass.
3.create a tcl object and return.
4.set up connections and take inputn1,n2.
5.if argc==4 then argv[1] is "sum" then add n1,n2.
6.if argc==2 then argv[1] is "sub" then n1-n2.
7.if argv[1] is "mul" then call multiply function.
8.in multiply() scan n1,n1 values from keyboard and perform n1*n2.
9.display output.
10.stop.

PROGRAM:
C ++ Program for attaching new agent:
#include "agent.h" //Available in the path of NS2
#include<stdio.h>
class MyAgent:public Agent
{
private:
int n1,n2;
protected:
int command(int argc,const char* const* argv);
void multiply();
void show();
public:
MyAgent();
};
static class MyAgentClass : public TclClass
{
public:
MyAgentClass():TclClass("Agent/MyAgent")
{}
TclObject * create(int,const char* const*) // To use the above MyAgent as constant name
use this line
{
return (new MyAgent());
}}
//Shadow object
Page 31 of 80
//When a TCL object is been called, the C++ class will retuen an agent. If agent is
//Not present, it shows a failed shadow object error.

class_MyAgent;

//Now implement all the functions of the main class

MyAgent::MyAgent():Agent(PT_UDP) //PT-Packet type


{
bind("n1_",&n1); // variables to be called from tcl, binding is between OTCL and C++
bind("n2_",&n2);

} int MyAgent::command(int argc,const char* const* argv)


//argc is argument count (starts 0), argv is argument vector (starts 1)
{
if(argc==4)
{
if(strcmp(argv[1],"Sum")==0)
{
n1=atoi(argv[2]);
n2=atoi(argv[3]);
printf("%d+%d=%d\n",n1,n2,n1+n2);
}
return (TCL_OK);
}
if(argc==2)
{
if(strcmp(argv[1],"Sub")==0)
{
printf("%d-%d=%d\n",n1,n2,n1-n2);
}
if(strcmp(argv[1],"Show")==0)
{
printf("The value of n1=%d\nThe value of n2=%d\n",n1,n2);
}
if(strcmp(argv[1],"Mul")==0)
{
multiply ();
}
return (TCL_OK);
}
return Agent::command(argc,argv);
}
void MyAgent::multiply()
{
printf("Enter n1,n2 values:\n");
Page 32 of 80
scanf("%d%d",&n1,&n2);
printf("%d*%d=%d\n",n1,n2,n1*n2);
}

Procedure for attaching agent:

➢ create a new folder in ‘ns-allinone-2.35/ns-2.35’ with name ‘test’ and save the above
file
with name ‘MyAgent.cc’ in test folder
➢ Again go to ns-allinone-2.35/ns-2.35 and then open makefile in this file after the line
164 insert “test/MyAgent.o \” . ensure that there should not be any extra blank spaces
after “\” open the terminal and type the following commands:
$ cd ns-allinone-2.35/ns-2.35
$ make clean
for i in indep-utils/cmu-scen-gen/setdest in…...…...ns.core core core.ns core.nsx core.nse
common/ptypes2tcl common/ptypes2tcl.o
$ make
gcc -c -Wall -Wno-write-strings -DTCP_DELAY_BIND_ALL -DNO_TK -
DTCLCL_CLASSINSTVAR
-DNDEBUG -DLINUX_TCP_HEADER -DUSE_SHM -DHAVE_………..
-Wall -Wno-write-strings -DCPP_NAMESPACE=std -o ucb-tr-stat tr-stat.o logparse.o utils.o
-L/home/mallesh/ns-allinone-2.35/lib -ltcl8.5 -lnsl -ldl -lm
make[1]: Leaving directory '/home/mallesh/ns-allinone-2.35/ns-2.35/indep-
utils/webtrace-conv/ucb'
$ su
Password:****
root@ubuntu:ns-allinone-2.35/ns-2.35# make install

TCL Script:

set agent1 [new Agent/MyAgent] //agent1 is object ref


$agent1 Sum 10 20
$agent1 Show
$agent1 set n1_ 5
$agent1 set n2_ 2
$agent1 Sub
$agent1 Show
$agent1 Mul
$agent1 Show

Page 33 of 80
OUTPUT:

10+20=30
The value of n1=10
The value of n2=20
5-2=3
The value of n1=5
The value of n2=2
Enter n1,n2 values:
10
20
10*20=200
The value of n1=10
The value of n2=20

RESULT:

Thus the program for creating new agent called MyAgent using c++ has been
executed successfully.

Page 34 of 80
Ex No: 7 Date:

PROTOCOL PING USING C++ AND TCL

AIM:
To create a new protocol for ping using c++ program.

ALGORITHM:
1.start
2.create a structure named MyPingHeader.
3.write header access methods.
4.create class MyPingHeader and MyPingclass.
5.in MyPingAgent create a new packet ie
Packet *pkt=allocPkt()
6.access the ping header for new packet.
7.store the time in send_time filed and send packet.
8.access ip header for received packet.
9.if flag field is 0 then send an echo and discard the packet and create a new packet and
access ping header for new packet.
10.else display the nodes received ping answer from another and free all packets.
11.stop.

PROGRAM:
C ++ Program for implementation of PING Protocol:

#include "agent.h"
#include "tclcl.h"
#include "packet.h"
#include "address.h"
#include "ip.h"
#include<stdio.h>
struct MyPingHeader
{ char flag;
double send_time;
static int offset_;
inline static MyPingHeader* access(const Packet* p)
{
return (MyPingHeader*) p->access(offset_);
}}
;
class MyPingAgent : public Agent
{
public:
MyPingAgent();
protected:
int command(int argc,const char*const* argv);
Page 35 of 80
void recv(Packet*,Handler*);
};
int MyPingHeader::offset_;
static class MyPingHeaderClass : public PacketHeaderClass
{
public:
MyPingHeaderClass():PacketHeaderClass("PacketHeader/MyPing",sizeof(MyPingHeader))
{
bind_offset(&MyPingHeader::offset_);
}}
class_pinghdr;
static class MyPingClass:public TclClass
{
public:
MyPingClass():TclClass("Agent/MyPing")
{}
TclObject * create(int,const char*const*)
{
return (new MyPingAgent());
}
}class_ping;
MyPingAgent::MyPingAgent() : Agent(PT_PING)
{}
int MyPingAgent::command(int argc,const char*const* argv)
{ if(argc==2)
{ if(strcmp(argv[1],"send")==0)
{
Packet *pkt=allocpkt();
MyPingHeader *hdr=MyPingHeader::access(pkt);
hdr->flag=0;
hdr->send_time=Scheduler::instance().clock();
send(pkt,0);
return(TCL_OK);
}}
return (Agent::command(argc,argv));
}
void MyPingAgent::recv(Packet *pkt,Handler*)
{
hdr_ip* iphdr=hdr_ip::access(pkt);
MyPingHeader* pinghdr=MyPingHeader::access(pkt);
if(pinghdr->flag==0)
{
double stime=pinghdr->send_time;
Packet::free(pkt);
Packet* pktret=allocpkt();
MyPingHeader* hdrret=MyPingHeader::access(pktret);
Page 36 of 80
hdrret->flag=1;
hdrret->send_time=stime;
send(pktret,0);
} else
{
double rtt=Scheduler::instance().clock()-pinghdr->send_time;
printf("node %d received ping answer from node %d with round-trip-time=%1f rtt
seconds\n",iphdr-
>src_.addr_,iphdr->dst_.addr_,rtt);
Packet::free(pkt);
}}

Procedure for attaching agent:

➢ create a new folder in ‘ns-allinone-2.35/ns-2.35’ with name ‘Ping’ and save the above
file with name ‘MyPing.cc’ in test folder
➢ Again go to ns-allinone-2.35/ns-2.35 and then open makefile in this file after the line
164
insert “Ping/MyPing.o \” . ensure that there should not be any extra blank spaces after “\”
open the terminal and type the following commands:
$ cd ns-allinone-2.35/ns-2.35
$ make clean
for i in indep-utils/cmu-scen-gen/setdest in…...…...ns.core core core.ns core.nsx core.nse
common/ptypes2tcl common/ptypes2tcl.o
$ make
gcc -c -Wall -Wno-write-strings -DTCP_DELAY_BIND_ALL -DNO_TK -
DTCLCL_CLASSINSTVAR
-DNDEBUG -DLINUX_TCP_HEADER -DUSE_SHM -DHAVE_………..
-Wall -Wno-write-strings -DCPP_NAMESPACE=std -o ucb-tr-stat tr-stat.o logparse.o utils.o
-L/home/mallesh/ns-allinone-2.35/lib -ltcl8.5 -lnsl -ldl -lm
make[1]: Leaving directory '/home/mallesh/ns-allinone-2.35/ns-2.35/indep-
utils/webtrace-conv/ucb'
$ su
Password:****
root@ubuntu:ns-allinone-2.35/ns-2.35# make install

TCL Script:

set ns [new Simulator]


set n0 [$ns node]
set n1 [$ns node]
$ns duplex-link $n0 $n1 1Mb 1s DropTail
set p0 [new Agent/MyPing]
$ns attach-agent $n0 $p0
set p1 [new Agent/MyPing]

Page 37 of 80
$ns attach-agent $n1 $p1
$ns connect $p0 $p1
$ns at 1 "$p0 send"
$ns at 3 "$p0 send"
$ns at 5 "$p0 send"
$ns at 7 "$p0 send"
$ns at 10.0 "$ns halt"
$ns run

OUTPUT:
node 1 received ping answer from node 0 with round-trip-time=2.000000 rtt seconds
node 1 received ping answer from node 0 with round-trip-time=2.000000 rtt seconds
node 1 received ping answer from node 0 with round-trip-time=2.000000 rtt seconds
node 1 received ping answer from node 0 with round-trip-time=2.000000 rtt seconds

RESULT:

Thus the program for creating a new protocol called ping has been executed
successfully.

Page 38 of 80
Ex No: 8 Date:

DIJKSTRA'S ALGORITHM
AIM:
To write a C program for implementation of dijkstras algorithm.
ALGORITHM:
1.start
2.Enter number of nodes and read the cost matrix from the keyboard.
3.for(j=0;j<n;j++) then do
3.1:for(i=0;i<n;i++) then do
3.1.1: d[i]=c[j][i] end for
3.2.d[n]=30000
3.3.dijkstra(c,d,j,n)
3.4.Display the shortest path from node j
3.5.end for
4.free(c)
5.free(d)
6.stop
Program:

Shortest Path Using Dijkstra’s Algorithm:


#include<stdio.h>
#include<stdlib.h>
int minimum(int i,int j)
{
if(i<j)
return i;
else
return j;
}
int digikstra(int **c,int *d,int sn,int n)
{ int *
v,min,i,j;
v=(int*)calloc(n,sizeof(int));
v[sn]=1;
for(j=1;j<n;j++)

Page 39 of 80
{
min=n;
for(i=0;i<n;i++)
if(d[i]<=d[min]&&v[i]!=1)
min=i;
v[min]=1;
for(i=0;i<n;i++)
if(v[i]==0)
d[i]=minimum(d[i],d[min]+c[min][i]);
}
free(v);
} int main()
{ int **c,*d,sn,n,i,j,t;
printf("enter the number of nodes:\n");
scanf("%d",&n);
c=(int**)calloc(n,sizeof(int*));
for(i=0;i<n;i++)
c[i]=(int*)calloc(n,sizeof(int));
d=(int*)calloc(n+1,sizeof(int));
printf("enter the cost matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{s
canf("%d",&t);
(t==-1)?(c[i][j]=30000):(c[i][j]=t);
}
printf("the shortest path from all %d nodes:\n",n);
for(j=0;j<n;j++)
{
for(i=0;i<n;i++)
d[i]=c[j][i];
d[n]=30000;
digikstra(c,d,j,n);
for(i=0;i<n;i++)
printf("%d ",((d[i]>=10000)?-1:d[i]));
printf("\n");
}
free(c);
free(d);
}

Page 40 of 80
Output:

enter the number of nodes:


4
enter the cost matrix:
0 -1 2 6
-1 0 5 8
2 502
6 820
the shortest path from all 4 nodes:
0724
7057
2502
4720

Result:

Thus the program for finding shortest path using dijkstra’s has been executed
successfully.

Page 41 of 80
Ex No: 9 Date:

LINK STATE PROTOCOL


AIM:
To write a C program for implementing Link state routing algorithm.
Algorithm:
1.start
2.Declare count,src_router,I,j,k,w,v,min.
3.Declare cost_matrix[100][100],dist[100],last[100],flag.
4.Enter the number of routers.
5.Enter the cost matrix values.
6.if the cost_matrix[i][j]<0 then reinitialize cost_matrix[i][j]=1000;
7.Enter the source router.
8.Inside for loop set last[v]=src_router and distance vector cost_matrix[src_router][v].
9.if dist[w]<min then v=w then min=dist[w] .
10.if (min+cost_matrix[v][w]<dist[w]) then dist[w] =min+cost[v][w]; and last[w]=v;
PROGRAM:
#include <stdio.h>
#include <string.h>
int main()
{
int count,src_router,i,j,k,w,v,min;
int cost_matrix[100][100],dist[100],last[100];
int flag[100];
printf("\n Enter the no of routers");
scanf("%d",&count);
printf("\n Enter the cost matrix values:");
for(i=0;i<count;i++)
for(j=0;j<count;j++)
{
scanf("%d",&cost_matrix[i][j]);
if(cost_matrix[i][j]<0)
cost_matrix[i][j]=1000;
}
printf("\n Enter the source router:");
scanf("%d",&src_router);
for(v=0;v<count;v++)

Page 42 of 80
{
flag[v]=0;
last[v]=src_router;
dist[v]=cost_matrix[src_router][v];
}
flag[src_router]=1;
for(i=0;i<count;i++)
{
min=1000;
for(w=0;w<count;w++)
{
if(!flag[w])
if(dist[w]<min)
{
v=w;
min=dist[w];
}
}
}
flag[v]=1;
for(w=0;w<count;w++)
if(!flag[w] && min+cost_matrix[v][w]<dist[w])
{
dist[w]=min+cost_matrix[v][w];
last[w]=v;
}
printf(“the shortest path from %d to remaining nodes is:\n”,src_router);
for(i=0;i<count;i++)
{
w=i;
while(w!=src_router)
w=last[w];
printf("\n %d----→%d:%d",src_router,i,dist[i]);
}
}

Page 43 of 80
OUTPUT :
Enter the no of routers
4
Enter the cost matrix values:
0 -1 2 6
-1 0 5 8
2502
6820
Enter the source router: 0
the shortest path from 0 to remaining nodes is:
0----->0 : 0
0----->1:7
0----->2:2
0----->3 :4

RESULT:

Thus the program for finding shortest distance using link state packets has been
executed successfully.

Page 44 of 80
Ex No:10 Date:

TRACE FILE ANALYSIS

Aim:
To write a C program to print the number of packets dropped,sent,received.
Algorithm:
1.start
2.open main()
3.open the file using file pointer in read mode.
4.Declare float variables drop=0,received=0,sent=0,throughput=0 and character variable
char ch;
5.while((ch=getc(f)!=EOF) then
5.1:if(ch==’d’)
++drop;
5.2:if(ch==’r’)
++received;
6.while(getc(f)!=’\n’) the empty loop
7.Calculate sent packet,throughput and print them on the screen.
8.stop
program:

BEGIN {
r=d=0
}
{
if ( $1 == "r" )
++r
else if ( $1 == "d" )a
++d
}
END {
printf("received=%d,dropped=%d,sent=%d,throughput=%f\n",r,d,r+d,r/(r+d));
}

Page 45 of 80
OUTPUT :

BAND WIDTH THROUGHPUT


0.5 0.794082
1 0.876004
1.5 0.981439
2 0.96875
2.5 0.96875
3 0.96875
3.5 0.96875
4 0.96875
4.5 0.96875
5 0.96875

throughput
1.2

0.8

0.6

0.4

0.2

0
1 2 3 4 5 6 7 8 9 10

RESULT:

Thus the program for analyzing the trace file using awk program has been executed
successfully.

Page 46 of 80
Ex No:11 Date:
LAN SIMULATION

AIM:
To write a TCL script for lan simulation.

ALGORITHM:

1.Start

2.Create simulator object.

3.Create a trace objects.

4.Create a name objects.

5.Create the nodes named from N0 to N7.

6.Create the link between the nodes.

7.Give a fixed positions to nodes.

8.Set the queue size of links n2-n3,n5-n4 to 10.

9.Create the queue between the nodesn2-n3 and n5-n4.

10.Create a TCP connection tcp0 to node1.

11.Create a FTP connection ftp0 over tcp0.

12.Create a TCP sink and attach to n2,n3,n4 and connect sink1 to tcp0.

13.Create a UDP connectionudp0 to no.

14.Create a CBR connection cbr0 over udp0.

15.Create a null agent null0 and attach to n2,n3,n4 and connect to udp0.

16.Create aTCP connection tcp1 to n6.

17.Set up a ftp connection ftp1 over tcp1.

18.Create a TCP sink,sink2 and attach to n5,n4 and connect to tcp1.

19.Create a UDP connection udp1 to n7.

20.Set up a CBR connection cbr1 over udp1.

21.Create a null agent null and attach to n3,n4 and connect to udp1.

Page 47 of 80
22.Schedule events for the CBR and FTP agents.

23.Define a 'finish procedure'.

24.Call the finish procedure.

25.Run the simulation.

26.Stop.

program:

set ns [new Simulator]


set tf [open LAN.tr w]
$ns trace-all $tf
set nf [open LAN.nam w]
$ns namtrace-all $nf
for { set i 0 } { $i<=7 } { incr i } {
set n($i) [$ns node]
$n($i) color blue
$n($i) label "node$i"
}
$ns duplex-link $n(0) $n(2) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(2) 1Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 2Mb 10ms DropTail
$ns duplex-link $n(7) $n(3) 1Mb 10ms DropTail
$ns duplex-link $n(3) $n(4) 2Mb 10ms DropTail
$ns duplex-link $n(4) $n(5) 2Mb 10ms DropTail
$ns duplex-link $n(5) $n(6) 1Mb 10ms DropTail
$ns duplex-link-op $n(0) $n(2) orient right-down
$ns duplex-link-op $n(1) $n(2) orient right-up
$ns duplex-link-op $n(2) $n(3) orient right
$ns duplex-link-op $n(3) $n(7) orient up
$ns duplex-link-op $n(3) $n(4) orient right
$ns duplex-link-op $n(4) $n(5) orient right
$ns duplex-link-op $n(5) $n(6) orient right
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
$udp0 set fid_ 100
set udp7 [new Agent/UDP]
$ns attach-agent $n(7) $udp7
$udp7 set fid_ 101
set tcp1 [new Agent/TCP]
$ns attach-agent $n(1) $tcp1
$tcp1 set fid_ 102
set tcp6 [new Agent/TCP]

Page 48 of 80
$ns attach-agent $n(6) $tcp6
$tcp6 set fid_ 103
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1000
$cbr0 set interval_ 0.005
set cbr7 [new Application/Traffic/CBR]
$cbr7 attach-agent $udp7
$cbr7 set packetSize_ 1000
$cbr7 set interval_ 0.005
set null4 [new Agent/Null]
$ns attach-agent $n(4) $null4
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ftp1 set packetSize_ 2000
$ftp1 set interval_ 0.001
set ftp6 [new Application/FTP]
$ftp6 attach-agent $tcp6
$ftp6 set packetSize_ 1600
$ftp6 set interval_ 0.001
set sink4 [new Agent/TCPSink]
$ns attach-agent $n(4) $sink4
set sink41 [new Agent/TCPSink]
$ns attach-agent $n(4) $sink41
$ns connect $udp0 $null4
$ns connect $udp7 $null4
$ns connect $tcp6 $sink41
$ns connect $tcp1 $sink4
$ns at 0.1 "$cbr0 start"
$ns at 0.8 "$cbr7 start"
$ns at 0.1 "$ftp1 start"
$ns at 0.1 "$ftp6 start"
$ns at 4.5 "$ftp1 stop"
$ns at 4.5 "$ftp6 stop"
$ns at 4.5 "$cbr0 stop"
$ns at 4.5 "$cbr7 stop"
$ns color 100 green
$ns color 101 green
$ns color 102 red
$ns color 103 red
$ns queue-limit $n(2) $n(3) 5
$ns duplex-link-op $n(2) $n(3) queuePos 0.5
$ns queue-limit $n(5) $n(4) 5
$ns duplex-link-op $n(5) $n(4) queuePos 0.5
proc finish {} {
global ns nf tf
Page 49 of 80
$ns flush-trace
close $nf
close $tf
exec nam LAN.nam &
exit 0
}
$ns at 5.0 "finish"
$ns run

OUTPUT:

Page 50 of 80
RESULT:

Thus the TCL script for LAN simulation has been executed successfully.

Page 51 of 80
Ex No:12 Date:

SIMPLE WIRELESS NETWORK


AIM:

To write a tcl script to simulate a simple wireless network with DSDV,DSR and AODV
routing protocol

ALGORITHM:

1.start
2.set wireless channel,two ray ground,wireless phy,queue,queuelength and anteena
3.also set DSR,nodes number is 10 with speed 5
4.set dimenessions of x and y to 1000
5. set cp "seen1/scen10" and set cc to "scen1/cbr-op1
6.stop at 25 and size is 512 with rate of 100kb
7.set channel b and width 2.0e6
8.set new simulator and set nt open wireless-tr in write mode
9.set new tropography
10.create a channel chan_1 and create god
11.now config the adhoc routing
12.now create the nodes
13. set the initial node position
14. write the finish procedure
15. stop

PROGRAM:

set val(chan) Channel/WirelessChannel


set val(prop) Propagation/TwoRayGround
set val(netif) Phy/WirelessPhy
set val(mac) Mac/802_11
set val(ifq) Queue/DropTail/PriQueue
set val(ifqlen) 150
set val(ant) Antenna/OmniAntenna
set val(ll) LL
set val(rp) DSR
set val(nn) 50
set val(speed) 5
set val(x) 1000
set val(y) 1000
set val(cp) "./scen-1000x1000-N$val(nn)-S$val(speed)"
set val(cc) "./cbr-$val(nn)"
set val(stop) 25
set psize 512
set rate 100kb
Page 52 of 80
set channelBandwidth 2.0e6
Mac/802_11 set basicRate_ $channelBandwidth
Mac/802_11 set dataRate_ $channelBandwidth
set ns_ [new Simulator]
set nt [open wireless_tr.tr w]
$ns_ trace-all $nt
set nf [open wireless_nam.nam w]
$ns_ namtrace-all-wireless $nf $val(x) $val(y)
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
set chan_1 [new $val(chan)]
create-god $val(nn)
$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) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace OFF \
-channel $chan_1
puts "creating nodes...."
for {set i 0 } {$i<$val(nn)} {incr i} {
set node_($i) [$ns_ node]
$node_($i) random-motion 0
}
puts "loading random connection pattern...."
set god_ [God instance]
source $val(cp)
source $val(cc)
for {set i 0} {$i<$val(nn)} {incr i} {
$ns_ initial_node_pos $node_($i) 30
}
for {set i 0} {$i<$val(nn)} {incr i} {
$ns_ at $val(stop) "$node_($i) reset";
}
$ns_ at $val(stop) "finish"
$ns_ at $val(stop) "$ns_ trace-annotate\"simulation has ended\""
$ns_ at $val(stop) "puts\"NS EXITING...\":$ns_ halt"
proc finish {} {
global ns_ nt nf
Page 53 of 80
$ns_ flush-trace
close $nt
close $nf
exec nam wireless_nam.nam &
exit 0
}
puts "starting simulation...."
$ns_ run

OUTPUT:

num_nodes is set 50
creating nodes....
INITIALIZE THE LIST xListHead
loading random connection pattern....
starting simulation....
channel.cc:sendUp - Calc highestAntennaZ_ and distCST_
highestAntennaZ_ = 1.5, distCST_ = 550.0
SORTING LISTS ...DONE!

Page 54 of 80
RESULT:

Thus the TCL script to simulate a simple wireless network with DSDV routing
protocol has been executed successfully.

Page 55 of 80
Ex No:13 Date:

BLACKHOLE ATTACK

AIM:
To write the tcl program to create attackers from the existing protocol .

ALGORITHM:

1.start
2.to create a wireless netwsork with 5 nodes and AODV protocol
3. create a ns simulator
4.set gup topography object and open ns trace file and open nam trace file
5. now set up the mobile node parameter
6. now create 5 nodes
7.now assign color red to node2 and attacker
8.now assign color green to node0 and source
9. now assign color blue to node3 and destination
10.set up node n2 as an attacker
11.set up UDP connection
12.set CBR application over UDP connection
13.define a finish procedure
14.run the program
15.stop

PROGRAM:

#===================================

# Simulation parameters setup

#===================================

set val(chan) Channel/WirelessChannel ;# channel type

set val(prop) Propagation/TwoRayGround ;# radio-propagation model

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

set val(ll) LL ;# link layer type

set val(ant) Antenna/OmniAntenna ;# antenna model

Page 56 of 80
set val(ifqlen) 50 ;# max packet in ifq

set val(nn) 4 ;# number of mobilenodes

set val(rp) AODV ;# routing protocol

set val(x) 500 ;# X dimension of topography

set val(y) 500 ;# Y dimension of topography

set val(stop) 100.0 ;# time of simulation end

#===================================

# Initialization

#===================================

#Create a ns simulator

set ns [new Simulator]

#Setup topography object

set topo [new Topography]

$topo load_flatgrid $val(x) $val(y)

create-god $val(nn)

#Open the NS trace file

set tracefile [open blackhole.tr w]

$ns trace-all $tracefile

#Open the NAM trace file

set namfile [open blackhole.nam w]

$ns namtrace-all $namfile

$ns namtrace-all-wireless $namfile $val(x) $val(y)

set chan [new $val(chan)];#Create wireless channel

#===================================

# Mobile node parameter setup

Page 57 of 80
#===================================

$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) \

-channel $chan \

-topoInstance $topo \

-agentTrace ON \

-routerTrace ON \

-macTrace OFF \

-movementTrace ON

#===================================

# Nodes Definition

#===================================

#Create 7 nodes

set n0 [$ns node]

$n0 set X_ 99

$n0 set Y_ 299

$n0 set Z_ 0.0

$ns initial_node_pos $n0 20

set n1 [$ns node]

Page 58 of 80
$n1 set X_ 299

$n1 set Y_ 297

$n1 set Z_ 0.0

$ns initial_node_pos $n1 20

set n2 [$ns node]

$n2 set X_ 499

$n2 set Y_ 298

$n2 set Z_ 0.0

$ns initial_node_pos $n2 20

set n3 [$ns node]

$n3 set X_ 700

$n3 set Y_ 299

$n3 set Z_ 0.0

$ns initial_node_pos $n3 20

set n4 [$ns node]

$n4 set X_ 199

$n4 set Y_ 350

$n4 set Z_ 0.0

$ns initial_node_pos $n4 20

# Node 5 is given RED Color and a label- indicating it is a Blackhole Attacker

$n2 color red

$ns at 2.0 "$n2 color red"

$ns at 2.0 "$n2 label Attacker"

# Node 0 is given GREEN Color and a label - acts as a Source Node

$n0 color green

Page 59 of 80
$ns at 0.0 "$n0 color green"

$ns at 0.0 "$n0 label Source"

# Node 3 is given BLUE Color and a label- acts as a Destination Node

$n3 color blue

$ns at 0.0 "$n3 color blue"

$ns at 0.0 "$n3 label Destination"

#===================================

# Set node 5 as attacker

#===================================

$ns at 2.0 "[$n2 set ragent_] malicious"

#===================================

# Agents Definition

#===================================

#Setup a UDP connection

set udp0 [new Agent/UDP]

$ns attach-agent $n0 $udp0

set null1 [new Agent/Null]

$ns attach-agent $n3 $null1

$ns connect $udp0 $null1

$udp0 set packetSize_ 1500

#===================================

# Applications Definition

#===================================

#Setup a CBR Application over UDP connection

set cbr0 [new Application/Traffic/CBR]

Page 60 of 80
$cbr0 attach-agent $udp0

$cbr0 set packetSize_ 1000

$cbr0 set rate_ 0.1Mb

$cbr0 set random_ null

$ns at 1.0 "$cbr0 start"

$ns at 100.0 "$cbr0 stop"

#===================================

# Termination

#===================================

#Define a 'finish' procedure

proc finish {} {

global ns tracefile namfile

$ns flush-trace

close $tracefile

close $namfile

exec nam blackhole.nam &

exit 0

for {set i 0} {$i < $val(nn) } { incr i } {

$ns at $val(stop) "\$n$i reset"

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

$ns at $val(stop) "finish"

$ns at $val(stop) "puts \"done\" ; $ns halt"

$ns run

Page 61 of 80
OUTPUT:

RESULT:

Thus the TCL script for adding attacker to simulate Black Hole attack has been
executed successfully.

Page 62 of 80
Ex No:14 Date:

COMPARISION OF DIFFERENT ROUTING PROTOCOLS USING X-GRAPH

AIM:

To write a awk program for comparision of different routing protocols.

ALGORITHM:

1.start

2.Begin and declare drop,sent,recieved,throughput and initial to zero.

3.if $1 is send and $7 is cbr then increment sent.

4.if $1 is received and $7 is cbr then increment receive.

5.if $1 is drop and $7 is cbr then increment drop.

6.throughput=rec/sent.

7.print sent,received,drop,throughput values.

8.stop

PROGRAM:

AWK program:

BEGIN {
r=s=d=0
}
{
if ($4=="AGT" )
( $1=="r" ) ? ++r : ( $1=="D" ) ? ++d : ( $1=="s" ) ? ++s : true
}
END {
printf("Throughput=%f\n",r/s)
}

X-Graph Program:

TitleText: "number of nodes vs throughput"


XUnitText: "no of nodes"
YUnitText: "throughput"

Page 63 of 80
"DSDV"
10 0.150000
20 0.135417 Values Obtained
30 0.146341
40 0.291391
50 0.194595
"AODV"
10 0.439024
20 0.589474
30 0.632000
40 0.679348
50 0.600000
"DSR"
10 0.416667
20 0.800000
30 0.857143
40 0.800000
50 0.600000

OUTPUT:

Result:

Thus the comparison of different protocols performance using x graph is noted


successfully.

Page 64 of 80
ADVANCED LAB PROGRAMS

Page 65 of 80
Ex No: 15 Date:

DSDV-Destination Sequence Distance Vector Routing

AIM:
To study the throughput performance of DSDV in an wireless Ad hoc network
environment.

THEORY:
DSDV is a proactive table driven protocol. In which the all the nodes maintain a
routing table through which the packets are transmitted. The tables are forwarded if a
node observes a significant change in local topology. The table updates are of two types,
incremental updates and full dump An incremental update takes a single network data
packet unit (NDPU), while a full dump may take multiple NDPUs.
If a link breaks the weight is initiated as infinity and the update is made throughout
the network.
The availability of routes to all destinations at all times implies that much less delay
is involved in the route setup process. Another disadvantage of DSDV is that in order to
obtain information about a particular destination node, a node has to wait for a table
update message initiated by the same destination node.

PROCEDURE:
1. Set up a new simulator nam file and create new trace file.
2. Create 10 nodes which communicate in wireless mode for 78 sec.
3. Choose DSDV as a routing protocol.
4. Run the simulation.
5. Calculate the throughput using awk file.

PROGRAM:
set val(chan) Channel/WirelessChannel
set val(prop) Propagation/TwoRayGround
set val(netif) Phy/WirelessPhy
set val(mac) Mac/802_11
set val(ifq) Queue/DropTail/PriQueue
set val(ll) LL
set val(ant) Antenna/OmniAntenna
set val(ifqlen) 50
set val(nn) 10
set val(rp) DSDV
set val(x) 500
set val(y) 500

# Initialize Global Variables


set ns_ [new Simulator]
set tracefd [open dsdv.tr w]
Page 66 of 80
$ns_ trace-all $tracefd

set namtrace [open dsdv.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)

# New API to config node:


# 1. Create channel (or multiple-channels);
# 2. Specify channel in node-config (instead of channelType);
# 3. Create nodes for simulations.

# Create channel #1 and #2


set chan_1_ [new $val(chan)]
set chan_2_ [new $val(chan)]
set chan_3_ [new $val(chan)]
set chan_4_ [new $val(chan)]
set chan_5_ [new $val(chan)]
set chan_6_ [new $val(chan)]
set chan_7_ [new $val(chan)]
set chan_8_ [new $val(chan)]
set chan_9_ [new $val(chan)]
set chan_10_ [new $val(chan)]

# Create node(0) "attached" to channel #1


# configure node, please note the change below.
$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) \
-topoInstance $topo \
-agentTrace 0N \
-routerTrace ON \
-macTrace ON \
-movementTrace OFF \
-channel $chan_1_
Page 67 of 80
for {set i 0} {$i < 10} {incr i} {
set node_($i) [$ns_ node]
}

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


$node_($i) random-motion 0
}
for {set i 0} {$i < $val(nn)} {incr i} {
$ns_ initial_node_pos $node_($i) 20
}

#
# Provide initial (X,Y, for now Z=0) co-ordinates for mobilenodes
#

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


$node_($i) set X_ [expr 5.0+$i ]
$node_($i) set Y_ [expr 2.0+$i ]
$node_($i) set Z_ [expr 0.0+$i ]
}

# Now produce some simple node movements


# Node_(1) starts to move towards node_(0)
#
$ns_ at 3.0 "$node_(1) setdest 50.0 40.0 25.0"
$ns_ at 3.0 "$node_(0) setdest 48.0 38.0 5.0"
$ns_ at 3.0 "$node_(0) setdest 53.0 36.0 4.5"

# Node_(1) then starts to move away from node_(0)


$ns_ at 20.0 "$node_(1) setdest 490.0 480.0 30.0"

# Setup traffic flow between nodes


# UDP connections between node_(0) and node_(1)

#
# nodes: 10, max conn: 8, send rate: 0.25, seed: 1.0
#
#
# 1 connecting to 2 at time 2.5568388786897245
#
set udp_(0) [new Agent/UDP]
$ns_ attach-agent $node_(1) $udp_(0)
set null_(0) [new Agent/Null]
$ns_ attach-agent $node_(2) $null_(0)
set cbr_(0) [new Application/Traffic/CBR]
Page 68 of 80
$cbr_(0) set packetSize_ 512
$cbr_(0) set interval_ 0.25
$cbr_(0) set random_ 1
$cbr_(0) set maxpkts_ 10000
$cbr_(0) attach-agent $udp_(0)
$ns_ connect $udp_(0) $null_(0)
$ns_ at 2.5568388786897245 "$cbr_(0) start"
#
# 4 connecting to 5 at time 56.333118917575632
#
set udp_(1) [new Agent/UDP]
$ns_ attach-agent $node_(4) $udp_(1)
set null_(1) [new Agent/Null]
$ns_ attach-agent $node_(5) $null_(1)
set cbr_(1) [new Application/Traffic/CBR]
$cbr_(1) set packetSize_ 512
$cbr_(1) set interval_ 0.25
$cbr_(1) set random_ 1
$cbr_(1) set maxpkts_ 10000
$cbr_(1) attach-agent $udp_(1)
$ns_ connect $udp_(1) $null_(1)
$ns_ at 56.333118917575632 "$cbr_(1) start"
#
# 4 connecting to 6 at time 146.96568928983328
#
set udp_(2) [new Agent/UDP]
$ns_ attach-agent $node_(4) $udp_(2)
set null_(2) [new Agent/Null]
$ns_ attach-agent $node_(6) $null_(2)
set cbr_(2) [new Application/Traffic/CBR]
$cbr_(2) set packetSize_ 512
$cbr_(2) set interval_ 0.25
$cbr_(2) set random_ 1
$cbr_(2) set maxpkts_ 10000
$cbr_(2) attach-agent $udp_(2)
$ns_ connect $udp_(2) $null_(2)
$ns_ at 146.96568928983328 "$cbr_(2) start"
#
# 6 connecting to 7 at time 55.634230382570173
#
set udp_(3) [new Agent/UDP]
$ns_ attach-agent $node_(6) $udp_(3)
set null_(3) [new Agent/Null]
$ns_ attach-agent $node_(7) $null_(3)
set cbr_(3) [new Application/Traffic/CBR]
$cbr_(3) set packetSize_ 512
Page 69 of 80
$cbr_(3) set interval_ 0.25
$cbr_(3) set random_ 1
$cbr_(3) set maxpkts_ 10000
$cbr_(3) attach-agent $udp_(3)
$ns_ connect $udp_(3) $null_(3)
$ns_ at 55.634230382570173 "$cbr_(3) start"
#
# 7 connecting to 8 at time 29.546173154165118
#
set udp_(4) [new Agent/UDP]
$ns_ attach-agent $node_(7) $udp_(4)
set null_(4) [new Agent/Null]
$ns_ attach-agent $node_(8) $null_(4)
set cbr_(4) [new Application/Traffic/CBR]
$cbr_(4) set packetSize_ 512
$cbr_(4) set interval_ 0.25
$cbr_(4) set random_ 1
$cbr_(4) set maxpkts_ 10000
$cbr_(4) attach-agent $udp_(4)
$ns_ connect $udp_(4) $null_(4)
$ns_ at 29.546173154165118 "$cbr_(4) start"
#
# 7 connecting to 9 at time 7.7030203154790309
#
set udp_(5) [new Agent/UDP]
$ns_ attach-agent $node_(7) $udp_(5)
set null_(5) [new Agent/Null]
$ns_ attach-agent $node_(9) $null_(5)
set cbr_(5) [new Application/Traffic/CBR]
$cbr_(5) set packetSize_ 512
$cbr_(5) set interval_ 0.25
$cbr_(5) set random_ 1
$cbr_(5) set maxpkts_ 10000
$cbr_(5) attach-agent $udp_(5)
$ns_ connect $udp_(5) $null_(5)
$ns_ at 7.7030203154790309 "$cbr_(5) start"
#
# 8 connecting to 9 at time 20.48548468411224
#
set udp_(6) [new Agent/UDP]
$ns_ attach-agent $node_(8) $udp_(6)
set null_(6) [new Agent/Null]
$ns_ attach-agent $node_(9) $null_(6)
set cbr_(6) [new Application/Traffic/CBR]
$cbr_(6) set packetSize_ 512
$cbr_(6) set interval_ 0.25
Page 70 of 80
$cbr_(6) set random_ 1
$cbr_(6) set maxpkts_ 10000
$cbr_(6) attach-agent $udp_(6)
$ns_ connect $udp_(6) $null_(6)
$ns_ at 20.48548468411224 "$cbr_(6) start"
#
# 9 connecting to 10 at time 76.258212521792487
#
set udp_(7) [new Agent/UDP]
$ns_ attach-agent $node_(9) $udp_(7)
set null_(7) [new Agent/Null]
$ns_ attach-agent $node_(8) $null_(7)
set cbr_(7) [new Application/Traffic/CBR]
$cbr_(7) set packetSize_ 512
$cbr_(7) set interval_ 0.25
$cbr_(7) set random_ 1
$cbr_(7) set maxpkts_ 10000
$cbr_(7) attach-agent $udp_(7)
$ns_ connect $udp_(7) $null_(7)
$ns_ at 76.258212521792487 "$cbr_(7) start"
#
#Total sources/connections: 6/8
#

# Tell nodes when the simulation ends


#
for {set i 0} {$i < $val(nn) } {incr i} {
$ns_ at 30.0 "$node_($i) reset";
}
$ns_ at 78.0 "stop"
$ns_ at 78.01 "puts \"NS EXITING...\" ; $ns_ halt"
proc stop {} {
global ns_ tracefd namtrace
$ns_ flush-trace
close $tracefd
close $namtrace

exec nam dsdv.nam &


exit 0
}

puts "Starting Simulation..."


$ns_ run
Scenario:

Page 71 of 80
SCREEN SHOT:

RESULT:

The DSDV routing protocol is successfully implemented in an 10 node based system in


ns2 and the trace file is generated.

Page 72 of 80
Ex No: 16 Date:

MAC PROTOCOL - ALOHA


AIM:
To implement the Aloha scenario in a network simulator.

INTRODUCTION:
MAC-ALOHA:
Aloha refers to a simple communication scheme in which each source (transmitter)
in a network sends data whenever there is a frame to send. If the frame successfully
reaches the destination (receiver), the next frame is sent. If the frame fails to be received at
the destination, it is sent again.

TYPES OF ALOHA
 PURE ALOHA
With Pure Aloha, stations are allowed access to the channel whenever they have
data to transmit. Because the threat of data collision exists, each station must either
monitor its transmission on the rebroadcast or await an acknowledgment from the
destination station. By comparing the transmitted packet with the received packet
or by the lack of an acknowledgement, the transmitting station can determine the
success of the transmitted packet. If the transmission was unsuccessful it is resent
after a random amount of time to reduce the probability of re-collision.
 SLOTTED ALOHA
Assuming constant length packets, transmission time is broken into slots equivalent
to the transmission time of a single packet. Stations are only allowed to transmit at
slot boundaries. When packets collide they will overlap completely instead of
partially. This has the effect of doubling the efficiency of the Aloha protocol and has
come to be known as Slotted Aloha.

 R-ALOHA(RESERVATION ALOHA)
This technique is sometimes combined with TDMA system to form the so called
reservation ALOHA protocol. In this protocol the time slot is divided into contention
periods and contention free periods. During the contention interval , an MS use very
short packets to contended for the upcoming contention free interval that will be
used for transmission of long information packets.

Need for ALOHA in Wireless Network


Aloha works better in a wireless broadcast system or a half-duplex two-way link.
But as networks become more complex, for example in an Ethernet system involving
multiple sources and destinations in which data travels many paths at once, trouble occurs
because data frames collide (conflict). Enhancement of Communication volume worsens
the collision problems. The result is degradation of system efficiency, because when two
frames collide, the data contained in both frames is lost.

Page 73 of 80
PROCEDURE:

1. Create new simulation scenario with 6 nodes of simulation time 125 sec.
2. Choose aloha as MAC protocol.
3. Connect the link between node 3 and node 4 using Mac aloha protocol.
4. Connect the link between node 0 and node 4 where FTP is applied over TCP
connection.
5. Connect the link between node 1 and node 5 with UDP connection.
6. Run the scenario.

PROGRAM:

set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the Trace files


set file1 [open csma.tr w]
set winfile [open WinFile w]
$ns trace-all $file1

#Open the NAM trace file


set file2 [open out.nam w]
$ns namtrace-all $file2

#Define a 'finish' procedure


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

#Create six nodes


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

$n1 color red


Page 74 of 80
$n1 shape box

#Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
$ns duplex-link $n3 $n4 0.3Mb 100ms DropTail
$ns duplex-link $n3 $n5 0.3Mb 100ms DropTail

set lan [$ns newLan "$n3 $n4" 0.5Mb 40ms LL Queue/DropTail MAC/Sat/Unslotted Aloha
Channel]

#Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns simplex-link-op $n2 $n3 orient right
$ns simplex-link-op $n3 $n2 orient left
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

#Set Queue Size of link (n2-n3) to 10


# $ns queue-limit $n2 $n3 20

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552

#Setup a FTP over TCP connection


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

#Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_ 2
Page 75 of 80
#Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false

$ns at 0.1 "$cbr start"


$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the
# tcp source node, will be called here "tcp",
# and the name of output file.

$ns at 125.0 "finish"


$ns run

SCREENSHOT:

RESULT:
Thus the MAC- Aloha scenario was implemented successfully in a 6 node system
and trace file is generated.

Page 76 of 80
Ex No: 17 Date:

MAC PROTOCOL – CSMA


AIM:
In order to study the performance of CSMA protocol

INTRODUCTION:
MAC-CSMA:
Carrier Sense Multiple Access (CSMA) is a media access control (MAC) protocol in
which a node verifies the absence of other traffic before transmitting on a shared
transmission medium.

TYPES OF CSMA:
1-PERSISTENT CSMA
When the sender is ready to transmit data, it checks if the physical medium is busy. If
so, it senses the medium continually until it become idle, and then it transmits a pieces of
data, In case of a collision, the sender ewais for a random period of time and attempts to
transmit again.
P- PERSISTENT CSMA
This protocol is a generalization of 1-persisten CSMA. When the sender is ready to
send data, it checks continually if the medium is busy. If the medium becomes idle, the
sender transmits a frame with a probability p. In case the transmission did not happen the
sender waits until the next available time slot and transmits again with the same
probability p. This process repeats until the frame is sent or some other sender starts
transmitting.
NON PERSISTENT CSMA
This protocol Sense the channel if it is busy then it waits for a random amount of time
and sense the channel again if the channel is idle then it will transmit a packet immediately.
If collision occurs then it will wait for a random amount of time and then the frames are
transmitted.

NEED FOR CSMA IN WIRELESS NETWORK


A major challenge in the field of wireless communications in spatially distributed
networks is sharing the medium and the available resources in a distributed manner.
Sharing the medium has the adherent problem of interference, which may lead to
erroneous reception of packets. We consider nodes that are randomly distributed in space
and address the problem of interference through the MAC layer design, which is an
essential source of efficient resource allocation. The MAC protocol CSMA are applied for
the communication between transmitters and receivers , and we investigate how often the
packets are received successfully.

Page 77 of 80
PROCEDURE:
1. Create new simulation scenario with routing with 6 nodes of simulation time 125 sec.
2. Choose CSMA as MAC protocol.
3. Choose node 3 and node 5 and start the routing between these two nodes.
4. Run the scenario.

PROGRAM:

set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the Trace files


set file1 [open csma.tr w]
set winfile [open WinFile w]
$ns trace-all $file1

#Open the NAM trace file


set file2 [open out.nam w]
$ns namtrace-all $file2

#Define a 'finish' procedure


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

#Create six nodes


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

$n1 color red


$n1 shape box

#Create links between the nodes


$ns duplex-link $n0 $n1 2Mb 10ms DropTail
Page 78 of 80
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns simplex-link $n1 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n1 0.3Mb 100ms DropTail
$ns simplex-link $n2 $n4 0.3Mb 100ms DropTail
$ns simplex-link $n4 $n2 0.3Mb 100ms DropTail
$ns duplex-link $n3 $n5 0.3Mb 100ms DropTail
$ns duplex-link $n4 $n5 0.3Mb 100ms DropTail

set lan [$ns newLan "$n3 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]

#Give node position (for NAM)


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

#$ns duplex-link-op $n4 $n5 orient right-up


#$ns simplex-link-op $n1 $n3 orient right
#$ns simplex-link-op $n3 $n1 orient left
#$ns duplex-link-op $n3 $n5 orient right-down
#$ns simplex-link-op $n2 $n4 orient right
#$ns simplex-link-op $n4 $n2 orient left
#$ns duplex-link-op $n4 $n5 orient right-up

#Set Queue Size of link (n2-n3) to 10


# $ns queue-limit $n2 $n3 20

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552

#Setup a FTP over TCP connection


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

#Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
Page 79 of 80
$udp set fid_ 2

#Setup a CBR over UDP connection


set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false

$ns at 0.1 "$cbr start"


$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"

# next procedure gets two arguments: the name of the


# tcp source node, will be called here "tcp",
# and the name of output file.

$ns at 125.0 "finish"


$ns run

SCREEN SHOT:

RESULT:
Thus the MAC-CSMA is implemented in a 6 node based system and its trace file is
generated.

Page 80 of 80

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy