You are on page 1of 80

Networks Simulation Laboratory

INSTRUCTIONS TO THE STUDENTS

1. The student must carry this manual to every laboratory session.

2. In every laboratory session, each problem solution is explained.

3. Programs and exercise problems must be executed with in the current lab
session.

4. Each lab session is evaluated for 20 marks.

5. The programs executed must be written in a lab observation note book and is
evaluated for maximum marks of 10 in the same session.

6. The record is evaluated for maximum marks of 10 if submitted in the next


laboratory session. Otherwise will be evaluated for 5 marks

7. In-time submission i.e. completion in the current session yields 100 % marks,
otherwise will be evaluated for 50% marks.

8. The laboratory record must consist of

i. Code for the programs executed in the laboratory session

ii. Exercise problems.

iii. Answers to the viva-voce questions.

9. Any incompletion of the lab record results into fewer marks.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Course Learning Objectives (LO):

This laboratory will develop students‟ knowledge in/on

LO1: Java network programming, client/server application using TCP/IP and


simulation of network topology using Tcl script
LO2: open source network simulator NS2 for analyzing TCP/UDP traffic analysis
and routing protocols
LO3: different types of queues, behavior of variants in TCP wired network and
wireless network consisting of TCP/IP traffic
LO4: performance evaluation of Dynamic Source Routing(DSR), Destination-
Sequenced Distance- Vector(DSDV) and Ad hoc On-Demand Distance Vector
Routing(AODV)

Course Learning Outcomes (CO):

Upon completion of this laboratory, students will be able to

CO1: develop Java network programming for client/server networking and use Tcl
script for network topology
CO2: implement working procedure of TCP/UDP agents using ACK packets and
construct route with various nodes in wired network environment
CO3: simulate wired network and wireless network using NS2 tool and describe
different queues, buffer types supported in NS2 tool
CO4: compare the performance of DSR, DSDV and AODV algorithms

Grading:

Continuous Internal Evaluation (CIE) : 40 Marks

End Semester Examination (ESE) : 60 Marks

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

List of Experiments
Experiment-I
1. Java network programming:
a. Processing internet address.
b. Applications with TCP and UDP sockets.

Experiment-II
2. Implement TCP/IP client and server technology using JAVA network
programming.

Experiment-III
3. Simulate a sample network topology using Tcl script.

Experiment-IV
4. Familiarizing network simulator–2(NS2) environment.

Experiment-V
5. Simulate a wired network consisting of TCP and UDP traffic using NS2 and then
calculate their respective throughput using AWK script.

Experiment-VI
6. Performance evaluation of different routing protocols in wired network
environment using NS2.

Experiment-VII
7. Performance evaluation of different queues, effect of queues and buffers in wired
network environment using NS2.

Experiment-VIII
8. Compare the behavior of different variants of TCP (Tahoe, Reno, Vegas etc.) in
wired network using NS2. Compare the congestion window behavior by plotting
graph.

Experiment-IX
9. Simulation of wireless ad hoc networks using NS2.

Experiment-X
10. Performance evaluation of DSR ad-hoc wireless routing protocols using NS2.

Experiment-XI
11. Performance evaluation of DSDV ad-hoc wireless routing protocols using NS2.

Experiment-XII
12. Performance evaluation of AODV ad-hoc wireless routing protocols using NS2.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-I

OBJECTIVE:
This Lab Session will develop student's knowledge in
 Writing code to access internet addresses using network programming in
Java

OUTCOME:

Upon completion of this lab, students will be able to


 Write Java program for getting IP address of the machine which is connected
in the network and vice versa.

1. Java network programming:


a. Processing internet address.

Processing Internet Address:

InetAddress address = InetAddress.getByName("www.Google.com");

This method does not merely set a private String field in the InetAddress class. It


actually makes a connection to the local DNS server to look up the name and the
numeric address. If the DNS server can’t find the address, this method throws
an UnknownHostException, a subclass of IOException.

Program:
import java.io.*;
import java.net.*;

public class GoogleByName {

public static void main (String[] args) {


try
{
InetAddress address = InetAddress.getByName("www.Google.com");
System.out.println(address);
}
catch (UnknownHostException ex)
{
System.out.println("Could not find www.google.com");
}
}
}

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

You can also do a reverse lookup by IP address. For example, if you want the
hostname for the address 208.201.239.100, pass the dotted quad address
to InetAddress.getByName():
InetAddress address = InetAddress.getByName("208.201.239.100");
System.out.println(address.getHostName());

If the address you look up does not have a hostname, getHostName() simply returns


the dotted quad address you supplied.

try {

InetAddress[] addresses = InetAddress.getAllByName("www.oreilly.com");

for (InetAddress address : addresses) {

System.out.println(address);

} catch (UnknownHostException ex) {

System.out.println("Could not find www.oreilly.com");

Finally, the getLocalHost() method returns an InetAddress object for the host on


which your code is running:
InetAddress me = InetAddress.getLocalHost();

This method tries to connect to DNS to get a real hostname and IP address such as
“elharo.laptop.corp.com” and “192.1.254.68”; but if that fails it may return
the loopback address instead. This is the hostname “localhost” and the dotted quad
address “127.0.0.1”.

Example. Find the address of the local machine

import java.net.*;

public class MyAddress

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

{
public static void main (String[] args)
{

try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
}
catch (UnknownHostException ex)
{
System.out.println("Could not find this computer's address.");
}
}
}

Here’s the output; I ran the program on titan.oit.unc.edu:

% java MyAddress
titan.oit.unc.edu/152.2.22.14

Whether you see a fully qualified name like titan.oit.unc.edu or a partial name


like titan depends on what the local DNS server returns for hosts in the local
domain. If you’re not connected to the Internet, and the system does not have a fixed
IP address or domain name, you’ll probably see localhost as the domain name and
127.0.0.1 as the IP address.

If you know a numeric address, you can create an InetAddress object from that
address without talking to DNS using InetAddress.getByAddress(). This method can
create addresses for hosts that do not exist or cannot be resolved:

public static InetAddress getByAddress(byte[] addr) throws


UnknownHostException
public static InetAddress getByAddress(String hostname, byte[] addr)
throws UnknownHostException

The first InetAddress.getByAddress() factory method creates an InetAddress object


with an IP address and no hostname.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

The second InetAddress.getByAddress() method creates an InetAddress object with


an IP address and a hostname.

For example, this code fragment makes an InetAddress for 107.23.216.196:

byte[] address = {107, 23, (byte) 216, (byte) 196};


InetAddress lessWrong = InetAddress.getByAddress(address);
InetAddress lessWrongWithname = InetAddress.getByAddress(
"lesswrong.com", address);

Reference:https://www.oreilly.com/library/view/java-network-programming/9781449365936
/ch04.html

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

INTRODUCTION TO SOCKET PROGRAMMING


Java Sockets
The socket API in Java is provided in the java.net package which has several classes
supporting socket-based client/server communication.

Java Net Package


Client and server sockets for connection-oriented and connectionless
communication are implemented by the Socket, ServerSocket, DatagramSocket, and
MulticastSocket classes in the java.net package. In addition to these socket related
classes, the java.net package also contains other classes that can help the
communication.

In particular, the InetAddress class encapsulates Internet IP addresses and supports


conversion between dotted decimal addresses and host names.

The DatagramPacket class is used to construct UDP datagram packets. The


SocketImpl and DatagramSocketImpl classes and the SocketImplFactory interface
provide hooks for implementing custom sockets.

High-level browser-server Web connections are implemented through the URL,


URLConnection, HttpURLConnection, and URLEncoder classes. The
ContentHandler and URLStreamHandler classes are abstract classes that can be
used for the implementation of Web content and stream handlers. They are
supported by the ContentHandlerFactory and URLStreamHandlerFactory
interfaces. The FileNameMap interface is used to map filenames to MIME types.

The classes in the java.net package can be listed as follows:

The Classes
ContentHandler
DatagramPacket

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

DatagramSocket
DatagramSocketImpl
HttpURLConnection
InetAddress
MulticastSocket
ServerSocket
Socket
SocketImpl
URL
URLConnection
URLEncoder
URLStreamHandler
The Interfaces
ContentHandlerFactory
FileNameMap
SocketImplFactory
URLStreamHandlerFactory
Exceptions
BindException
ConnectException
MalformedURLException
NoRouteToHostException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException

Java Socket Programming:

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Java Socket programming is used for communication between the applications


running on different JRE. Java Socket programming can be connection-oriented or
connection-less.

Socket and ServerSocket classes are used for connection-oriented socket


programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.

The client in socket programming must know two details:


1. IP Address of Server, and
2. Port number.
CLIENT SIDE PROGRAMMING

Establish a Socket Connection


To connect to other machine we need a socket connection. A socket connection
means the two machines have information about each other’s network location (IP
Address) and TCP port. The java.net.Socket class represents a Socket. To open a
socket:

Socket socket = new Socket(“127.0.0.1”, 5000)


 First argument – IP address of Server. ( 127.0.0.1  is the IP address of local-
host, where code will run on single stand-alone machine).
 Second argument – TCP Port. (Just a number representing which application
to run on a server. For example, HTTP runs on port 80. Port number can be
from 0 to 65535)

Communication
To communicate over a socket connection, streams are used to both input and out-
put the data.
Closing the connection
The socket connection is closed explicitly once the message to server is sent.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

SERVER PROGRAMMING

Establish a Socket Connection


To write a server application two sockets are needed.
 A ServerSocket which waits for the client requests (when a client makes a
new Socket())
 A plain old Socket s to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing the socket as well as
input/output streams.

Socket programming boils down to two systems communicating with one another.
Generally, network communication comes in two flavors: Transport Control
Protocol (TCP) and User Datagram Protocol (UDP).

TCP and UDP are used for different purposes and both have unique constraints:

TCP is relatively simple and reliable protocol that enables a client to make a
connection to a server and the two systems to communicate. In TCP, each entity
knows that its communication payloads have been received.

UDP is a connectionless protocol and is good for scenarios where you do not
necessarily need every packet to arrive at its destination, such as media streaming.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-I

1 (b). Java network programming: Applications with TCP and UDP sockets.

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing code to establish communication between server and client with TCP
connectivity using Socket Programming in Java

OUTCOME:
Upon completion of this lab, students will be able to
 write Java program for establishing communication between server and
clients with TCP connectivity using Socket Programming.

MyClient.java
import java.io.*;
import java.net.*;
public class MyClient{
public static void main(String[] args){
try
{
Socket s=new Socket("localhost",6666);
OutputStreamWriter dout=new OutputStreamWriter(s.getOutputStream());
PrintWriter out=new PrintWriter(dout);
dout.write("hellllllooooo");
dout.flush();
dout.close();
s.close();
}
catch(Exception e) {System.out.println(e);}
}
}

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

MyServer.java
import java.io.*;
import java.io.BufferedReader;
import java.net.*;
public class MyServer{
public static void main(String[] args){
try
{
System.out.println("Server Started... ");
ServerSocket ss=new ServerSocket(6666);

System.out.println("Server is waiting for client... ");


Socket s=ss.accept();

System.out.println("Client connected ... ");


BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str=br.readLine();
System.out.println("My Message is "+str);
ss.close();
}
catch(Exception e) {System.out.println(e);}
}
}

Output

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

EXERCISE:
1. Write Java program to establish one-way communication in a network where
many clients send data to server with TCP connectivity.

VIVA-VOCE:
a) What is a Socket and socket programming?
b) Which class of Java is responsible to create sockets at server side?
c) Explain the class OutputStreamWriter.
d) Explain the class BufferedReader.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-II

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing code to for chat application between server and client with TCP
connectivity using Socket Programming in Java

OUTCOME:
Upon completion of this lab, students will be able to
 write Java program for establishing 2 way chat between server and client
with TCP connectivity using Socket Programming.

2. Implement TCP/IP client and server technology using JAVA network


programming.

MyClient.java
import java.io.*;
import java.net.*;
public class MyClient{
public static void main(String[] args){
try
{
Socket s=new Socket("localhost",6666);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String msgin="",msgout="";
while(!msgin.equals("end"))
{
msgout=br.readLine();
dout.writeUTF(msgout);
msgin=din.readUTF();
System.out.println(msgin);
}
}
catch(Exception e) {System.out.println(e);}
}
}

MyServer.java
import java.net.*;
public class MyServer{
public static void main(String[] args){
try
{
System.out.println("Server Started... ");
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

String msgin="",msgout="";
while(!msgin.equals("end"))
{
msgin=din.readUTF();
System.out.println(msgin);
msgout=br.readLine();
dout.writeUTF(msgout);
dout.flush();
}
}
catch(Exception e) {System.out.println(e);}
}
}

Output

VIVA-VOCE:
a) Describe DataInputStream class and all operations of it.
b) Describe DataOutputStream class and all operations of it.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-II
OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing code to for communication between server and client with UDP
connectivity

OUTCOME:
Upon completion of this lab, students will be able to
 establish communication between server and client with UDP connectivity
using Socket Programming.

2 (b). Write Java program to establish one-way communication in a network where


a single client sends some data and server receives using UDP connectivity.

UDPC.java
import java.io.*;
import java.net.*;
class UDPC
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser=new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length,IPAddress,9876);
clientSocket.send(sendPacket);
}
}

UDPS.java
import java.io.*;
import java.net.*;
class UDPS
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];

while(true)

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

{
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
}
}
}

Output

Experiment-III

OBJECTIVE:

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

This Lab Session will develop student's knowledge in


 writing tcl scripts for simulate the sample networks.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate different types of networks using tcl scripts.

3. Simulate a sample network topology using Tcl script.

This network consists of 4 nodes (n0, n1, n2, n3) as shown in above figure. The duplex links
between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The
duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each node
uses a DropTail queue, of which the maximum size is 10. A "tcp" agent is attached to n0, and
a connection is established to a tcp "sink" agent attached to n3. As default, the maximum
size of a packet that a "tcp" agent can generate is 1KByte. A tcp "sink" agent generates and
sends ACK packets to the sender (tcp agent) and frees the received packets. A "udp" agent
that is attached to n1 is connected to a "null" agent attached to n3. A "null" agent just frees
the packets received. A "ftp" and a "cbr" traffic generator are attached to "tcp" and "udp"
agents respectively, and the "cbr" is configured to generate 1 KByte packets at the rate of 1
Mbps. The "cbr" is set to start at 0.1 sec and stop at 4.5 sec, and "ftp" is set to start at 1.0 sec
and stop at 4.0 sec.

#Program: sample.tcl

# Create a simulator object


set ns [new Simulator]
  
# Define different colors 
# for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
  
# Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf
  
# Define a 'finish' procedure
proc finish {} {
    global ns nf
    $ns flush-trace
      

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

    # Close the NAM trace file


    close $nf
      
    # Execute NAM on the trace file
    exec nam out.nam &
    exit 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 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
  
# Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 10
  
# Give node position (for NAM)
$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 for link (n2-n3). (for NAM)
$ns duplex-link-op $n2 $n3 queuePos 0.5
    
# Setup a TCP connection
set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
  
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
  

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

# 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 $n3 $null
$ns connect $udp $null
$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_ 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 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"
  
# Detach tcp and sink agents
# (not really necessary)
$ns at 4.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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns run

Output:

Viva Voce:
1. How to connect nodes?
2. Show the syntax of Setup a FTP over TCP connection.

Introduction about NS2

NS2 INSTALLATION ON UBUNTU 16.04

1) Download 'ns-allinone-2.35' from :
  http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.35/ns-allinone-
2.35.tar.gz/download

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

2) Extract the downloaded zip file 'ns-allinone-2.35.tar.gz file' to desktop.

3) Now you need to download some essential packages for ns2,these packages can be
downloaded by using the following commands : applications>accessories>terminal or
dashhome>terminal then type the below lines one by one on the terminal window

    "sudo apt-get update"


    "sudo apt-get dist-upgrade"
    "sudo apt-get update"
    "sudo apt-get gcc"
    "sudo apt-get install build-essential autoconf automake"
    "sudo apt-get install tcl8.5-dev tk8.5-dev"
    "sudo apt-get install perl xgraph libxt-dev libx11-dev libxmu-dev"

4) Now change your directory(here i have already extracted the downloaded files to
desktop,so my location is desktop) type the following codes in the command window to
install NS2.

    cd Desktop  
    cd ns-allinone-2.35
    ./install

                              The installation procedure will take a few minutes..........

5) After compleating the installation type the following command in the command window

    gedit ~/.bashrc

6) Now an editor window appears,please copy and paste the follwing codes in the end of
the text file (note that '/home/abhiram/Desktop/ns-allinone-2.35/octl-1.14' in each line in
the below code should be replaced with your location where the 'ns-allinone-2.35.tar.gz'file
is extracted)

# LD_LIBRARY_PATH
OTCL_LIB=/home/abhiram/Desktop/ns-allinone-2.35/otcl-1.14
NS2_LIB=/home/abhiram/Desktop/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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

# TCL_LIBRARY
TCL_LIB=/home/abhiram/Desktop/ns-allinone-2.35/tcl8.5.10/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB

# PATH
XGRAPH=/home/abhiram/Desktop/ns-allinone-2.35/bin:/home/abhiram/Desktop/ns-
allinone-2.35/tcl8.5.10/unix:/home/abhiram/Desktop/ns-allinone-2.35/tk8.5.10/unix
NS=/home/abhiram/Desktop/ns-allinone-2.35/ns-2.35/
NAM=/home/abhiram/Desktop/ns-allinone-2.35/nam-1.15/
PATH=$PATH:$XGRAPH:$NS:$NAM

7) Save and close the text editor and then type the following command on the terminal

    source ~/.bashrc

8) Close the terminal window and start a new terminal window and now change the
directory to ns-2.35 and validate ns-2.35 by exicuting the following command ( it takes 30 to
45 minutes)

    cd ns-2.35
    ./validate

9) If the installation is successful, then you will be able to see % at the command prompt
while typing the following command

    ns

10) Now type

    exit

In general, an NS script starts with making a Simulator object instance.

 set ns [new Simulator]: generates an NS simulator object instance, and assigns


it to variable ns (italics is used for variables and values in this section). What
this line does is the following:
 
o Initialize the packet format (ignore this for now)
o Create a scheduler (default is calendar scheduler)
o Select the default address format (ignore this for now)

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

 The "Simulator" object has member functions that do the following:


 
o Create compound objects such as nodes and links (described later)
o Connect network component objects created (ex. attach-agent)
o Set network component parameters (mostly for compound objects)
o Create connections between agents (ex. make connection between a
"tcp" and "sink")
o Specify NAM display options
o Etc.
 
Most of member functions are for simulation setup (referred to as plumbing
functions in the Overview section) and scheduling, however some of them
are for the NAM display. The "Simulator" object member function
implementations are located in the "ns-2/tcl/lib/ns-lib.tcl" file.

 
 $ns color fid color: is to set color of the packets for a flow specified by the flow
id (fid). This member function of "Simulator" object is for the NAM display,
and has no effect on the actual simulation.
 
 $ns namtrace-all file-descriptor: This member function tells the simulator to
record simulation traces in NAM input format. It also gives the file name that
the trace will be written to later by the command $ns flush-trace. Similarly,
the member function trace-all is for recording the simulation trace in a gen-
eral format.
 
 proc finish {}: is called after this simulation is over by the command $ns at 5.0
"finish". In this function, post-simulation processes are specified.
 
 set n0 [$ns node]: The member function node creates a node. A node in NS is
compound object made of address and port classifiers (described in a later
section). Users can create a node by separately creating an address and a port
classifier objects and connecting them together. However, this member func-
tion of Simulator object makes the job easier. To see how a node is created,
look at the files: "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-node.tcl".
 
 $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex
links of specified bandwidth and delay, and connects the two specified nodes.
In NS, the output queue of a node is implemented as a part of a link, therefore
users should specify the queue-type when creating links. In the above simula-

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

tion script, DropTail queue is used. If the reader wants to use a RED queue,
simply replace the word DropTail with RED. The NS implementation of a
link is shown in a later section. Like a node, a link is a compound object, and
users can create its sub-objects and connect them and the nodes. Link source
codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl"
files. One thing to note is that you can insert error modules in a link compo-
nent to simulate a lossy link (actually users can make and insert any network
objects). Refer to the NS documentation to find out how to do this.

 
 $ns queue-limit node1 node2 number: This line sets the queue limit of the two
simplex links that connect node1 and node2 to the number specified. At this
point, the authors do not know how many of these kinds of member func-
tions of Simulator objects are available and what they are. Please take a look
at "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl", or NS documenta-
tion for more information.
 
 $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the
NAM display. To see the effects of these lines, users can comment these lines
out and try the simulation.


Now that the basic network setup is done, the next thing to do is to setup traffic
agents such as TCP and UDP, traffic sources such as FTP and CBR, and attach them
to nodes and agents respectively.

 set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in


general, users can create any agent or traffic sources in this way. Agents and
traffic sources are in fact basic objects (not compound objects), mostly imple-
mented in C++ and linked to OTcl. Therefore, there are no specific Simulator
object member functions that create these object instances. To create agents or
traffic sources, a user should know the class names these objects (Agent/TCP,
Agnet/TCPSink, Application/FTP and so on). This information can be found
in the NS documentation or partly in this documentation. But one shortcut is
to look at the "ns-2/tcl/libs/ns-default.tcl" file. This file contains the default
configurable parameter value settings for available network objects. There-
fore, it works as a good indicator of what kind of network objects are avail-
able in NS and what are the configurable parameters.
 

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

 $ns attach-agent node agent: The attach-agent member function attaches an


agent object created to a node object. Actually, what this function does is call
the attach member function of specified node, which attaches the given agent
to itself. Therefore, a user can do the same thing by, for example, $n0 attach
$tcp. Similarly, each agent object has a member function attach-agent that at-
taches a traffic source object to itself.
 
 $ns connect agent1 agent2: After two agents that will communicate with each
other are created, the next thing is to establish a logical network connection
between them. This line establishes a network connection by setting the desti-
nation address to each others' network and port address pair.


Assuming that all the network configuration is done, the next thing to do is write a
simulation scenario (i.e. simulation scheduling). The Simulator object has many
scheduling member functions. However, the one that is mostly used is the
following:

 $ns at time "string": This member function of a Simulator object makes the


scheduler (scheduler_ is the variable that points the scheduler object created
by [new Scheduler] command at the beginning of the script) to schedule the
execution of the specified string at given simulation time. For exam-
ple, $ns at 0.1 "$cbr start" will make the scheduler call a start member function
of the CBR traffic source object, which starts the CBR to transmit data. In NS,
usually a traffic source does not transmit actual data, but it notifies the under-
lying agent that it has some amount of data to transmit, and the agent, just
knowing how much of the data to transfer, creates packets and sends them.

After all network configuration, scheduling and post-simulation procedure


specifications are done, the only thing left is to run the simulation. This is done
by $ns run.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-IV

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing tcl scripts in NS2 for simulate the sample networks.

OUTCOME:
Upon completion of this lab, students will be able to
 learn how to set up nodes and links, how to send data from one node to another,
how to monitor a queue and how to start nam from your simulation script to
visualize your simulation.

4. Familiarizing network simulator–2(NS2) environment.

1. How to start
Now we are going to write a 'template' that you can use for all of the first Tcl scripts. You
can write your Tcl scripts in any text editor like joe or emacs. I suggest that you call this first
example 'example1.tcl'.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

First of all, you need to create a simulator object. This is done with the command

set ns [new Simulator]

Now we open a file for writing that is going to be used for the nam trace data.

set nf [open out.nam w]


$ns namtrace-all $nf

The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the
second line we tell the simulator object that we created above to write all simulation data
that is going to be relevant for nam into this file.

The next step is to add a 'finish' procedure that closes the trace file and starts nam.

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

The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of
simulation time.
$ns at 5.0 "finish"
You probably understand what this line does just by looking at it. ns provides you with a
very simple way to schedule events with the 'at' command.
The last line finally starts the simulation.
$ns run

You can actually save the file now and try to run it with 'ns example1.tcl'. You are going to
get an error message like 'nam: empty trace file out.nam' though, because until now we
haven't defined any objects (nodes, links, etc.) or events. You will have to use the code from
this section as starting point in the other sections. 

2. Two nodes, one link


In this section we are going to define a very simple topology with two nodes that are
connected by a link. The following two lines define the two nodes. (Note: You have to insert
the code in this section before the line '$ns run', or even better, before the line '$ns at 5.0
"finish"').
set n0 [$ns node]
set n1 [$ns node]

A new node object is created with the command '$ns node'. The above code creates two
nodes and assigns them to the handles 'n0' and 'n1'.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

The next line connects the two nodes.


$ns duplex-link $n0 $n1 1Mb 10ms DropTail

This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with
the bandwidth 1Megabit, a delay of 10ms and a DropTail queue.

Now you can save your file and start the script with 'ns example1.tcl'. nam will be started
automatically and you should see an output that resembles the picture below.

3. Sending data
Of course, this example isn't very satisfying yet, since you can only look at the topology, but
nothing actually happens, so the next step is to send some data from node n0 to node n1. In
ns, data is always being sent from one 'agent' to another. So the next step is to create an
agent object that sends data from node n0, and another agent object that receives the data on
node n1.

#Create a UDP agent and attach it to node n0


set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic
generator to the UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-
explaining. The packet Size is being set to 500 bytes and a packet will be sent every 0.005
seconds (i.e. 200 packets per second). 
The next lines create a Null agent which acts as traffic sink and attach it to node n1.

set null0 [new Agent/Null] 


$ns attach-agent $n1 $null0

Now the two agents have to be connected with each other.

$ns connect $udp0 $null0

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

And now we have to tell the CBR agent when to send data and when to stop sending. Note:
It's probably best to put the following lines just before the line '$ns at 5.0 "finish"'.
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

This code should be self-explaining again.

Now you can save the file and start the simulation again. When you click on the 'play'
button in the nam window, you will see that after 0.5 simulation seconds, node 0 starts
sending data packets to node 1. You might want to slow nam down then with the 'Step'
slider.

I suggest that now you start some experiments with nam and the Tcl script. You can click on
any packet in the nam window to monitor it, and you can also click directly on the link to
get some graphs with statistics. I also suggest that you try to change the 'packetsize_' and
'interval_' parameters in the Tcl script to see what happens. 

4. The topology

Now insert the following lines into the code to create four nodes.
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
The following piece of Tcl code creates three duplex links between the nodes.
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms DropTail

You can save and start the script now. You might notice that the topology looks a bit
awkward in nam. You can hit the 're-layout' button to make it look better, but it would be
nice to have some more control over the layout. Add the next three lines to your Tcl script
and start it again.
$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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

You will probably understand what this code does when you look at the topology in the
nam window now. It should look like the picture below.

Note that the autolayout related parts of nam are gone, since now you have taken the layout
into your own hands. The options for the orientation of a link are right, left, up, down and
combinations of these orientations. You can experiment with these settings later, but for
now please leave the topology the way it is.

5. The events

Now we create two UDP agents with CBR traffic sources and attach them to the nodes n0
and n1. Then we create a Null agent and attach it to node n3.

#Create a UDP agent and attach it to node n0


set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

#Create a UDP agent and attach it to node n1


set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1

# Create a CBR traffic source and attach it to udp1


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

set null0 [new Agent/Null]


$ns attach-agent $n3 $null0

The two CBR agents have to be connected to the Null agent.


$ns connect $udp0 $null0

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns connect $udp1 $null0

We want the first CBR agent to start sending at 0.5 seconds and to stop at 4.5 seconds while
the second CBR agent starts at 1.0 seconds and stops at 4.0 seconds.
$ns at 0.5 "$cbr0 start"
$ns at 1.0 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"
When you start the script now with 'ns example2.tcl', you will notice that there is more
traffic on the links from n0 to n2 and n1 to n2 than the link from n2 to n3 can carry.

A simple calculation confirms this: We are sending 200 packets per second on each of the
first two links and the packet size is 500 bytes.

This results in a bandwidth of 0.8 megabits per second for the links from n0 to n2 and from
n1 to n2.

That's a total bandwidth of 1.6Mb/s, but the link between n2 and n3 only has a capacity of
1Mb/s, so obviously some packets are being discarded.

But which ones? Both flows are black, so the only way to find out what is happening to the
packets is to monitor them in nam by clicking on them.

In the next two sections I'm going to show you how to distinguish between different flows
and how to see what is actually going on in the queue at the link from n2 to n3.

6. Marking flows
Add the following two lines to your CBR agent definitions.
$udp0 set class_ 1
$udp1 set class_ 2

The parameter 'fid_' stands for 'flow id'.


Now add the following piece of code to your Tcl script, preferably at the beginning after the
simulator object has been created, since this is a part of the simulator setup.
$ns color 1 Blue
$ns color 2 Red

This code allows you to set different colors for each flow id.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Now you can start the script again and one flow should be blue, while the other one is red.

Watch the link from node n2 to n3 for a while, and you will notice that after some time the
distribution between blue and red packets isn't too fair anymore (at least that's the way it is
on my system).

In the next section I'll show you how you can look inside this link's queue to find out what is
going on there.

7. Monitoring a queue

You only have to add the following line to your code to monitor the queue for the link from
n2 to n3.
$ns duplex-link-op $n2 $n3 queuePos 0.5

Start ns again and you will see a picture similar to the one below after a few moments.

You can see the packets in the queue now, and after a while you can even see how the
packets are being dropped, though (at least on my system, I guess it might be different in
later or earlier releases) only blue packets are being dropped.

But you can't really expect too much 'fairness' from a simple DropTail queue. So let's try to
improve the queueing by using a SFQ (stochastic fair queueing) queue for the link from n2
to n3.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Change the link definition for the link between n2 and n3 to the following line.

$ns duplex-link $n3 $n2 1Mb 10ms SFQ

The queueing should be 'fair' now. The same amount of blue and red packets should be
dropped.

8. Creating a larger topology


As always, the topology has to be created first, though this time we take a different
approach which you will find more comfortable when you want to create larger topologies.
The following code creates seven nodes and stores them in the array n().

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


{
set n($i) [$ns node]
}

You have certainly seen 'for' loops in other programming languages before, and I am sure
you understand the structure at once.

Note that arrays, just like other variables in Tcl, don't have to be declared first.

Now we're going to connect the nodes to create a circular topology.

The following piece of code might look a bit more complicated at first.

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


{
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}

This 'for' loop connects all nodes with the next node in the array with the exception of the
last node, which is being connected with the first node. To accomplish that, I used the '%'
(modulo) operator.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

When you run the script now, the topology might look a bit strange in nam at first, but after
you hit the 're-layout' button it should look like the picture below.

9. Link failure

The next step is to send some data from node n(0) to node n(3).

#Create a UDP agent and attach it to node n(0)


set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

set null0 [new Agent/Null]


$ns attach-agent $n(3) $null0

$ns connect $udp0 $null0

$ns at 0.5 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"

The code above should look familiar to you by now. The only difference to the last sections
is that now we have to use the node array elements.

If you start the script, you will see that the traffic takes the shortest path from node 0 to node
3 through nodes 1 and 2, as could be expected.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Now we add another interesting feature. We let the link between node 1 and 2 (which is
being used by the traffic) go down for a second.
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)

It is probably not too hard to understand these two lines. Now you can start the script again
and you will see that between the seconds 1.0 and 2.0 the link will be down, and all data that
is sent from node 0 is lost.

Now I will show you how to use dynamic routing to solve that 'problem'. Add the following
line at the beginning of your Tcl script, after the simulator object has been created.

$ns rtproto DV

Start the simulation again, and you will see how at first a lot of small packets run through
the network. If you slow nam down enough to click on one of them, you will see that they
are 'rtProtoDV' packets which are being used to exchange routing information between the
nodes. When the link goes down again at 1.0 seconds, the routing will be updated and the
traffic will be re-routed through the nodes 6, 5 and 4.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-V

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing tcl scripts in NS2 for simulate the wired networks.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate wired network and analyze the throughput using awk script.

5. Simulate a wired network consisting of TCP and UDP traffic using NS2 and then
calculate their respective throughput using AWK script.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Program :

#Create a simulator object


set ns [new Simulator]

#Tell the simulator to use dynamic routing


$ns rtproto DV

#Open the nam trace file


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

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}

#Create seven nodes


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

#Create links between the nodes


for {set i 0} {$i < 7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}

#Create a UDP agent and attach it to node n(0)


set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

#Create a Null agent (a traffic sink) and attach it to node n(3)


set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0

#Connect the traffic source with the traffic sink


$ns connect $udp0 $null0

#Schedule events for the CBR agent and the network dynamics
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns rtmodel-at 2.0 up $n(1) $n(2)


$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

AWK Script for throughput evaluation

Note : 

1. This awk script is for new trace format files.


2. Copy this awk files to the directory where tcl script is saved.
3. Change initial values as per your need.

BEGIN {
recvdSize = 0
startTime = 1e6
stopTime = 0
}

# Trace line format: new


if ($2 == "-t") {
event = $1
time = $3
node_id = $5
flow_id = $39
pkt_id = $41
pkt_size = $37
flow_t = $45
level = $19
}

# Store start time


if (level == "AGT" && (event == "+" || event == "s") && pkt_size >= 512) {
if (time < startTime) {
startTime = time
}
}

# 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 size
recvdSize += pkt_size

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

}
}

END {
printf("Average Throughput[kbps] = %.2f\t\t StartTime=%.2f\tStopTime=%.2f\n",
(recvdSize/(stopTime-startTime))*(8/1000),startTime,stopTime)
}

TRACE FILES AND DESCRIPTION

The file written by an application to store coverage information or overall network


information and In NS2 , it is called as Trace File.

In order to generate a trace file. we have to create a trace file in Otcl script.

SYNTAX FOR CREATING A TRACE FILE

# Open the trace file


set nf [open out.tr w]
$ns trace-all $nf

which means we are opening a newtrace file named as "out" and also telling that data must
be stored in .tr [trace] format.

"nf" is the file handler that we are used here to handle the trace file.

"w" means write i.e the file out.tr is opened for writing.

>> "r" means reading and "a" means appending

The second line tells the simulator to trace each packet on every link in the topology and for
that we give file handler nf for the simulator ns.

# Define finish procedure


proc finish {} {
global ns nf
$ns flush-trace
close nf
exit 0
}

In here the trace data is flushed into the file by using command $ns flush-trace and then file
is closed.

While running the ns2 program via terminal, trace file is generated in the selected directory
(folder or directory where the program stored).

SNAP SHOT OF A GENERATED TRACE FILE FOR WIRED NETWORK

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

The format of a trace string is shown below:

In here,there is 12 feilds and we can explain it as;

1. EVENT OR TYPE IDENTIFIER


+ :a packet enque event
-  :a packet deque event
r  :a packet reception event
d :a packet drop (e.g., sent to dropHead_) event
c :a packet collision at the MAC level

2. TIME : at which the packet tracing string is created.


3-4. SOURCE AND DESTINATION NODE : source and destination ID's of tracing objects.
5. PACKET NAME : Name of the packet type.
6. PACKET SIZE : Size of packet in bytes.
7. FLAGS : 7 digit flag string.

“-”: disable
1st = “E”: ECN (Explicit Congestion Notification) echo is enabled.
2nd = “P”: the priority in the IP header is enabled.
3rd : Not in use
4th = “A”: Congestion action
5th = “E”: Congestion has occurred.
6th = “F”: The TCP fast start is used.
7th = “N”: Explicit Congestion Notification (ECN) is on. 

8. FLOW ID
9-10. SOURCE AND DESTINATION ADDRESS :

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

The format of these two fields is “a.b”, where “a" is the address and "b" is the port.
11. SEQUENCE NUMBER
12. PACKET UNIQUE ID

Each trace line starts with an event (+, -, d, r) descriptor followed by the simulation
time (in seconds) of that event, and from and to node, which identify the link on
which the event occurred.

Look at Figure in the Network Components to see where in a link each type of event
is traced. The next information in the line before flags (appeared as "------" since no
flag is set) is packet type and size (in Bytes).

Currently, NS implements only the Explicit Congestion Notification (ECN) bit, and
the remaining bits are not used.

The next field is flow id (fid) of IPv6 that a user can set for each flow at the input
OTcl script.

Even though fid field may not used in a simulation, users can use this field for
analysis purposes.
The fid field is also used when specifying stream color for the NAM display.

The next two fields are source and destination address in forms of "node.port".

The next field shows the network layer protocol's packet sequence number.

Note that even though UDP implementations 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.

Experiment-VI

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the wired network protocols and
evaluate the performance of those protocols.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate wired network protocols and analyze the performance of those protocols.

6. Performance evaluation of different routing protocols in wired network


environment using NS2.

a. Performance Evaluation of TCP and CBR connections sharing a bottleneck link

set ns [new Simulator]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the Trace files


set file1 [open out.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]

#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.5Mb 40ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 30ms DropTail

#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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

#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

#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.

proc plotWindow {tcpSource file} {


global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 0.1 "plotWindow $tcp $winfile"

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns at 125.0 "finish"


$ns run

Performance Evaluation of TCP and CBR connections with random drops. 

#Create a simulator object


set ns [new Simulator]

# tcp 0
# \
# \
# 2------------3
# /
# /
# cbr 1

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the NAM trace file


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

#Open the Trace file


set tf [open out.tr w]
set windowVsTime2 [open WindowVsTimeNReno w]
$ns trace-all $tf

#Define a 'finish' procedure


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

#Create four nodes


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

$ns at 0.1 "$n1 label \"CBR\""


$ns at 1.0 "$n0 label \"FTP\""

#Create links between the nodes

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns duplex-link $n0 $n2 2Mb 10ms DropTail


$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.07Mb 20ms DropTail
$ns simplex-link $n3 $n2 0.07Mb 20ms DropTail

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


$ns queue-limit $n2 $n3 10

#Monitor the queue for link (n2-n3). (for NAM)


$ns simplex-link-op $n2 $n3 queuePos 0.5

#Set error model on link n2 to n3.


set loss_module [new ErrorModel]
$loss_module set rate_ 0.2
$loss_module ranvar [new RandomVariable/Uniform]
$loss_module drop-target [new Agent/Null]
$ns lossmodel $loss_module $n2 $n3

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#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 $n3 $null
$ns connect $udp $null
$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

#Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 624.0 "$ftp stop"

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns at 624.5 "$cbr stop"

# Printing the window size


proc plotWindow {tcpSource file} {
global ns
set time 0.01
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 1.1 "plotWindow $tcp $windowVsTime2"

# sample the bottleneck queue every 0.1 sec. store the trace in qm.out
set qmon [$ns monitor-queue $n2 $n3 [open qm.out w] 0.1];
[$ns link $n2 $n3] queue-sample-timeout; # [$ns link $n2 $n3] start-tracing

#Detach tcp and sink agents (not really necessary)


$ns at 624.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

$ns at 625.0 "finish"


$ns run

TCP connections with delays and initial transmission times created at random

set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tf [open out.tr w]


set windowVsTime [open win w]
set param [open parameters w]
$ns trace-all $tf

#Define a 'finish' procedure


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

#Create bottleneck and dest nodes


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

#Create links between these nodes


$ns duplex-link $n2 $n3 0.7Mb 20ms DropTail

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set NumbSrc 5
set Duration 10

#Source nodes
for {set j 1} {$j<=$NumbSrc} { incr j } {
set S($j) [$ns node]
}

# Create a random generator for starting the ftp and for bottleneck link delays
set rng [new RNG]
$rng seed 0

# paratmers for random variables for delays


set RVdly [new RandomVariable/Uniform]
$RVdly set min_ 1
$RVdly set max_ 5
$RVdly use-rng $rng

# parameters for random variables for begenning of ftp connections


set RVstart [new RandomVariable/Uniform]
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng

#We define two random parameters for each connections


for {set i 1} {$i<=$NumbSrc} { incr i } {
set startT($i) [expr [$RVstart value]]
set dly($i) [expr [$RVdly value]]
puts $param "dly($i) $dly($i) ms"
puts $param "startT($i) $startT($i) sec"
}

#Links between source and bottleneck


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 100
}

#Monitor the queue for link (n2-n3). (for NAM)


$ns duplex-link-op $n2 $n3 queuePos 0.5

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


$ns queue-limit $n2 $n3 10

#TCP Sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_src($j) [new Agent/TCP/Reno]
}

#TCP Destinations
for {set j 1} {$j<=$NumbSrc} { incr j } {

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set tcp_snk($j) [new Agent/TCPSink]


}

#Connections
for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns attach-agent $S($j) $tcp_src($j)
$ns attach-agent $n3 $tcp_snk($j)
$ns connect $tcp_src($j) $tcp_snk($j)
}

#FTP sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set ftp($j) [$tcp_src($j) attach-source FTP]
}

#Parametrisation of TCP sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$tcp_src($j) set packetSize_ 552
}

#Schedule events for the FTP agents:


for {set i 1} {$i<=$NumbSrc} { incr i } {
$ns at $startT($i) "$ftp($i) start"
$ns at $Duration "$ftp($i) stop"
}

proc plotWindow {tcpSource file k} {


global ns
set time 0.03
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
puts $file "$k $now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file $k" }

# The procedure will now be called for all tcp sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns at 0.1 "plotWindow $tcp_src($j) $windowVsTime $j"
}

$ns at [expr $Duration] "finish"


$ns run

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

Experiment-VII

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the different queues and buffers and
evaluate the performance of those Queues.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate queues in wired network and analyze the performance of those queues.

7. Performance evaluation of different queues, effect of queues and buffers in wired


network environment using NS2.

7a. TCP connections with a RED bottleneck buffer

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tf [open out.tr w]


set windowVsTime [open win w]
set param [open parameters w]
$ns trace-all $tf

#Define a 'finish' procedure


proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam out.nam &
exec grep "a" red-queue.tr > ave.tr
exec grep "Q" red-queue.tr > cur.tr
exit 0
}

#Create bottleneck and dest nodes


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

#Create links between these nodes


$ns duplex-link $n2 $n3 0.7Mb 20ms RED

set NumbSrc 3
set Duration 50

#Source nodes
for {set j 1} {$j<=$NumbSrc} { incr j } {
set S($j) [$ns node]
}

# Create a random generator for starting the ftp and for bottleneck link delays
set rng [new RNG]
$rng seed 2

# parameters for random variables for begenning of ftp connections


set RVstart [new RandomVariable/Uniform]
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng

#We define random starting time for each connection


for {set i 1} {$i<=$NumbSrc} { incr i } {
set startT($i) [expr [$RVstart value]]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set dly($i) 1
puts $param "startT($i) $startT($i) sec"
}

#Links between source and bottleneck


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 20
}

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


$ns queue-limit $n2 $n3 100

set redq [[$ns link $n2 $n3] queue]


set traceq [open red-queue.tr w]
$redq trace curq_
$redq trace ave_
$redq attach $traceq

#TCP Sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_src($j) [new Agent/TCP/Reno]
$tcp_src($j) set window_ 8000
}

#TCP Destinations
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_snk($j) [new Agent/TCPSink]
}

#Connections
for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns attach-agent $S($j) $tcp_src($j)
$ns attach-agent $n3 $tcp_snk($j)
$ns connect $tcp_src($j) $tcp_snk($j)
}

#FTP sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set ftp($j) [$tcp_src($j) attach-source FTP]
}

#Parametrisation of TCP sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$tcp_src($j) set packetSize_ 552
}

#Schedule events for the FTP agents:


for {set i 1} {$i<=$NumbSrc} { incr i } {
$ns at $startT($i) "$ftp($i) start"
$ns at $Duration "$ftp($i) stop"

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

proc plotWindow {tcpSource file k} {


global ns NumbSrc
set time 0.03
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
if {$k == 1} {
puts -nonewline $file "$now \t $cwnd \t"
} else {
if {$k < $NumbSrc } {
puts -nonewline $file "$cwnd \t" }
}
if { $k == $NumbSrc } {
puts -nonewline $file "$cwnd \n" }
$ns at [expr $now+$time] "plotWindow $tcpSource $file $k" }

# The procedure will now be called for all tcp sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns at 0.1 "plotWindow $tcp_src($j) $windowVsTime $j"
}

$ns at [expr $Duration] "finish"


$ns run

TCP connections with a DROP TAIL buffer.

set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tf [open out.tr w]


set windowVsTime [open win w]
set param [open parameters w]
$ns trace-all $tf

#Define a 'finish' procedure


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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

exec nam out.nam &


exit 0
}

#Create bottleneck and dest nodes


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

#Create links between these nodes


$ns duplex-link $n2 $n3 0.7Mb 20ms DropTail

set NumbSrc 3
set Duration 50

#Source nodes
for {set j 1} {$j<=$NumbSrc} { incr j } {
set S($j) [$ns node]
}

# Create a random generator for starting the ftp and for bottleneck link delays
set rng [new RNG]
$rng seed 2

# parameters for random variables for begenning of ftp connections


set RVstart [new RandomVariable/Uniform]
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng

#We define random starting times for each connection


for {set i 1} {$i<=$NumbSrc} { incr i } {
set startT($i) [expr [$RVstart value]]
set dly($i) 1
puts $param "startT($i) $startT($i) sec"
}

#Links between source and bottleneck


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 20
}

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


$ns queue-limit $n2 $n3 100

#TCP Sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_src($j) [new Agent/TCP/Reno]
$tcp_src($j) set window_ 8000
}

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

#TCP Destinations
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_snk($j) [new Agent/TCPSink]
}

#Connections
for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns attach-agent $S($j) $tcp_src($j)
$ns attach-agent $n3 $tcp_snk($j)
$ns connect $tcp_src($j) $tcp_snk($j)
}

#FTP sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set ftp($j) [$tcp_src($j) attach-source FTP]
}

#Parametrisation of TCP sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$tcp_src($j) set packetSize_ 552
}

#Schedule events for the FTP agents:


for {set i 1} {$i<=$NumbSrc} { incr i } {
$ns at $startT($i) "$ftp($i) start"
$ns at $Duration "$ftp($i) stop"
}
proc plotWindow {tcpSource file k} {
global ns NumbSrc
set time 0.03
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
if {$k == 1} {
puts -nonewline $file "$now \t $cwnd \t"
} else {
if {$k < $NumbSrc } {
puts -nonewline $file "$cwnd \t" }
}
if { $k == $NumbSrc } {
puts -nonewline $file "$cwnd \n" }
$ns at [expr $now+$time] "plotWindow $tcpSource $file $k" }

# The procedure will now be called for all tcp sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns at 0.1 "plotWindow $tcp_src($j) $windowVsTime $j"
}

set qfile [$ns monitor-queue $n2 $n3 [open queue.tr w] 0.05]


[$ns link $n2 $n3] queue-sample-timeout;

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns at [expr $Duration] "finish"


$ns run

Experiment-VIII

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the different queues and buffers and
evaluate the performance of those Queues.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate queues in wired network and analyze the performance of those queues.

8. Compare the behavior of different variants of TCP (Tahoe, Reno, Vegas etc.) in
wired network using NS2. Compare the congestion window behavior by plotting
graph.

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tf [open out.tr w]


set windowVsTime [open win w]
set param [open parameters w]
$ns trace-all $tf

#Define a 'finish' procedure


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

#Create bottleneck and dest nodes


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

#Create links between these nodes


$ns duplex-link $n2 $n3 0.7Mb 20ms DropTail

set NumbSrc 5
set Duration 10

#Source nodes
for {set j 1} {$j<=$NumbSrc} { incr j } {
set S($j) [$ns node]
}

# Create a random generator for starting the ftp and for bottleneck link delays
set rng [new RNG]
$rng seed 0

# paratmers for random variables for delays


set RVdly [new RandomVariable/Uniform]
$RVdly set min_ 1
$RVdly set max_ 5
$RVdly use-rng $rng

# parameters for random variables for begenning of ftp connections


set RVstart [new RandomVariable/Uniform]
$RVstart set min_ 0
$RVstart set max_ 7
$RVstart use-rng $rng

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

#We define two random parameters for each connections


for {set i 1} {$i<=$NumbSrc} { incr i } {
set startT($i) [expr [$RVstart value]]
set dly($i) [expr [$RVdly value]]
puts $param "dly($i) $dly($i) ms"
puts $param "startT($i) $startT($i) sec"
}

#Links between source and bottleneck


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail
$ns queue-limit $S($j) $n2 100
}

#Monitor the queue for link (n2-n3). (for NAM)


$ns duplex-link-op $n2 $n3 queuePos 0.5

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


$ns queue-limit $n2 $n3 10

#TCP Sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_src($j) [new Agent/TCP/Reno]
# Note : just change above line with TCP/Tahoe and TCP/Vegas
#After executing this file just change the tcp_src with tahoe and vegas
}

#TCP Destinations
for {set j 1} {$j<=$NumbSrc} { incr j } {
set tcp_snk($j) [new Agent/TCPSink]
}

#Connections
for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns attach-agent $S($j) $tcp_src($j)
$ns attach-agent $n3 $tcp_snk($j)
$ns connect $tcp_src($j) $tcp_snk($j)
}

#FTP sources
for {set j 1} {$j<=$NumbSrc} { incr j } {
set ftp($j) [$tcp_src($j) attach-source FTP]
}

#Parametrisation of TCP sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$tcp_src($j) set packetSize_ 552
}

#Schedule events for the FTP agents:


for {set i 1} {$i<=$NumbSrc} { incr i } {

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns at $startT($i) "$ftp($i) start"


$ns at $Duration "$ftp($i) stop"
}

proc plotWindow {tcpSource file k} {


global ns
set time 0.03
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
puts $file "$k $now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file $k" }

# The procedure will now be called for all tcp sources


for {set j 1} {$j<=$NumbSrc} { incr j } {
$ns at 0.1 "plotWindow $tcp_src($j) $windowVsTime $j"
}

$ns at [expr $Duration] "finish"


$ns run

AWK file for calculate congestion window

BEGIN {
}
{
if($6=="cwnd_") {
printf("%f\t%f\n",$1,$7);
}
}
END {}
Note : After executing all 3 files, we can compare the results.
Experiment-IX

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the wireless adhoc networks.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate the wireless adhoc networks.

9. Simulation of wireless ad hoc networks using NS2.

Program: wrls1.tcl

# A 3-node example for ad-hoc simulation with AODV.

# Define options
set val(chan) Channel/WirelessChannel; # channel type
set val(prop) Propagation/TwoRayGround; # radio-propagation model

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

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
set val(ifqlen) 50; # max packet in ifq
set val(nn) 3; # number of mobilenodes
set val(rp) AODV; # routing protocol
set val(x) 500; # X dimension of topography
set val(y) 400; # Y dimension of topography
set val(stop) 150; # time of simulation end

set ns [new Simulator]


set tracefd [open simple.tr w]
set windowVsTime2 [open win.tr w]
set namtrace [open simwrls.nam w]

$ns trace-all $tracefd


$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 $val(nn)

#
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
#

# 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

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


set node_($i) [$ns node]
}

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

# Provide initial location of mobilenodes


$node_(0) set X_ 5.0
$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 490.0


$node_(1) set Y_ 285.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 150.0


$node_(2) set Y_ 240.0
$node_(2) set Z_ 0.0

# Generation of movements
$ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"
$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
$ns at 110.0 "$node_(0) setdest 480.0 300.0 5.0"

# Set a TCP connection between node_(0) and node_(1)


set tcp [new Agent/TCP/Newreno]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $node_(0) $tcp
$ns attach-agent $node_(1) $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 10.0 "$ftp start"

# Printing the window size


proc plotWindow {tcpSource file} {
global ns
set time 0.01
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 10.1 "plotWindow $tcp $windowVsTime2"

# Define node initial position in nam


for {set i 0} {$i < $val(nn)} { incr i } {
# 30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}

# Telling nodes when the simulation ends


for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "$node_($i) reset";

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

# ending nam and the simulation


$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "stop"
$ns at 150.01 "puts \"end simulation\" ; $ns halt"
proc stop {} {
global ns tracefd namtrace
$ns flush-trace
close $tracefd
close $namtrace
}

$ns run

Experiment-X
OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the Dynamic Source Routingand
evaluate the performance.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate the Dynamic Source Routing protocol and evaluate the performance
of it.

10. Performance evaluation of DSR ad-hoc wireless routing protocols using NS2.

Program:

# wrls1.tcl
# A 3-node example for ad-hoc simulation with DSR

# Define options

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

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) CMUPriQueue; # interface queue type
set val(ll) LL; # link layer type
set val(ant) Antenna/OmniAntenna; # antenna model
set val(ifqlen) 50 ; # max packet in ifq
set val(nn) 3 ; # number of mobilenodes
set val(rp) DSR; # routing protocol
set val(x) 500 ; # X dimension of topography
set val(y) 400 ; # Y dimension of topography
set val(stop) 150; # time of simulation end

set ns [new Simulator]


set tracefd [open simple.tr w]
set windowVsTime2 [open win.tr w]
set namtrace [open simwrls.nam w]

$ns trace-all $tracefd


$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 $val(nn)

#
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
#

# 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 \

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON

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


set node_($i) [$ns node]
}

# Provide initial location of mobilenodes


$node_(0) set X_ 5.0
$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 490.0


$node_(1) set Y_ 285.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 150.0


$node_(2) set Y_ 240.0
$node_(2) set Z_ 0.0

# Generation of movements
$ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"
$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
$ns at 110.0 "$node_(0) setdest 480.0 300.0 5.0"

# Set a TCP connection between node_(0) and node_(1)


set tcp [new Agent/TCP/Newreno]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $node_(0) $tcp
$ns attach-agent $node_(1) $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 10.0 "$ftp start"

# Printing the window size


proc plotWindow {tcpSource file} {
global ns
set time 0.01
set now [$ns now]
set cwnd [$tcpSource set cwnd_]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

puts $file "$now $cwnd"


$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 10.1 "plotWindow $tcp $windowVsTime2"

# Define node initial position in nam


for {set i 0} {$i < $val(nn)} { incr i } {
# 30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}
# Telling nodes when the simulation ends
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "$node_($i) reset";
}
# ending nam and the simulation
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "stop"
$ns at 150.01 "puts \"end simulation\" ; $ns halt"
proc stop {} {
global ns tracefd namtrace
$ns flush-trace
close $tracefd
close $namtrace
exec nam simwrls.nam &
exit 0
}
$ns run

Experiment-XI

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the Destination-Sequenced Distance-
Vector Routing and evaluate the performance.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate the Destination-Sequenced Distance-Vector Routing protocol and
evaluate the performance of it.

11. Performance evaluation of DSDV ad-hoc wireless routing protocols using NS2.

Program:
# wrls1.tcl
# A 3-node example for ad-hoc simulation with DSDV

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

# Define options
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
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 3 ;# number of mobilenodes
set val(rp) DSDV ;# routing protocol
set val(x) 500 ;# X dimension of topography
set val(y) 400 ;# Y dimension of topography
set val(stop) 150 ;# time of simulation end

set ns [new Simulator]


set tracefd [open simple.tr w]
set windowVsTime2 [open win.tr w]
set namtrace [open simwrls.nam w]

$ns trace-all $tracefd


$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 $val(nn)

#
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
#

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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON

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


set node_($i) [$ns node]
}

# Provide initial location of mobilenodes


$node_(0) set X_ 5.0
$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 490.0


$node_(1) set Y_ 285.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 150.0


$node_(2) set Y_ 240.0
$node_(2) set Z_ 0.0

# Generation of movements
$ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"
$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
$ns at 110.0 "$node_(0) setdest 480.0 300.0 5.0"

# Set a TCP connection between node_(0) and node_(1)


set tcp [new Agent/TCP/Newreno]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns attach-agent $node_(0) $tcp
$ns attach-agent $node_(1) $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 10.0 "$ftp start"

# Printing the window size


proc plotWindow {tcpSource file} {
global ns
set time 0.01
set now [$ns now]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set cwnd [$tcpSource set cwnd_]


puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns at 10.1 "plotWindow $tcp $windowVsTime2"

# Define node initial position in nam


for {set i 0} {$i < $val(nn)} { incr i } {
# 30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}

# Telling nodes when the simulation ends


for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "$node_($i) reset";
}
# ending nam and the simulation
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "stop"
$ns at 150.01 "puts \"end simulation\" ; $ns halt"
proc stop {} {
global ns tracefd namtrace
$ns flush-trace
close $tracefd
close $namtrace
}
$ns run
Experiment-XII

OBJECTIVE:
This Lab Session will develop student's knowledge in
 writing Otcl scripts in NS2 for simulate the Ad-hoc On-demand Distance
Vector Routing and evaluate the performance.

OUTCOME:
Upon completion of this lab, students will be able to
 simulate the Ad-hoc On-demand Distance Vector protocol and evaluate the
performance of it.

12. Performance evaluation of AODV ad-hoc wireless routing protocols using NS2.

Program:

#----------------------------------------------------------------
# Definition of the physical layer
#----------------------------------------------------------------

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set val(chan) Channel/WirelessChannel


set val(prop) Propagation/TwoRayGround
set val(ant) Antenna/OmniAntenna
set val(ll) LL
set val(ifq) Queue/DropTail/PriQueue
set val(ifqlen) 100
set val(netif) Phy/WirelessPhy
set val(mac) Mac/802_11
#-----------------------------------------------------------------
# Scenario parameters
#------------------------------------------------------------------
set val(nn) 30
set val(rp) AODV
set val(x) 2000
set val(y) 2000
set val(energymodel) EnergyModel;
set val(n_ch) chan_1

#############################################################
#----------------------------------------------------------------------
# Set up simulator objects
#----------------------------------------------------------------------

set ns [new Simulator]


set tracefd [open aodv.tr w]
$ns trace-all $tracefd
$ns use-newtrace
set namtrace [open sim12.nam w]
$ns namtrace-all-wireless $namtrace $val(x) $val(y)
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
#############################################################
#creating trace files
#############################################################
set f0 [open out02.tr w]
set f1 [open out12.tr w]
set f2 [open out22.tr w]
set f3 [open out32.tr w]

set f4 [open lost02.tr w]


set f5 [open lost12.tr w]
set f6 [open lost22.tr w]
set f7 [open lost32.tr w]

set f8 [open delay02.tr w]


set f9 [open delay12.tr w]
set f10 [open delay22.tr w]
set f11 [open delay32.tr w]
#############################################################
#defining channel parameters

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

#############################################################
set chan_1 [new $val(chan)]
set chan_2 [new $val(chan)]
set chan_3 [new $val(chan)]
set chan_4 [new $val(chan)]
#############################################################
#configuring 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) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace OFF \
-channel $chan_1 \
-energyModel $val(energymodel) \
-rxPower 0.3 \
-txPower 0.6 \
-initialEnergy 90 \
-rxPower 0.3 \
-txPower 0.6

#############################################################
#defining node size and motion
#############################################################

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


set n($i) [$ns node]
$n($i) random-motion 0
$n($i) color red
$ns at 0.0 "$n($i) color red"
$ns initial_node_pos $n($i) 200
}
for {set j 10} {$j < 20} { incr j } {
set n($j) [$ns node]
$n($j) random-motion 0
$n($j) color green
$ns at 0.0 "$n($j) color green"
$ns initial_node_pos $n($j) 200
}
for {set k 20} {$k < 30} { incr k } {
set n($k) [$ns node]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$n($k) random-motion 0
$n($k) color blue
$ns at 0.0 "$n($k) color blue"
$ns initial_node_pos $n($k) 200
}
#############################################################
#creating node movement
#############################################################
$ns at 0.0 "$n(4) start"
$ns at 0.0 "$n(5) start"
$ns at 0.0 "$n(6) setdest 445.0 40.0 155.0"
$ns at 0.0 "$n(7) setdest 660.0 18.0 10.0"
$ns at 0.0 "$n(8) setdest 285.0 140.0 105.0"
$ns at 0.0 "$n(9) setdest 860.0 158.0 150.0"
$ns at 0.0 "$n(10) setdest 745.0 940.0 105.0"
$ns at 0.0 "$n(11) setdest 660.0 398.0 180.0"
$ns at 0.0 "$n(12) setdest 445.0 220.0 105.0"
$ns at 0.0 "$n(13) setdest 60.0 218.0 110.0"
$ns at 0.0 "$n(14) setdest 345.0 40.0 105.0"
$ns at 0.0 "$n(15) setdest 960.0 18.0 10.0"
$ns at 0.0 "$n(16) setdest 445.0 740.0 155.0"
$ns at 0.0 "$n(17) setdest 660.0 918.0 10.0"
$ns at 0.0 "$n(18) setdest 285.0 540.0 105.0"
$ns at 0.0 "$n(19) setdest 860.0 658.0 150.0"
$ns at 0.0 "$n(20) setdest 845.0 940.0 105.0"
$ns at 0.0 "$n(11) setdest 760.0 398.0 180.0"
$ns at 0.0 "$n(22) setdest 945.0 220.0 105.0"
$ns at 0.0 "$n(23) setdest 60.0 918.0 110.0"
$ns at 0.0 "$n(24) setdest 545.0 640.0 105.0"
$ns at 0.0 "$n(25) setdest 460.0 818.0 10.0"
$ns at 0.0 "$n(26) setdest 545.0 340.0 155.0"
$ns at 0.0 "$n(27) setdest 860.0 318.0 10.0"
$ns at 0.0 "$n(28) setdest 685.0 340.0 105.0"
$ns at 0.0 "$n(29) setdest 860.0 658.0 150.0"
$ns at 7.0 "$n(9) setdest 545.0 40.0 105.0"
$ns at 7.0 "$n(8) setdest 760.0 18.0 10.0"
$ns at 7.0 "$n(7) setdest 445.0 40.0 155.0"
$ns at 7.0 "$n(6) setdest 660.0 18.0 10.0"
$ns at 7.0 "$n(5) setdest 285.0 140.0 105.0"
$ns at 7.0 "$n(4) setdest 860.0 158.0 150.0"
$ns at 7.0 "$n(19) setdest 745.0 940.0 105.0"
$ns at 7.0 "$n(18) setdest 660.0 398.0 180.0"
$ns at 7.0 "$n(17) setdest 445.0 220.0 105.0"
$ns at 7.0 "$n(16) setdest 60.0 218.0 110.0"
$ns at 7.0 "$n(15) setdest 345.0 40.0 105.0"
$ns at 7.0 "$n(14) setdest 960.0 18.0 10.0"
$ns at 7.0 "$n(13) setdest 445.0 740.0 155.0"
$ns at 7.0 "$n(12) setdest 660.0 918.0 10.0"
$ns at 7.0 "$n(11) setdest 285.0 540.0 105.0"
$ns at 7.0 "$n(10) setdest 860.0 658.0 150.0"
$ns at 7.0 "$n(29) setdest 845.0 940.0 105.0"

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns at 7.0 "$n(18) setdest 760.0 398.0 180.0"


$ns at 7.0 "$n(27) setdest 945.0 220.0 105.0"
$ns at 7.0 "$n(26) setdest 60.0 918.0 110.0"
$ns at 7.0 "$n(25) setdest 545.0 640.0 105.0"
$ns at 7.0 "$n(24) setdest 460.0 818.0 10.0"
$ns at 7.0 "$n(23) setdest 545.0 340.0 155.0"
$ns at 7.0 "$n(22) setdest 860.0 318.0 10.0"
$ns at 7.0 "$n(21) setdest 685.0 340.0 105.0"
$ns at 7.0 "$n(20) setdest 860.0 658.0 150.0"
#############################################################

$ns at 6.0 "$n(1) setdest 625.0 625.0 185.0"


$ns at 5.0 "$n(0) setdest 450.0 450.0 180.0"
$ns at 12.0 "$n(1) setdest 180.0 185.0 185.0"
$ns at 6.0 "$n(2) setdest 430.0 430.0 185.0"
$ns at 12.0 "$n(2) setdest 390.0 390.0 185.0"
$ns at 6.0 "$n(3) setdest 450.0 450.0 185.0"
$ns at 12.0 "$n(3) setdest 230.0 265.0 185.0"
#############################################################
#connecting traffic agent
#n(0) source n(1) sink0
#############################################################s
et udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set sink0 [new Agent/LossMonitor]
$ns attach-agent $n(1) $sink0
$ns connect $udp0 $sink0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set rate_ 600kb
$cbr0 set interval_ 0.05
$cbr0 attach-agent $udp0
#############################################################
#n(2) source n(4) sink1
#############################################################
set udp1 [new Agent/UDP]
$ns attach-agent $n(2) $udp1
set sink1 [new Agent/LossMonitor]
$ns attach-agent $n(4) $sink1
$ns connect $udp1 $sink1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set rate_ 600kb
$cbr1 set interval_ 0.05
$cbr1 attach-agent $udp1
#############################################################
#n(5) source n(6) sink
#############################################################
set udp2 [new Agent/UDP]
$ns attach-agent $n(5) $udp2
set sink2 [new Agent/LossMonitor]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns attach-agent $n(6) $sink2


$ns connect $udp2 $sink2
set cbr2 [new Application/Traffic/CBR]
$cbr2 set packetSize_ 500
$cbr2 set rate_ 600kb
$cbr2 set interval_ 0.05
$cbr2 attach-agent $udp2
#############################################################
#n(3) source n(6) sink
#############################################################
set udp3 [new Agent/UDP]
$ns attach-agent $n(3) $udp3
set sink3 [new Agent/LossMonitor]
$ns attach-agent $n(6) $sink3
$ns connect $udp3 $sink3
set cbr3 [new Application/Traffic/CBR]
$cbr3 set packetSize_ 500
$cbr3 set rate_ 600kb
$cbr3 set interval_ 0.05
$cbr3 attach-agent $udp3
#############################################################
#finish procedure
#############################################################
proc finish {} {
global ns f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 tracefd namtrace
#Close the output files
close $f0
close $f1
close $f2
close $f3
close $f4
close $f5
close $f6
close $f7
close $f8
close $f9
close $f10
close $f11
$ns flush-trace
close $tracefd
close $namtrace
exec nam sim12.nam &
#Call xgraph to display the results
exec xgraph out02.tr out12.tr out22.tr out32.tr -geometry 800x400 -y bandwidth -t
30_node_AODV_throughput -x time &
exec xgraph lost02.tr lost12.tr lost22.tr lost32.tr -geometry 800x400 -y packet-loss -t
30_node_AODV_packet_loss -x time &
exec xgraph delay02.tr delay12.tr delay22.tr delay32.tr -geometry 800x400 -y routing-
delay -t 30_node_AODV_packet_delay -x time &
exit 0
}

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

#############################################################
#node position setting
#############################################################

#node position -static (fixed ) topology


$n(0) set X_ 850.0
$n(0) set Y_ 50.0
$n(0) set Z_ 0.0

$n(1) set X_ 1200.0


$n(1) set Y_ 200.0
$n(1) set Z_ 0.0

$n(2) set X_ 1300.0


$n(2) set Y_ 300.0
$n(2) set Z_ 0.0

$n(3) set X_ 1150.0


$n(3) set Y_ 300.0
$n(3) set Z_ 0.0

$n(4) set X_ 1400.0


$n(4) set Y_ 400.0
$n(4) set Z_ 0.0

$n(5) set X_ 1800.0


$n(5) set Y_ 300.0
$n(5) set Z_ 0.0

$n(6) set X_ 200.0


$n(6) set Y_ 150.0
$n(6) set Z_ 0.0

$n(7) set X_ 60.0


$n(7) set Y_ 130.0
$n(7) set Z_ 0.0

$n(8) set X_ 210.0


$n(8) set Y_ 850.0
$n(8) set Z_ 0.0

$n(9) set X_ 700.0


$n(9) set Y_ 920.0
$n(9) set Z_ 0.0

$n(10) set X_ 1250.0


$n(10) set Y_ 800.0
$n(10) set Z_ 0.0

$n(11) set X_ 1300.0


$n(11) set Y_ 1400.0

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$n(11) set Z_ 0.0

$n(12) set X_ 1600.0


$n(12) set Y_ 1350.0
$n(12) set Z_ 0.0

$n(13) set X_ 200.0


$n(13) set Y_ 250.0
$n(13) set Z_ 0.0

$n(14) set X_ 250.0


$n(14) set Y_ 50.0
$n(14) set Z_ 0.0

$n(15) set X_ 120.0


$n(15) set Y_ 1200.0
$n(15) set Z_ 0.0

$n(16) set X_ 300.0


$n(16) set Y_ 1350.0
$n(16) set Z_ 0.0

$n(17) set X_ 1150.0


$n(17) set Y_ 350.0
$n(17) set Z_ 0.0

$n(18) set X_ 400.0


$n(18) set Y_ 300.0
$n(18) set Z_ 0.0

$n(19) set X_ 100.0


$n(19) set Y_ 320.0
$n(19) set Z_ 0.0

$n(20) set X_ 200.0


$n(20) set Y_ 150.0
$n(20) set Z_ 0.0

$n(21) set X_ 1150.0


$n(21) set Y_ 90.0
$n(21) set Z_ 0.0

$n(22) set X_ 200.0


$n(22) set Y_ 1120.0
$n(22) set Z_ 0.0

$n(23) set X_ 300.0


$n(23) set Y_ 1130.0
$n(23) set Z_ 0.0

$n(24) set X_ 1315.0

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$n(24) set Y_ 300.0


$n(24) set Z_ 0.0

$n(25) set X_ 400.0


$n(25) set Y_ 1400.0
$n(25) set Z_ 0.0

$n(26) set X_ 10.0


$n(26) set Y_ 30.0
$n(26) set Z_ 0.0

$n(27) set X_ 20.0


$n(27) set Y_ 1750.0
$n(27) set Z_ 0.0

$n(28) set X_ 1970.0


$n(28) set Y_ 230.0
$n(28) set Z_ 0.0

$n(29) set X_ 1840.0


$n(29) set Y_ 420.0
$n(29) set Z_ 0.0
#############################################################
# Initialize Flags
#############################################################
set holdtime0 0
set holdseq0 0
set holdtime1 0
set holdseq1 0
set holdtime2 0
set holdseq2 0
set holdtime3 0
set holdseq3 0
set holdrate0 0
set holdrate1 0
set holdrate2 0
set holdrate3 0
#############################################################
#record procedure
#############################################################

proc record {} {
global sink0 sink1 sink2 sink3 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 holdtime0 holdseq0
holdtime1 holdseq1 holdtime2 holdseq2 holdtime3 holdseq3 holdrate0 holdrate1 holdrate2
holdrate3
set ns [Simulator instance]
#Set the time after which the procedure should be called again
set time 0.5
set now [$ns now]
set bw0 [$sink0 set bytes_]
set bw1 [$sink1 set bytes_]

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

set bw2 [$sink2 set bytes_]


set bw3 [$sink3 set bytes_]

set bw4 [$sink0 set nlost_]


set bw5 [$sink1 set nlost_]
set bw6 [$sink2 set nlost_]
set bw7 [$sink3 set nlost_]

set bw8 [$sink0 set lastPktTime_]


set bw9 [$sink0 set npkts_]

set bw10 [$sink1 set lastPktTime_]


set bw11 [$sink1 set npkts_]

set bw12 [$sink2 set lastPktTime_]


set bw13 [$sink2 set npkts_]

set bw14 [$sink3 set lastPktTime_]


set bw15 [$sink3 set npkts_]

puts $f0 "$now [expr (($bw0+$holdrate0)*8)/(2*$time*1000000)]"


puts $f1 "$now [expr (($bw1+$holdrate1)*8)/(2*$time*1000000)]"
puts $f2 "$now [expr (($bw2+$holdrate2)*8)/(2*$time*1000000)]"
puts $f3 "$now [expr (($bw3+$holdrate3)*8)/(2*$time*1000000)]"

# Record Packet Loss Rate in File


puts $f4 "$now [expr $bw4/$time]"
puts $f5 "$now [expr $bw5/$time]"
puts $f6 "$now [expr $bw6/$time]"
puts $f7 "$now [expr $bw7/$time]"

# Record Packet Delay in File

if { $bw9 > $holdseq0 } {


puts $f8 "$now [expr ($bw8 - $holdtime0)/($bw9 - $holdseq0)]"
} else {
puts $f8 "$now [expr ($bw9 - $holdseq0)]"
}

if { $bw11 > $holdseq1 } {

puts $f9 "$now [expr ($bw10 - $holdtime1)/($bw11 - $holdseq1)]"

} else {

puts $f9 "$now [expr ($bw11 - $holdseq1)]"

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

if { $bw13 > $holdseq2 } {

puts $f10 "$now [expr ($bw12 - $holdtime2)/($bw13 - $holdseq2)]"

} else {

puts $f10 "$now [expr ($bw13 - $holdseq2)]"

if { $bw15 > $holdseq3 } {

puts $f11 "$now [expr ($bw14 - $holdtime3)/($bw15 - $holdseq3)]"

} else {

puts $f11 "$now [expr ($bw15 - $holdseq3)]"

$sink0 set bytes_ 0


$sink1 set bytes_ 0
$sink2 set bytes_ 0
$sink3 set bytes_ 0

$sink0 set nlost_ 0


$sink1 set nlost_ 0
$sink2 set nlost_ 0
$sink3 set nlost_ 0

set holdtime0 $bw8


set holdseq0 $bw9

set holdrate0 $bw0


set holdrate1 $bw1
set holdrate2 $bw2
set holdrate3 $bw3

#Re-schedule the procedure


$ns at [expr $now+$time] "record"
}

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

Department of IT, Kakatiya Institute of Technology & Science, Warangal


Networks Simulation Laboratory

$ns at 60.0 "$n($i) reset";

$ns at 0.0 "record"


$ns at 10.0 "$cbr0 start"
$ns at 10.0 "$cbr1 start"
$ns at 10.0 "$cbr2 start"
$ns at 10.0 "$cbr3 start"
$ns at 50.0 "$cbr0 stop"
$ns at 50.0 "$cbr1 stop"
$ns at 50.0 "$cbr2 stop"
$ns at 50.0 "$cbr3 stop"
$ns at 60.0 "finish"

puts "Starting Simulation..."

#Run the simulation


$ns run

Department of IT, Kakatiya Institute of Technology & Science, Warangal

You might also like