Cn Lab Record
Cn Lab Record
1
Ex. No:
Learn to use commands like tcpdump, netstat, ipconfig,
Date: nslookup and traceroute. Capture ping and traceroute PDUs
using a network protocol analyzer and examine
AIM
COMMANDS
1. Tcpdump
To display all traffic between two hosts (represented by variables host1 and
host2): # tcpdumphost host1 and host2
Display traffic from a source or destination host only:
To display traffic from only a source (src) or destination (dst) host: # tcpdump
src host
# tcpdump dst host
Display traffic for a specific protocol
Provide the protocol as an argument to display only traffic for a specific
protocol, for example tcp,udp, icmp, arp
# tcpdump protocol
For example to display traffic only for the tcp traffic :
# tcpdump tcp
Filtering based on source or destination
port To filter based on a source or destination
2
port: # tcpdump src port ftp # tcpdump dst port
http
3
2. Netstat
Netstat is a common command line TCP/IP networking available in most
versions of Windows, Linux, UNIX and other operating systems.
Netstat provides information and statistics about protocols in use and current
TCP/IP network connections. The Windows help screen analogous to a Linux or
UNIX for netstat reads as follows: displays protocol statistics and current
TCP/IP network connections.
#netstat
3. ipconfig
In Windows, ipconfig is a console application designed to run from the
Windows command prompt. This utility allows you to get the IP address
information of a Windows computer.
Using ipconfig
From the command prompt, type ipconfig to run the utility with default
options. The output of the default command contains the IP address, network
mask, and gateway for all physical and virtual network adapter.
4
#ipconfig
4. nslookup
The nslookup (which stands for name server lookup) command is a network
utility program used to obtain information about internet servers. It finds name
server information for domains by querying the Domain Name System.
The nslookup command is a powerful tool for diagnosing DNS problems. You
know you're experiencing a DNS problem when you can access a resource by
specifying its IP address but not its DNS name.
#nslookup
5. Trace route
Trace route uses Internet Control Message Protocol (ICMP) echo packets with
variable time to live (TTL) values. The response time of each hop is calculated.
To guarantee accuracy, each hop is queried multiple times (usually three times)
to better measure the response of that particular hop.
Trace route is a network diagnostic tool used to track the pathway taken by a
packet on an IP network from source to destination. Trace route also records the
time taken for each hop the packet makes during its route to the destination.
Trace
5
route uses Internet Control Message Protocol (ICMP) echo packets with
variable time to live (TTL) values.
The response time of each hop is calculated. To guarantee accuracy, each hop is
queried multiple times (usually three times) to better measure the response of
that particular hop. Trace route sends packets with TTL values that gradually
increase from packet to packet, starting with TTL value of one. Routers
decrement TTL values of packets by one when routing and discard packets
whose TTL value has reached zero, returning the ICMP error message ICMP
Time Exceeded.
For the first set of packets, the first router receives the packet, decrements the
TTL value and drops the packet because it then has TTL value zero. The router
sends an ICMP Time Exceeded message back to the source. The next set of
packets are given a TTL value of two, so the first router forwards the packets,
but the second router drops them and replies with ICMP Time Exceeded.
Proceeding in this way, trace route uses the returned ICMP Time Exceeded
messages to build a list of routers that packets traverse, until the destination is
reached and returns an ICMP Echo Reply message.
With the tracert command shown above, we're asking tracert to show us the
path from the local computer all the way to the network device with the
hostname www.google.com.
#tracert google.com
6
5. Ping
The ping command sends an echo request to a host available on the network.
Using this command, you can check if your remote host is responding well or
not. Tracking and isolating hardware and software problems. Determining the
status of the network and various foreign hosts. The ping command is usually
used as a simple way to verify that a computer can communicate over the
networkwith another computer or network device. The ping command operates
by sending Internet Control Message Protocol (ICMP) Echo Request messages
to the destination computer and waiting for a response
# ping172.16.6.2
RESULT
Thus, the various networks commands like tcpdump, netstat, ipconfig, nslookup
and traceroute ping are executed successfully.
7
Ex. No:
Write a HTTP web client program to download a web page
Date: using TCP sockets
AIM
To write a java program for socket for HTTP for web page upload and download.
ALGORITHM
Client:
1. Start.
6. Stop.
Server:
1. Start
2. Create socket, bind IP address and port number with the created socket and
make server a listening server.
7. Stop.
8
PROGRAM
CLIENT:
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Client{
public static void main(String args[]) throws
Exception{ Socket soc;
BufferedImage img = null;
soc=new Socket("localhost",4000);
System.out.println("Client is running. ");
try {
System.out.println("Reading image from disk. ");
img = ImageIO.read(new
File("digital_image_processing.jpg")); ByteArrayOutputStream
baos = new ByteArrayOutputStream(); ImageIO.write(img,
"jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Sending image to server. ");
OutputStream out = soc.getOutputStream();
9
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
}catch (Exception e)
{ System.out.println("Exception: " +
e.getMessage()); soc.close();
}
soc.close();
}
}
SERVER:
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
public static void main(String args[]) throws
Exception{ ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
10
socket=server.accept();
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new
DataInputStream(in); int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new
ByteArrayInputStream(data); BufferedImage
bImage = ImageIO.read(ian); JFrame f =new
JFrame("Server");
ImageIcon icon = newImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}}
OUTPUT
When you run the client code, following output screen would appear on client
side.
11
RESULT
Thus, the socket program for HTTP for web page upload and download was
developed and executed successfully.
12
Ex. No:
Applications using TCP sockets like:
a. Echo client and Echo server
Date: b. Chat
AIM
b. Chat
ALGORITHM
Client:
1. Start
9. Stop
Server:
1. Start
3. Accept the connection request sent by the client for connection establishment
13
4. Receive the message sent by the client
7. Close the connection when client initiates termination and server becomes a
listening server, waiting for clients.
8. Stop.
PROGRAM
ESERVER:
import java.net.*;
import java.io.*;
public class EServer
{
public static void main(String args[])
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps; Socket c=null; try
{
s=new ServerSocket(9000);
}
catch(IOException e)
{
}
try
{
System.out.println(e);
14
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream()); while(true)
{
line=is.readLine();ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
ECLIENT:
import java.net.*;
import java.io.*;
public class EClient
{
public static void main(String args[])
{
Socket c=null; String line;
DataInputStream is,is1;
PrintStream os;
try
{
InetAddress ia = InetAddress.getLocalHost();
c=new Socket(ia,9000);
}
15
catch(IOException e)
{
}
try
{
System.out.println(e);
os=new PrintStream(c.getOutputStream()); is=new
DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream()); while(true)
{
System.out.println("Client:"); line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}
}
catch(IOException e)
{
System.out.println("Socket Closed!");
}}}
OUTPUT
Server
C:\Program Files\Java\jdk1.5.0\bin>javac EServer.java C:\Program Files\Java\jdk1.5.0\
bin>java EServer C:\Program Files\Java\jdk1.5.0\bin>
Client
C:\Program Files\Java\jdk1.5.0\bin>javac EClient.java C:\Program Files\Java\jdk1.5.0\
bin>java EClient
Client: Hai Server
16
Server: Hai
Server Client:
Hello Server:
Hello Client: end
Server: end
Client: ds
Socket Closed!
B. Chat
AIM
ALGORITHM
2. Both can be run in the same machine or different machines. If both are
running in the machine, the address to be given at the client side is local host
address.
3. If both are running in different machines, then in the client side we need to
specify the ip address of machine in which server application is running
PROGRAM
CHATSERVER.JAVA:
import java.net.*;
import java.io.*;
public class chatserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();
17
BufferedReader cin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{
s=cin.readLine();
if (s.equalsIgnoreCase("END"))
{
cout.println("BYE"); break;}
System. out.print("Client : "+s+"\n"); System.out.print("Server : ");
s=stdin.readLine(); cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close();
}
}
CHATCLIENT.JAVA:
import java.net.*;
import java.io.*;
public class chatclient
{
public static void main(String args[]) throws Exception
{
18
Socket sk=new Socket("127.0.0.1",2000);
BufferedReader sin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while (true)
{
System.out.print("Client : ");
s=stdin.readLine(); sout.println(s); s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close(); stdin.close();
}}
OUTPUT
Server:
E:\nwlab>javac chatserver.java E:\nwlab>java chatserver
Client: hi
Server: hi
Client:
E:\nwlab>javac chatclient.java E:\nwlab>java chatclient
Client: hi
Server: hi
19
RESULT
Thus, the java application program using TCP Sockets was developed and
executed successfully.
20
Ex. No:
Simulation of DNS using UDP sockets.
Date:
AIM
ALGORITHM
Server:
1. Start
6. Get the IP address mapped for the host name from the table.
8. Send the IP address for the requested host name to the client
9. Stop.
Client:
1. Start
21
6. Receive the reply datagram and read the IP address for the requested host
name
8. Stop.
PROGRAM
DNS SERVER:
import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++){
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140",
"69.63.189.16"};
System.out.println("Press Ctrl + C to Quit"); while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362); byte[] senddata =
new byte[1021];
22
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length); serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress(); int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen); if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata,
senddata.length,ipaddress,port); serversocket.send(pack);
serversocket.close();
}
}
}
DNS CLIENT:
import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress; if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
23
ipaddress,portaddr);
ipaddress = InetAddress.getByName(args[0]); byte[] senddata = new
byte[1024];
byte[] receivedata = new byte[1024]; int portaddr = 1362;
System.out.print("Enter the hostname : "); String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length,
clientsocket.send(pack);
DatagramPacket recvpack =new
DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData()); System.out.println("IP
Address: " + modified); clientsocket.close();
}
}
OUTPUT
Server:
javac udpdnsserver.java java udpdnsserver
Press Ctrl + C to Quit Request for host yahoo.com Request for host
cricinfo.com
Request for host youtube.com
Client:
Javac udpdnsclient.java
Java udpdnsclient
Enter the hostname: yahoo.com IP Address: 68.180.206.184
java udpdnsclient
Enter the hostname: cricinfo.com IP Address: 80.168.92.140
java udpdnsclient
Enter the hostname: youtube.com IP Address: Host Not Found
24
RESULT
Thus, the java application program using UDP Sockets to implement DNS was
developed and executed successfully
25
Ex. No:
Use a tool like Wireshark to capture packets and examine the
Date: packets
Installing Wireshark
26
Download the Windows Installer (64 bit).
Click on the link for your version of software, and you will see a pop-up box at
the foot of your screen.
Choose run, and when the UAC prompt appears, choose yes. This will bring
up the installation wizard.
Keep pressing ‘Next’ and accept the defaults. The installation will commence,
and the pop-up box below will appear. Accept the license agreement and press I
Agree. Accept the default settings.
Accept the default settings by pressing Next. The following wizard will appear
(see below). Press Finish.
27
The Wireshark installation will still be running in the background. It should take
roughly another 2-3 minutes. The wizard will appear to say the installation is
complete. Select Next, then Finish. You will now see a Wireshark shortcut on
the desktop, the same as below:
The view above shows The Main Window, which is broken into different
sections: The Menu: This is broken into the following 11 headings: File, Edit,
View, Go, Capture, Analyze, Statistics, Telephony, Wireless, Tools, Help. The
28
Filter Toolbar: This has a filter pane when you type in the protocol that you
want to view. The Packet List: This shows all packets that are captured and is
shown in blue in the preceding image. The Packet Details Pane: This is the
gray area that shows the protocol fields of the packet. The Packet Bytes Pane:
This shows a canonical hex dump of the packet data.
Make sure that you have the administrative privileges to start a live capture
on your device
Once these three things are done, you’re ready to start the capture process.
When you use Wireshark to capture packets, they are displayed in a human-
readable format to make them legible to the user. You can also break packets
down with filters and color-coding if you wish to see more specific
information. When you first open up Wireshark, you’ll be met by the following
launch screen:
29
The first thing you need to do is look at the available interfaces to capture. To
do this, select Capture > Options. The “Capture Interfaces” dialog box will
then open as shown below:
Check the box of the interface you want to capture and press the Start button to
start. You can select multiple interfaces if you want to capture data from
multiple sources simultaneously.
On Unix or Linux, the dialog box is shown in a similar style like this:
30
Promiscuous Mode
To activate promiscuous mode, click on the Capture Options dialog box and
click promiscuous mode.
In theory, this should show you all the traffic active on your network. The
promiscuous mode box is shown below:
However, this often isn’t the case. Many network interfaces are resistant to
promiscuous mode, so you need to check the Wireshark website for information
on your specific hardware.
On Windows, it’s useful to open Device Manager and check whether you have
your settings configured to reject promiscuous mode. For example:
31
(Simply click on network and then make sure that your promiscuous mode
setting are set to Allow All).
If you have your settings set to “reject” promiscuous mode, then you’re going to
limit the number of packets Wireshark captures. So even if you have
promiscuous mode enabled on Wireshark check your Device Manager to make
sure that your interface isn’t blocking any data from coming through.
Taking the time to check through your network infrastructure will ensure
Wireshark receives all the necessary packets of data.
Once you’ve captured your network data, you’ll want to look at your captured
packets. In the screenshot below you’ll see three panes, the packet list pane, the
packet bytes pane, and the packet details pane.
If you want more information, you can click on any of the fields in each packet
to see more. When you click on a packet, you’re shown a breakdown of its
internal bytes in the byte view section.
Packet List
The packet list pane is shown at the top of the screenshot. Each piece is broken
down to a number with time, source, destination, protocol and support
information.
32
Packet Details
Packet details can be found in the middle, showing the protocols of the chosen
packet. You can expand each section by clicking on the arrow next to your row
of choice. You can also apply additional filters by right-clicking on the chosen
item.
Packet Bytes
The packet bytes pane is shown at the bottom of the page. This pane shows the
internal data of your selected packet. If you highlight part of the data in this
section, its corresponding information is also highlighted in the packet details
pane. By default, all data is shown in hexadecimal format. If you want to
change it to bit format, right-click the pane and select this option from the
context menu.
RESULT
Thus, Wireshark tool is used to Capture packets and examine the packets.
33
Ex. No:
Write a code simulating ARP /RARP protocols
Date:
AIM
To write a java program for simulating ARP and protocols using TCP.
ALGORITHM
Client:
3. Get the IP address to be converted into MAC address from the user.
5. Receive the MAC address for the IP address from the server.
Server:
2. Create the socket, bind the socket created with IP address and port number
and make it a listening socket.
4. Server maintains the table in which IP and corresponding MAC addresses are
stored.
34
6. Retrieve the corresponding MAC address for the IP address and send it to the
client.
7. Close the connection with the client and now the server becomes a listening
server waiting for the connection request from other clients
8. Stop
PROGRAM
CLIENT:
import java.io.*; import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139)
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine(); dout.writeBytes(str1+'\n'; String str=din.readLine();
System.out.println("The Physical Address is: "+str);clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}}
}
35
SERVER:
import java.io.*; import java.net.*; import java.util.*; class Serverarp
{
public static void main(String args[])
{
try{
ServerSocket obj=new ServerSocket(139); Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n'); break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}}
}
36
OUTPUT
E:\networks>java Serverarp E:\networks>java Clientarp Enter the Logical
address (IP): 165.165.80.80
The Physical Address is: 6A:08: AA:C2
AIM
To write a java program for simulating RARP and protocols using UDP
ALGORITHM
Client:
3. Get the MAC address to be converted into IP address from the user.
5. Receive the datagram from the server and display the corresponding
IP address.
6. Stop
Server:
37
3. Create the datagram socket
4. Receive the datagram sent by the client and read the MAC address sent.
5. Retrieve the IP address for the received MAC address from the table.
7. Stop
PROGRAM
CLIENT:
import java.io.*; import java.net.*; import java.util.*; class Clientrarp12
{
public static void main(String args[])
{
try
{
}
DatagramSocket client=new DatagramSocket(); InetAddress
addr=InetAddress.getByName("127.0.0.1"); byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):")
String str=in.readLine(); sendbyte=str.getBytes();
DatagramPacket
sender=newDatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length); client.receive(receiver);
38
String s=new String(receiver.getData()); System.out.println("The Logical
Address is(IP): "+s.trim()); client.close();
catch(Exception e)
{
System.out.println(e);
}}}
SERVER:
import java.io.*; import java.net.*; import java.util.*; class Serverrarp12
{
public static void main(String args[])
{
try{ DatagramSocket server=new DatagramSocket(1309); while(true)
{
byte[] sendbyte=new byte[1024]; byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length); server.receive(receiver);
String str=new String(receiver.getData()); String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(mac[i]))
{
}}
break;
sendbyte=ip[i].getBytes(); DatagramPacket sender = new
DatagramPacket(sendbyte,sendbyte.length,addr,port); server.send(sender);
39
break;
}}}catch(Exception e)
{
System.out.println(e);
}}}
OUTPUT
I:\ex>java Serverrarp12 I:\ex>java Clientrarp12
Enter the Physical address (MAC):
6A:08: AA:C2
The Logical Address is (IP): 165.165.80.80
RESULT
Thus, the program for implementing to display simulating ARP and RARP
protocols was executed successfully and output is verified.
40
Ex. No:
Study of Network simulator (NS)
Date:
AIM
THEORY
41
BASIC ARCHITECTURE
Figure 2.1 shows the basic architecture of NS2. NS2 provides users with
executable command ns which takes on input argument, the name of a Tcl
simulation scripting file. Users are feeding the name of a Tcl simulation script
(which sets up a simulation) as an input argument of an NS2 executable
commands.In most cases, a simulation trace file is created, and is used to plot
graph and/or to create animation. NS2 consists of two key languages: C++ and
Object-oriented Tool Command Language (OTcl). While the C++ definesthe
internal mechanism (i.e., a backend) of the simulation objects, the OTcl sets up
simulation by assembling and configuring the objects as well as scheduling
discrete events (i.e., a frontend).
The C++ and the OTcl are linked together using TclCL. Mapped to a C++
object, variables in the OTcl domains are sometimes referred to as handles.
Conceptually, a handle (e.g., n as a Node handle) is just a string (e.g.,_o10) in
the OTcl domain, and does not contain any functionality. Instead, the
functionality (e.g., receiving packet) is defined in the mapped C++ object (e.g.,
of class Connector). In the OTcl domain, a handle acts as a frontend which
interacts with users and other OTcl objects. Itdefines its own procedures and
variables to facilitate the interaction. Note that the member procedures and
variables in the OTcl domain are called instance procedures (instprocs) and
instance variables (instvars), respectively. Before proceeding further, the readers
42
are encouraged to
43
learn C++ and OTcl languages. We refer the readers to [14] for the detail of C+
+, while a brief tutorial of Tcl and OTcl tutorial are given in Appendices A.1
and A.2, respectively.
NS2 provides a large number of built-in C++ objects. It is advisable to use these
C++ objects to set up a simulation using a Tcl simulation script. However,
advance users may find these objects insufficient. They need to develop their
own C++ objects, and use aOTcl configuration interface to put together these
objects. After simulation, NS2 outputs either text-based or animation-based
simulation results. To interpret these results graphically and interactively, tools
such as NAM (Network AniMator) and XGraph are used. To analyze a
particular behavior of the network, users can extract a relevant subset of text-
based data and transform it to a more conceivable presentation.
CONCEPT OVERVIEW
NS uses two languages because simulator has two different kinds of things it
needs to do. On one hand, detailed simulations of protocols requires a systems
programming language which can efficiently manipulate bytes, packet headers,
and implement algorithms that run over large data sets. For these tasks run-time
speed is important and turn-around time (run simulation, find bug, fix bug,
recompile, re-run) is less important. On the other hand, a large part of network
research involves slightly varying parameters or configurations, or quickly
exploring a number of scenarios.
In these cases, iteration time (change the model and re-run) is more important.
Since configuration runs once (at the beginning of the simulation), run-time of
this part of the task is less important. ns meets both of these needs with two
languages, C++ and OTcl.
Tcl scripting
44
• Tcl runs on most of the platforms such as Unix, Windows, andMac.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Hello World!
Variables
Create the event scheduler Open new files & turn on the tracing Create the
nodes Setup the links
Set the time of traffic generation (e.g., CBR, FTP) Terminate the simulation
NS Simulator Preliminaries.
45
set ns [new Simulator]
Which is thus the first line in the tcl script. This line declares a new variable as
using the set command, you can call this variable as you wish, In general people
declares it as ns because it is an instance of the Simulator class, so an object the
code[new Simulator] is indeed the installation of the class Simulator using the
reserved word new.
In order to have output files with data on the simulation (trace files) or files
used for visualization (nam files), we need to create the files using ―open
command:
Once we define several nodes, we can define the links that connect them. An
example of a definition of a link is:
Which means that $n0 and $n2 are connected using a bi-directional link that has
10ms of propagation delay and a capacity of 10Mb per sec for each direction.
46
To define a directional link instead of a bi-directional one, we should replace
―duplex-link by
―simplex-link.
There are number variants of the TCP protocol, such as Tahoe, Reno,
NewReno, Vegas. The type of agentappears in the first line:
The command $ns attach-agent $n0 $tcpdefines the source node of the tcp
connection.
The command set sink [new Agent /TCPSink] Defines the behavior of the
destination node of TCP andassigns to it a pointer called sink.
47
The below shows the definition of a CBR application using a UDP agent
The command $ns attach-agent $n4 $sink defines the destination node. The
command $ns connect
$tcp $sink finally makes the TCP connection between the source and
destination nodes.
TCP has many parameters with initial fixed defaults values that can be changed
if mentioned explicitly. For example, the default TCP packet size has a size of
1000bytes.This can be changed to another value, say 552bytes, using the
command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can
identify them with different colors in the visualization part. This is done by the
command $tcp set fid_ 1 that assigns to the TCP connection a flow
identification of ―1.We shall later give the flow identification of ―2‖ to the
UDP connection.
RESULT
48
Ex. No:
CONGESTION CONTROL IN TCP
Date:
CONGESTION CONTROL
Congestion refers to a network state where a node or link carries so much data
that it may deteriorate network service quality, resulting in queuing delay, frame
or data packet loss and the blocking of new connections.
Open Loop Technique and closed Loop Technique are utilized in ns2 program
for congestion control.
Open loop
o Acknowledgement policy.
o Retransmission policy.
o Discarding policy.
o Window policy.
o Admission policy.
Closed loop
o Explicit feedback.
o Back pressure.
49
o Implicit feedback.
o Choke packet.
50
$ns attach-agent $n0 $tcp1
set tcp2 [new Agent/TCP/Reno]
$ns attach-agent $n1 $tcp2
set tcp3 [new Agent/TCP/Reno]
$ns attach-agent $n2 $tcp3
set tcp4 [new Agent/TCP/Reno]
$ns attach-agent $n1 $tcp4
$tcp1 set fid_ 1
$tcp2 set fid_ 2
$tcp3 set fid_ 3
$tcp4 set fid_ 4
# receiving (sink) node
set sink1 [new Agent/TCPSink]
$ns attach-agent $n4 $sink1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n5 $sink2
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
set sink4 [new Agent/TCPSink]
$ns attach-agent $n4 $sink4
# establish the traffic between the source and sink
$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
$ns connect $tcp3 $sink3
$ns connect $tcp4 $sink4
# Setup a FTP traffic generator on "tcp"set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ftp1 set type_ FTP
51
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
$ftp2 set type_ FTP
set ftp3 [new Application/FTP]
$ftp3 attach-agent $tcp3
$ftp3 set type_ FTP
set ftp4 [new Application/FTP]
$ftp4 attach-agent $tcp4
$ftp4 set type_ FTP
set p0 [new Agent/Ping]
$ns attach-agent $n0
$p0set p1 [new Agent/Ping]
$ns attach-agent $n4
$p1#Connect the two agents
$ns connect $p0 $p1
# Method call from ping.cc file Agent/Ping instprocrecv {from rtt} {
$self instvar node_
puts "node [$node_ id] received ping answer from \
$from with round-trip-time $rttms."
}
# start/stop the traffic
$ns at 0.2 "$p0 send"
$ns at 0.3 "$p1 send"
$ns at 0.5 "$ftp1 start"
$ns at 0.6 "$ftp2 start"
$ns at 0.7 "$ftp3 start"
$ns at 0.8 "$ftp4 start"
$ns at 66.0 "$ftp4 stop"
52
$ns at 67.0 "$ftp3 stop"
$ns at 68.0 "$ftp2 stop"
$ns at 70.0 "$ftp1 stop"
$ns at 70.1 "$p0 send"
$ns at 70.2 "$p1 send"
# Set simulation end time
$ns at 80.0 "finish"
# procedure to plot the congestion
window# cwnd_ used from tcpreno.
cc file
proc plot Window
{tcpSourceoutfile} {global ns
set now [$ns now]
set cwnd_ [$tcpSource set cwnd_]
# the data is recorded in a file called
congestion.xg.puts $outfile "$now $cwnd_"
$ns at [expr $now+0.1] "plotWindow $tcpSource $outfile"
}
set outfile [open "congestion.xg" w]
$ns at 0.0 "plotWindow $tcp1
$outfile"proc finish {}
{ exec
namcongestion.nam&
exec xgraphcongestion.xg -geometry
300x300 &exit 0
}
# Run simulation
$ns run
53
OUTPUT
RESULT
Thus, the Congestion Control Algorithm has been Simulated and studied
54
Ex. No:
AIM
In theory, a transport layer protocol could be a very simple software routine, but
the TCP protocol cannot be called simple. Why use a transport layer which is as
complex as TCP? The most important reason depends on IP's unreliability. In
fact all the layers below TCP are unreliable and deliver the datagram hop by-
hop. The IP layer delivers the datagram hop-by-hop and does not guarantee
delivery of a datagram; it is a connectionless system. IP simply handles the
routing of datagram’s; and if problems occur, IP discards the packet without a
second thought, generating an error message back to the sender in the process.
The task of ascertaining the status of the datagram sent over a network and
handling the resending of information if parts have been discarded falls to TCP.
TCP manages the flow of datagrams from the higher layers, as well as incoming
datagrams from the IP layer. It has to ensure that priorities and security are
respected. TCP must be capable of handling the termination of an application
above it that was expecting incoming datagrams, as well as failures in the lower
layers. TCP also must maintain a state table of all data streams in and out of the
TCP layer. The isolation of these services in a separate layer enables
applications to be designed without regard to flow control or message
reliability. Without the TCP layer, each application would have to implement
the services themselves, which is a waste
of resources.
55
TCP resides in the transport layer, positioned above IP but below the upper
layers and their applications. TCP resides only on devices that actually process
datagram’s, ensuring that the datagram has gone from the source to target
machines. It does not reside on a device that simply routes datagrams, so there
is no TCP layer in a gateway. This makes sense, because on a gateway the
datagram has no need to go higher in the layered model than the IP layer.
proc finish {} {
global ns nf
$ns flush-traceclose
exit 0 }
56
$ns duplex-link $r2 $h3 10Mb 20ms DropTail
$ns duplex-link $r2 $h4 5Mb 20ms DropTail
$ns duplex-link-op $h1 $r1 orient right-down
$ns duplex-link-op $h2 $r1 orient right-up
$ns duplex-link-op $r1 $r2 orient right
$ns duplex-link-op $r2 $h3 orient right-up
$ns duplex-link-op $r2 $h4 orient right-down
set udp [new Agent/UDP]
$ns attach-agent $h2 $udp
set cbr [new Application/Traffic/CBR]
#$cbr set interval_ 0.0005
$cbr attach-agent $udp
set null [new
Agent/Null]
$ns attach-agent
$h4 $null
set tcp [new Agent/TCP]
$ns attach-agent $h1 $tcp
set ftp [new Application/FTP]
#$ftp set interval_ 0.0005
$ftp attach-agent $tcp
set sink [new Agent/TCPSink]
RESULT
Thus, the NS2 with TCP and UDP packets has been Simulated and studied.
58
Ex. No:
AIM
To simulate and study the Distance Vector routing algorithm using simulation.
SOFTWARE REQUIRED
NS-2
THEORY
ALGORITHM
3. Open a nam trace file and define finish procedure then close the trace file,
and execute nam on tracefile.
59
8. Apply CBR Traffic over both UDP connections
PROGRAM
proc finish {} {
global nf ns tr
close $tr
exec
namout.nam&
exit 0
60
$ns duplex-link $n2 $n1 10Mb 10ms DropTail
Agent/Null]
$ns rtproto DV
$ns run
OUTPUT
RESULT
Thus, the Distance vector Routing Algorithm has been Simulated and studied.
62
Ex. No:
Simulation of Link State Routing Algorithm
Date:
AIM
To simulate and study the link state routing algorithm using simulation.
SOFTWARE REQUIRED
NS-2
THEORY
In link state routing, each router shares its knowledge of its neighbourhood with
every other router in the internetwork. (i) Knowledge about Neighbourhood:
Instead of sending its entire routing table a router sends info about its
neighborhood only. (ii) To all Routers: each router sends this information to
every other router on the internetwork not just to its neighbor. It does so by a
process called flooding. (iii)Information sharing when there is a change: Each
router sends out information about the neighbors when there is change.
PROCEDURE
The Dijkstra algorithm follows four steps to discover what is called the shortest
path tree (routing table) for each router: The algorithm begins to build the tree
by identifying its roots. The root router’s trees the router itself. The algorithm
then attaches all nodes that can be reached from the root. The algorithm
compares the tree’s temporary arcs and identifies the arc with the lowest
cumulative cost. This arc and the node to which it connects are now a
permanent part of the shortest path tree. The algorithm examines the database
and identifies every node that can be reached from its chosen node. These nodes
and their arcs are added temporarily
63
to the tree. The last two steps are repeated until every node in the network has
become a permanent part of the tree.
ALGORITHM
3. Open a nam trace file and define finish procedure then close the trace file,
and execute nam on tracefile.
9. Choose Link state routing protocol to transmit data from sender to receiver.
PROGRAM
$ns namtrace-all
$nfproc finish {
global ns nr nf
64
$ns flush-trace
close$nf
close$nr
exec namthro.nam&
exit 0
$cbr0 attach-agent
65
Agent/Null]
$ns rtproto LS
66
$ns at 45 "finish"
$ns run
OUTPUT
RESULT
Thus, the Link State Routing Algorithm has been Simulated and studied.
67
Ex. No:
Simulation of Error
Date: Detection Code (Like CRC)
AIM
ALGORITHM
2. Given a bit string, append 0S to the end of it (the number of 0s is the same as
the degree of the generator polynomial) let B(x) be the polynomial
corresponding to B.
7. Let T’ represent the bit stream the receiver gets and T’(x) the associated
polynomial. The
68
PROGRAM
import java.io.*;
class crc_gen
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
data_bits=Integer.parseInt(br.readLine());data=new int[data_bits];
data[i]=Integer.parseInt(br.readLine());
divisor[i]=Integer.parseInt(br.readLine());
69
for(int i=0; i< data_bits; i++)
System.out.print(data[i]);
System.out.println();
System.out.print(divisor[i]);
System.out.println();
*/
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/* CRC GENERATION */
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.print(div[i]);
System.out.println();
{ rem[j] = div[j];
70
for(int i=0;i<div.length;i++)
crc[i]=(div[i]^rem[i]);
System.out.println();
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/* ERROR DETECTION */
System.out.println();
crc[i]=Integer.parseInt(br.readLine());
System.out.print(crc[i]);
System.out.println();
rem[j] = crc[j];
rem=divide(crc, divisor,rem);
if(rem[i]!=0)
71
{
System.out.println("Error");
break;
if(i==rem.length-1)
System.out.println("No Error");
System.out.println("THANK YOU.......)");
int cur=0;
while(true)
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
cur++;
if((rem.length-cur)<divisor.length)
break;
return rem;
}}
72
OUTPUT
CRC code:
101100111
73
1
Error
THANK YOU.......)
RESULT
Thus, the above program for error checking code using was executed
successfully.
74