Professional Documents
Culture Documents
3. Programs and exercise problems must be executed with in the current lab
session.
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.
7. In-time submission i.e. completion in the current session yields 100 % marks,
otherwise will be evaluated for 50% marks.
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:
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.
Experiment-I
OBJECTIVE:
This Lab Session will develop student's knowledge in
Writing code to access internet addresses using network programming in
Java
OUTCOME:
Program:
import java.io.*;
import java.net.*;
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());
try {
System.out.println(address);
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”.
import java.net.*;
{
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.");
}
}
}
% java MyAddress
titan.oit.unc.edu/152.2.22.14
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:
Reference:https://www.oreilly.com/library/view/java-network-programming/9781449365936
/ch04.html
The Classes
ContentHandler
DatagramPacket
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
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.
SERVER PROGRAMMING
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.
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);}
}
}
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);
Output
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.
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.
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));
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.
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.
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)
{
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:
OUTCOME:
Upon completion of this lab, students will be able to
simulate different types of networks using tcl scripts.
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
$ns run
Output:
Viva Voce:
1. How to connect nodes?
2. Show the syntax of Setup a FTP over TCP connection.
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
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
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
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
# 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
$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-
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.
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:
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.
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'.
First of all, you need to create a simulator object. This is done with the command
Now we open a file for writing that is going to be used for the nam trace data.
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.
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'.
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.
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.
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"
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
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.
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
This code allows you to set different colors for each flow id.
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.
Change the link definition for the link between n2 and n3 to the following line.
The queueing should be 'fair' now. The same amount of blue and red packets should be
dropped.
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.
The following piece of code might look a bit more complicated at first.
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.
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).
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.
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.
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.
Program :
#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)
Note :
BEGIN {
recvdSize = 0
startTime = 1e6
stopTime = 0
}
# 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
}
}
END {
printf("Average Throughput[kbps] = %.2f\t\t StartTime=%.2f\tStopTime=%.2f\n",
(recvdSize/(stopTime-startTime))*(8/1000),startTime,stopTime)
}
In order to generate a trace file. we have to create a trace file in Otcl script.
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.
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.
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).
“-”: 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 :
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.
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.
# tcp 0
# \
# \
# 2------------3
# /
# /
# cbr 1
# 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
TCP connections with delays and initial transmission times created at random
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
#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 } {
#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]
}
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.
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
set dly($i) 1
puts $param "startT($i) $startT($i) sec"
}
#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]
}
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
#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]
}
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.
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
#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]
}
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.
Program: wrls1.tcl
# Define options
set val(chan) Channel/WirelessChannel; # channel type
set val(prop) Propagation/TwoRayGround; # radio-propagation model
create-god $val(nn)
#
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
#
# 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"
$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
create-god $val(nn)
#
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
#
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON
# 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"
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
# 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
create-god $val(nn)
#
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
#
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON
# 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"
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
#----------------------------------------------------------------
#############################################################
#----------------------------------------------------------------------
# Set up simulator objects
#----------------------------------------------------------------------
#############################################################
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
#############################################################
$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"
#############################################################
#node position setting
#############################################################
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_]
} else {
} else {
} else {