Lab_Manual
Lab_Manual
PAGE FACULTY
S.No. DATE NAME OF THE EXPERIMENT MARKS
NO. SIGN
c) File Transfer
4. Simulation of DNS using UDP sockets.
Use a tool like Wireshark to capture packets and
5.
examine the packets
a) Write a code simulating ARP protocols
6.
b) Write a code simulating RARP protocols
1
Ex.No:1 Learn to use commands like tcpdump, netstat, ifconfig, nslookup and
trace route. Capture ping and trace route PDUs using a network
Date: protocol analyzer and examine
AIM:
To use commands like tcpdump, netstat, ifconfig, nslookup and trace route. Capture
ping and trace route PDUs using a network protocol analyzer and examine.
PROCEDURE:
1. Tcpdump
Tcpdump is a command line utility that allows you to capture and analyse network traffic going
through your system.
To check if tcpdump is installed on your system:
$ which tcpdump
/usr/sbin/tcpdump
If tcpdump is not installed,
$ sudo apt install tcpdump
2
To capture packets with tcpdump
tcpdump -D: to see which interfaces are available for capture
3
Filter packets based on the source or destination IP Address
tcpdump -i any -c5 -nn src 172.16.20.138
4
2. netstat
netstat (network statistics) is a command line tool for monitoring network connections both
incoming and outgoing as well as viewing routing tables, interface statistics etc.
3. ifconfig
It displays the details of a network interface card like IP address, MAC Address, and the status
of a network interface card.
5
4. nslookup
nslookup (stands for “Name Server Lookup”) is a useful command for getting information from
DNS server. It is a network administration tool for querying the Domain Name System (DNS)
to obtain domain name or IP address mapping or any other specific DNS record.
5. tracert
The tracert command is used in Windows to map the journey that a packet of information
undertakes from its source to its destination.
$ tracert annauniv.edu
6
$ tracert 172.16.20.139
Capture ping and traceroute PDUs using a network protocol analyzer and examine.
To Open Wireshark
Open directly or use the following commands
# sudo wireshark
7
RESULT:
Thus commands like tcpdump, netstat, ifconfig, nslookup and traceroute was used. Ping and
traceroute PDUs using a network protocol analyzer was captured and examined.
8
Ex.No:2 Write a HTTP web client program to download a web page
Date: using TCP sockets
AIM:
To write a program in java to create a HTTP web client program to download a web page using
TCP sockets.
ALGORITHM:
1. Start the program.
2. Read the file to be downloaded from webpage.
3. To download an image, use java URL class which can be found under java.net package.
4. The file is downloaded from server and is stored in the current working directory.
5. Stop the program.
PROGRAM:
download.java
import java.io.*;
import java.net.URL;
public class download
{
public static void main(String[] args) throws Exception
{
try
{
String fileName = "html.jpg";
String website = "https://www.tutorialspoint.com/html/images/"+fileName;
System.out.println("Downloading File From: " + website);
URL url = new URL(website);
InputStream inputStream= url.openStream();
OutputStream outputStream= new FileOutputStream(fileName);
byte[] buffer = new byte[2048];
int length = 0;
9
while ((length = inputStream.read(buffer)) != -1)
{
System.out.println("Buffer Read of length: " + length);
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
catch(Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
}
}
OUTPUT:
RESULT:
Thus created a program in java for a HTTP web client program to download a web page using
TCP sockets is written and executed successfully.
10
Ex.No:3a
Applications using TCP Sockets - Echo Client and Echo Server
Date:
AIM:
To write a program in Java to implement an applications using TCP Sockets like Echo Client
and Echo Server.
ALGORITHM
1. Start the Program.
2. In Server:
a) Create a server socket and bind it to port.
b) Listen for new connection and when a connection arrives, accept it.
c) Read the data from client.
d) Echo the data back to the client.
e) Close all streams.
f) Close the server socket.
g) Stop.
3. In Client:
a) Create a client socket and connect it to the server’s port number.
b) Send user data to the server.
c) Display the data echoed by the server.
d) Close the input and output streams.
e) Close the client socket.
f) Stop.
4. Stop the program.
PROGRAM:
Server.java
import java.net.*;
import java.lang.*;
import java.io.*;
public class Server
{
11
public static final int PORT = 4000;
public static void main( String args[])
{
ServerSocket sersock = null;
Socket sock = null;
try
{
sersock = new ServerSocket(PORT);
System.out.println("Server Started :"+sersock);
try
{
sock = sersock.accept();
System.out.println("Client Connected :"+ sock);
DataInputStream ins = new DataInputStream(sock.getInputStream());
System.out.println(ins.readLine());
PrintStream ios = new PrintStream(sock.getOutputStream());
ios.println("Hello from server");
ios.close();
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket problem "+se.getMessage());
}
}
catch(Exception e)
{
System.out.println("Couldn't start " + e.getMessage()) ;
}
System.out.println(" Connection from: " + sock.getInetAddress());
}
}
12
Client.java
import java.lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class Client
{
public static void main(String args[])
{
Socket sock=null;
DataInputStream dis=null;
PrintStream ps=null;
System.out.println(" Trying to connect");
try
{
sock= new Socket(InetAddress.getLocalHost(),Server.PORT);
ps= new PrintStream(sock.getOutputStream());
ps.println(" Hi from client");
DataInputStream is = new DataInputStream(sock.getInputStream());
System.out.println(is.readLine());
}
catch(SocketException e)
{
System.out.println("SocketException " + e);
}
catch(IOException e)
{
System.out.println("IOException " + e);
}
finally
{
try
{
sock.close();
13
}
catch(IOException ie)
{
System.out.println(" Close Error :" + ie.getMessage());
}
}
}
}
OUTPUT:
RESULT:
Thus a program in Java implemented an applications using TCP Sockets like Echo Client and
Echo Server.
14
Ex.No:3b
Applications using TCP Sockets - CHAT
Date:
AIM:
To write a program in Java to implement an applications using TCP Sockets like chat.
ALGORITHM:
1. Start the Program.
2. In Server:
a) Create a server socket and bind it to port.
b) Listen for new connection and when a connection arrives, accept it.
c) Read Client's message and display it.
d) Get a message from user and send it to client.
e) Repeat steps 3-4 until the client sends "end".
f) Close all streams.
g) Close the server and client socket.
h) Stop.
3. In Client:
a) Create a client socket and connect it to the server’s port number.
b) Get a message from user and send it to server.
c) Read server's response and display it.
d) Repeat steps 2-3 until chat is terminated with "end" message.
e) Close all input/output streams.
f) Close the client socket.
g) Stop.
4. Stop the program.
PROGRAM:
tcpchatserver.java
import java.io.*;
import java.net.*;
class tcpchatserver
{
15
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(4000);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("Message from Client : " +CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
16
}
catch (Exception E)
{
System.out.println(E.getMessage());
}
}
}
tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
Clt = new Socket(InetAddress.getLocalHost(),4000);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("Message to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
17
SrvMsg = fromServer.readLine();
System.out.println("Message from Server : " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
}
OUTPUT:
RESULT:
Thus a program in Java implemented an application using TCP Sockets like Chat.
18
Ex.No:3c
Applications using TCP Sockets – FILE TRANSFER
Date:
AIM:
To write a java program for file transfer using TCP Sockets.
ALGORITHM:
1. Start the Program.
2. In Server:
a) Import java packages and create class file server.
b) Create a new server socket and bind it to the port.
c) Accept the client connection
d) Get the file name and stored into the BufferedReader.
e) Create a new object class file and readline.
f) If file is exists then FileReader read the content until EOF is reached.
g) Stop.
3. In Client:
a) Import java packages and create class file server.
b) Create a new server socket and bind it to the port.
c) Now connection is established.
d) The object of a BufferReader class is used for storing data content which has been retrieved
from socket object.
e) The connection is closed.
f) Stop.
4. Stop the program.
PROGRAM:
FileServer.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
19
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer
{
public static void main(String[] args) throws Exception
{
//Initialize Sockets
ServerSocket ssock = new ServerSocket(5000);
Socket socket = ssock.accept();
//The InetAddress specification
InetAddress IA = InetAddress.getByName("localhost");
//Specify the file
File file = new File("source.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
//Get socket's output stream
OutputStream os = socket.getOutputStream();
//Read File Contents into contents array
byte[] contents;
long fileLength = file.length();
long current = 0;
long start = System.nanoTime();
while(current!=fileLength){
int size = 10000;
if(fileLength - current >= size)
current += size;
else{
size = (int)(fileLength - current);
current = fileLength;
}
contents = new byte[size];
bis.read(contents, 0, size);
os.write(contents);
System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
20
}
os.flush();
//File transfer done. Close the socket connection!
socket.close();
ssock.close();
System.out.println("File sent succesfully!");
}}
FileClient.java
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) throws Exception{
//Initialize socket
Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);
byte[] contents = new byte[10000];
//Initialize the FileOutputStream to the output file's full path.
FileOutputStream fos = new FileOutputStream("source1.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = socket.getInputStream();
//No of bytes read in one read() call
int bytesRead = 0;
while((bytesRead=is.read(contents))!=-1)
bos.write(contents, 0, bytesRead);
bos.flush();
socket.close();
System.out.println("File saved successfully!");
}
}
21
source.txt (create a text file in the current working directory, to transfer)
Computer Networks Lab
OUTPUT:
source1.txt (The text file is transferred from server to client in the current working directory)
Computer Networks Lab
RESULT:
Thus the java program file transfer application using TCP Sockets was executed
22
Ex.No:4
SIMULATION OF DNS USING UDP SOCKETS
Date:
AIM:
To write a program in Java to perform Simulation of DNS using UDP sockets.
ALGORITHM:
1. Start the Program
2. In Server:
a) Create an array of hosts and its ip address in another array
b) Create a datagram socket and bind it to a port
c) Create a datagram packet to receive client request
d) Read the domain name from client to be resolved
e) Lookup the host array for the domain name
f) If found then retrieve corresponding address
g) Create a datagram packet and send ip address to client
h) Repeat steps 3-7 to resolve further requests from client
i) Close the server socket
j) Stop
3. In Client:
a) Create a datagram socket
b) Get domain name from user
c) Create a datagram packet and send domain name to the server
d) Create a datagram packet to receive server message
e) Read server's response
f) If ip address then display it else display "Domain does not exist"
g) Close the client socket
h) Stop
4. Stop the program.
23
PROGRAM:
dnsserver.java
import java.io.*;
import java.net.*;
public class dnsserver
{
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(8080);
byte[] senddata = new byte[1021];
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);
24
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();
}
}
}
dnsclient.java
import java.io.*;
import java.net.*;
public class dnsclient
{
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
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 8080;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
25
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:
RESULT:
Thus a program in Java is performed for Simulation of DNS using UDP sockets.
26
Ex.No:5
Use a tool like Wireshark to capture packets and examine the packets
Date:
AIM:
To use a tool like Wireshark to capture packets and examine the packets.
WIRESHARK:
Wireshark captures the data coming or going through the NICs on its device by using
an underlying packet capture library. By default, Wireshark captures on-device data only, but
it can capture almost all the data on its LAN if run in promiscuous mode. Currently, Wireshark
uses NMAP’s Packet Capture library(called npcap).
Getting Up and Running: After installation launch Wireshark, approve the administrator or
superuser privileges and you will be presented with a window that looks like this:
This window shows the interfaces on your device. To start sniffing select one interface
and click on the bluefin icon on the top left. The data capture screen has three panes. The top
pane shows real-time traffic, the middle one shows information about the chosen packet and
the bottom pane shows the raw packet data. The top pane shows source address(IPv4 or IPv6)
destination address, source and destination ports, protocol to which the packet belongs to and
additional information about the packet.
27
Since there are a lot of packets going in and out every second, looking at all of them
or searching for one type of packets will be tedious. This is why packet filters are provided.
Packets can be filtered based on many parameters like IP address, port number or protocol at
capture level or at display level. As obvious a display level filter will not affect the packets
being captured.
Some of the general capture filters are:
• host (capture the traffic through a single target)
• net( capture the traffic through a network or sub-network). “net” can be prefixed with
“src” or “dst” to indicate whether the data coming from or going to the target host(s).)
• port (capture the traffic through or from a port). “port” can be prefixed with “src” or
“dst” to indicate whether the data coming from or going to the target port.
• “and”, “not” and “or” logical connectives.(Used to combine multiple filters together).
There are some more basic filters and they can be combined very creatively. Another
range of filters, display filters are used to create abstraction on captured data. These basic
examples should provide a basic idea of their syntax:
• tcp.port==80/udp.port==X shows the tcp/udp traffic at port X.
• http.request.uri matches “parameter=value$” shows packets that are HTTP requests
at the application layer level and their URI ends with a parameter with some value.
• The logical connective and or and not work here too.
• ip.src==192.168.0.0/16 and ip.dst==192.168.0.0/16 will show traffic to and from
workstations and servers.
28
There is also a concept of colouring rules. Each protocol/port/other element is provided
a unique colour to make it easily visible for quick analysis. More details on colouring rules is
here
Plugins are extra pieces of codes that can be embedded into the native Wireshark.
Plugins help in analysis by:
• Showing parameter specific statistics and insights.
• Handling capture files and issues related to their formats.
• Collaborating with other tools and frameworks to set up an all-in-one network
monitoring solution.
With just the basic capability to see all the traffic going through your device or in your
LAN and the tools and plugins to help you in analysis, you can do a great deal of things with
your device. Like:
• Troubleshooting Internet connectivity problems with your device or WiFi.
• Monitoring your device for unwanted traffic that may be an indication of a malware
infection.
• Testing the working of your application that involve networking.
• Using it to just understand how computer networks work.
RESULT:
Thus, the packets capturing and examine the packets using a tool like Wireshark was done and
verified.
29
Ex.No:6a
SIMULATION OF ARP PROTOCOLS
Date:
AIM:
To write a java program to simulate ARP protocols.
ALGORITHM:
1. Start the program
2. In Client:
a) Using socket connection is established between client and server.
b) Get the IP address to be converted into MAC address.
c) Send this IP address to server.
d) Server returns the MAC address to client.
e) Stop.
3. In Server:
a) Accept the socket which is created by the client.
b) Server maintains the table in which IP and corresponding MAC addresses are stored.
c) Read the IP address which is send by the client.
d) Map the IP address with its MAC address and return the MAC address to client.
e) Stop.
4. Stop the program
PROGRAM:
Serverarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
30
ServerSocket obj=new ServerSocket(1122);
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);
}
}
}
Clientarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
31
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",1122);
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);
}
}
}
OUTPUT:
RESULT:
Thus a program in java simulated ARP protocols.
32
Ex.No:6b
SIMULATION OF RARP PROTOCOLS
Date:
AIM:
To write a program in java to simulate RARP protocols.
ALGORITHM:
1. Start the program
2. In Client:
a) Using socket connection is established between client and server.
b) Get the MAC address to be converted into IP address.
c) Send this MAC address to server.
d) Server returns the IP address to client.
e) Stop.
3. In Server:
a) Accept the socket which is created by the client.
b) Server maintains the table in which IP and corresponding MAC addresses are stored.
c) Read the MAC address which is send by the client.
d) Map the MAC address with its MAC address and return the IP address to client.
e) Stop.
4. Stop the program
PROGRAM:
serverrarp.java
import java.io.*;
import java.net.*;
import java.util.*;
public class serverrarp
{
public static void main(String args[])
{
33
try
{
DatagramSocket server = new DatagramSocket(1309);
while(true){
byte[] sendByte = new byte[1204];
byte[] receiveByte = new byte[1204];
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[] = {"10.0.3.186"};
String mac[] = {"D4:3D:7E:12:A3:D9"};
for (int i = 0; i < ip.length; i++) {
if(s.equals(mac[i]))
{
sendByte = ip[i].getBytes();
DatagramPacket sender = new DatagramPacket(sendByte,sendByte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
34
clientrarp.java
import java.io.*;
import java.net.*;
import java.util.*;
public class clientrarp
{
public static void main(String args[]){ try
{
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName("127.0.0.1");
byte[] sendByte = new byte[1204];
byte[] receiveByte = new byte[1024];
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical Address ");
String str = in.readLine();
sendByte = str.getBytes();
DatagramPacket sender = new DatagramPacket(sendByte,sendByte.length,addr,1309);
client.send(sender);
DatagramPacket receiver = new DatagramPacket(receiveByte,receiveByte.length);
client.receive(receiver);
String s = new String(receiver.getData());
System.out.println("The Logical Address is :" + s.trim());
client.close(); }
catch(Exception e)
{
System.out.println(e);
}}}
35
OUTPUT:
RESULT:
Thus a program in java simulated RARP protocols.
36
Ex.No:7
Study of Network simulator (NS)
Date:
AIM:
To study Network Simulator in detail.
INTRODUCTION:
Network Simulator (Version 2), widely known as NS2, is simply an event driven
simulation tool that has proved useful in studying the dynamic nature of communication
networks. Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2. In general, NS2 provides users with a way of
specifying such network protocols and simulating their corresponding behaviours. Due to its
flexibility and modular nature, NS2 has gained constant popularity in the networking research
community since its birth in 1989. Ever since, several revolutions and revisions have marked
the growing maturity of the tool, thanks to substantial contributions from the players in the
field. Among these are the University of California and Cornell University who developed the
REAL network simulator, 1 the foundation which NS is based on.
Since 1995 the Defence Advanced Research Projects Agency (DARPA) supported
development of NS through the Virtual Inter Network Testbed (VINT) project currently the
National Science Foundation (NSF) has joined the ride in development. Last but not the least,
the group of Researchers and developers in the community are constantly working to keep NS2
strong and versatile.
BASIC ARCHITECTURE:
37
Figure shows the basic architecture of NS2. NS2 provides users with executable
command ns which take 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 command ns.
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++ defines the 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 a 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. It may define 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 are encouraged to learn C++ and OTcl languages.
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 a OTcl
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 require 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
38
research involves slightly varying parameters or configurations, or quickly exploring 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.
39
$ns connect $udp $null
Creating Traffic (On Top of UDP)
set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp
Post-Processing Procedures
proc finish {}
{
global ns nf
$ns flush-trace close $nf
exec nam out.nam& exit 0
}
Schedule Events
$ns at <time> <event>
Call ‘finish’
$ns at 5.0 "finish"
Run the simulation
$ns run
RESULT:
Thus the study of Network Simulator was done successfully.
40
Ex.No:8
Study of TCP/UDP Performance Using Simulation Tool
Date:
AIM:
To study the performance of TCP/UDP using Simulation Tool (NS2)
ALGORITHM:
1. Create 4 nodes (n0, n1, n2, n3).
2. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms
of delay.
3. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay.
4. Each node uses a DropTail queue, of which the maximum size is 10.
5. A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent attached
to n3.
6. As default, the maximumsize of a packet that a "tcp" agent can generate is 1KByte.
7. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and frees the
received packets.
8. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3.
9. A"null" agent just frees the packets received.
10. 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.
11. 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:
41
#Open the NAM trace file
set nf [open out.namw]
$ns namtrace-all $nf
#Define a 'finish' procedure proc finish {} {
global ns nf
$ns flush-trace
#Close the NAMtrace file
close $nf
#Execute NAM on the trace file
exec nam out.nam&
exit 0
}
42
#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
43
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
OUTPUT:
RESULT:
Thus studied the performance of TCP/UDP using Simulation Tool (NS2).
44
Ex.No:9a
Simulation of Distance Vector Routing Algorithm
Date:
AIM:
To perform Simulation of Distance Vector Routing algorithm.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a namtrace file and define finish procedure then close the trace file, and execute nam
on trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose distance vector routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.
PROGRAM:
set ns [new Simulator]
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.namw]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
45
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
46
$ns rtproto DV
OUTPUT:
RESULT:
Thus performed Simulation of Distance Vector Routing algorithm.
47
Ex.No:9b
Simulation of Link State Routing Algorithm
Date:
AIM:
To perform Simulation of Link State Routing algorithm.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a namtrace file and define finish procedure then close the trace file, and execute nam
on trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose Link state routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.
PROGRAM:
set ns [new Simulator]
set nr [open link.tr w]
$ns trace-all $nr
set nf [open link.namw]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam link.nam &
exit 0
}
48
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
49
$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
OUTPUT:
RESULT:
Thus performed Simulation of Link State Routing algorithm.
50
Ex.No:10
Simulation of an Error Correction Code (like CRC)
Date:
AIM:
To write a program in Java to implement the Simulation of Error Correction Code.
ALGORITHM:
At sender side
1. Start the program
2. Read the number of bits to be sent. Let n be the Number of bits in data to be sent from sender
side.
3. Read the number of bits in the divisor. Let k be the Number of bits in the divisor (key
obtained from generator polynomial).
4. The binary data is first increased by adding k-1 zeros in the end of the data
5. Use modulo-2 binary division to divide binary data by the divisor and store remainder of
division.
6. Append the remainder at the end of the data to form the encoded data and send the same
At receiver side
1. Perform modulo-2 division again and if remainder is 0, then there are no errors.
Modulo 2 division
In each step, a copy of the divisor (or data) is XORed with the k bits of the dividend.
The result of the XOR operation (remainder) is (n-1) bits, which is used for the next
step after 1 extra bit is pulled down to make it n bits long.
When there are no bits left to pull down, we have a result. The (n-1)-bit remainder
which is appended at the sender side.
PROGRAM:
import java.io.*;
import java.util.*;
class crc
{
51
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n;
//Read input
System.out.println("Enter the size of the data:");
n = input.nextInt();
int data[] = new int[n];
System.out.println("Enter the data, bit by bit:");
for(int i=0 ; i < n ; i++)
{
System.out.println("Enter bit number " + (n-i) + ":");
data[i] = input.nextInt();
}
//Read Divisor
System.out.println("Enter the size of the divisor:");
n = input.nextInt();
int divisor[] = new int[n];
System.out.println("Enter the divisor, bit by bit:");
for(int i=0 ; i < n ; i++)
{
System.out.println("Enter bit number " + (n-i) + ":");
divisor[i] = input.nextInt();
}
//Perform Division
int remainder[] = divide(data, divisor);
for(int i=0 ; i < remainder.length-1 ; i++)
{
System.out.print(remainder[i]);
}
System.out.println("\nThe CRC code generated is:");
52
for(int i=0 ; i < data.length ; i++)
{
System.out.print(data[i]);
}
for(int i=0 ; i < remainder.length-1 ; i++)
{
System.out.print(remainder[i]);
}
System.out.println();
53
System.out.print("Remainder : ");
// If first bit of remainder is 1 then exor the remainder bits with divisor bits
if(remainder[0] == 1)
{
for(int j=1 ; j < divisor.length ; j++)
{
remainder[j-1] = exor(remainder[j], divisor[j]);
System.out.print(remainder[j-1]);
}
}
else
{
54
static void receive(int data[], int divisor[])
{
int remainder[] = divide(data, divisor);
for(int i=0 ; i < remainder.length ; i++)
{
if(remainder[i] != 0)
{
System.out.println("There is an error in received data...");
return;
}
}
System.out.println("Data was received without any error.");
}
}
55
OUTPUT:
RESULT:
Thus a program in Java implemented the Simulation of Error Correction Code (CRC).
56