0% found this document useful (0 votes)
8 views53 pages

Computer Network Lab

The document outlines various exercises related to networking and socket programming, including the use of commands like tcpdump, netstat, and traceroute, as well as the development of HTTP web client programs and applications using TCP sockets for echo clients, chat, and file transfer. Each exercise includes an aim, algorithms, and sample Java code for implementation. The document serves as a comprehensive guide for practical networking tasks and simulations.

Uploaded by

roshitha1208
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views53 pages

Computer Network Lab

The document outlines various exercises related to networking and socket programming, including the use of commands like tcpdump, netstat, and traceroute, as well as the development of HTTP web client programs and applications using TCP sockets for echo clients, chat, and file transfer. Each exercise includes an aim, algorithms, and sample Java code for implementation. The document serves as a comprehensive guide for practical networking tasks and simulations.

Uploaded by

roshitha1208
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

EX NO TITLE [Link]
1 LEARN TO USE COMMANDS LIKE TCPDUMP, NETSTAT, 3
IFCONFIG, NSLOOKUP AND TRACEROUTE. CAPTURE
PING AND TRACEROUTE PDUS USING A NETWORK
PROTOCOL ANALYZER AND EXAMINE

2 WRITE A HTTP WEB CLIENT PROGRAM TO 7


DOWNLOAD A WEB PAGE USING TCP SOCKETS

3 APPLICATIONS USING TCP SOCKETS LIKE: 10


ECHO CLIENT AND ECHO SERVER
CHAT
FILE TRANSFER

4 SIMULATION OF DNS USING UDP SOCKETS. 18

5 WRITE A CODE SIMULATING ARP /RARP PROTOCOLS. 21


6 STUDY OF NETWORK SIMULATOR (NS) AND 26
SIMULATION OF CONGESTION CONTROL
ALGORITHMS USING NS

7 STUDY OF TCP/UDP PERFORMANCE USING 30


SIMULATION TOOL.
8 SIMULATION OF DISTANCE VECTOR/ LINK STATE 34
ROUTING ALGORITHM.

9 PERFORMANCE EVALUATION OF ROUTING 40


PROTOCOLS USING SIMULATION TOOL.

SIMULATION OF ERROR CORRECTION CODE (LIKE 48


10 CRC).

1
EXNO: 1
LEARN TO USE COMMANDS LIKE TCPDUMP, NETSTAT, IFCONFIG, NSLOOKUP AND
TRACEROUTE. CAPTURE PING AND TRACEROUTE PDUS USING A NETWORK
PROTOCOL ANALYZER AND EXAMINE.
AIM:
To Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute ping.

Commands:
Tcpdump:

Display traffic between 2 hosts:


To display all traffic between two hosts (represented by variables host1 and host2): #
tcpdump host 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 port:
# tcpdump src port ftp
# tcpdump dst port http

[Link]
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

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

3
[Link]
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
[Link] route:
Traceroute 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. Traceroute is a network diagnostic tool used to track the pathway taken by a
packet on an IP network from source to destination. Traceroute also records the time taken for
each hop the packet makes during its route to the destination. Traceroute 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.
Traceroute 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 [Link] in this way, traceroute 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
[Link].
#tracert [Link]

4
[Link]:
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 network with 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, ifconfig, nslookup and
traceroute ping are executed successfully.
5
EX NO: 2 WRITE A HTTP WEB CLIENT PROGRAM TO DOWNLOAD A WEB PAGE USING
TCP SOCKETS

AIM
To write a java program for socket for HTTP for web page upload and download.

ALGORITHM:
Client:
1. Start.
2. Create socket and establish the connection with the server.
3. Read the image to be uploaded from the disk
4. Send the image read to the server
5. Terminate the connection
6. Stop.
Server:
1. Start
2. Create socket, bind IP address and port number with the created socket and make
server a listening server.
3. Accept the connection request from the client
4. Receive the image sent by the client.
5. Display the image.
6. Close the connection.
7. Stop.

PROGRAM
Client
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link]; import
[Link]; import
[Link];
import [Link]; import
[Link];
public class Client
{
public static void main(String args[]) throws Exception
{
Socket soc;
6
BufferedImage img = null;
soc=new
Socket("localhost",4000);
[Link]("Client is running.");
try {
[Link]("Reading image from disk. ");
img = [Link](new File("digital_image_processing.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
[Link](img, "jpg", baos);
[Link]();
byte[] bytes = [Link](); [Link]();
[Link]("Sending image to server.");
OutputStream out = [Link]();
DataOutputStream dos = new DataOutputStream(out);
[Link]([Link]);
[Link](bytes, 0, [Link]);
[Link]("Image sent to server. ");
[Link]();
[Link]();
}
catch (Exception e)
{
[Link]("Exception: " + [Link]());
[Link]();
}
[Link]();
}
}

Server
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
[Link]("Server Waiting for image");
7
socket=[Link](); [Link]("Client connected.");
InputStream in = [Link]();
DataInputStream dis = new DataInputStream(in);
int len = [Link]();
[Link]("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];
[Link](data);
[Link]();
[Link]();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = [Link](ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
[Link](icon);
[Link](l);
[Link]();
[Link](true);
}
}

OUTPUT:
When you run the client code, following output screen would appear on client side.

RESULT:
Thus the socket program for HTTP for web page upload and download was developed
and executed successfully.

8
EX. NO. 3 APPLICATIONS USING TCP SOCKETS LIKE: ECHO CLIENT AND ECHO
SERVER, CHAT AND FILE TRANSFER

AIM
To write a java program for application using TCP Sockets Links

a. Echo client and echo server


ALGORITHM
Client
1. Start
2. Create the TCP socket
3. Establish connection with the server
4. Get he message to be echoed from the user
5. Send the message to the server
6. Receive the message echoed by the server
7. Display the message received from the server
8. Terminate the connection
9. Stop
Server
1. Start
2. Create TCP socket, make it a listening socket
3. Accept the connection request sent by the client for connection establishment
4. Receive the message sent by the client
5. Display the received message
6. Send the received message to the client from which it receives
7. Close the connection when client initiates termination and server becomes a listening
server, waiting for clients.
8. Stop.

PROGRAM:
[Link]
import [Link].*;
import [Link].*;
public class EServer
{
public static void main(String args[])
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps;
Socket c=null;
try
9
{
s=new ServerSocket(9000);
}
catch(IOException e)
{
[Link](e);
}
try
{
c=[Link]();
is=new DataInputStream([Link]());
ps=new PrintStream([Link]());
while(true)
{
line=[Link]();
[Link](line);
}
}
catch(IOException e)
{
[Link](e);
}
}
}

[Link]
import [Link].*;
import [Link].*;
public class EClient
{ public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
InetAddress ia = [Link]();
c=new Socket(ia,9000);
}
catch(IOException e)
{
[Link](e);
10
}
try
{
os=new PrintStream([Link]());
is=new DataInputStream([Link]);
is1=new DataInputStream([Link]());
while(true)
{
[Link]("Client:");
line=[Link]();
[Link](line);
[Link]("Server:" + [Link]());
}
}
catch(IOException e)
{
[Link]("Socket Closed!");
}
}}

OUTPUT
Server
C:\Program Files\Java\jdk1.5.0\bin>javac [Link]
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 [Link]
C:\Program Files\Java\jdk1.5.0\bin>java EClient
Client: Hai Server
Server:Hai Server
Client: Hello
Server:Hello
Client:end
Server:end
Client:ds
Socket Closed!

11
[Link]
ALGORITHM
Client
1. Start
2. Create the UDP datagram socket
3. Get the request message to be sent from the user
4. Send the request message to the server
5. If the request message is “END” go to step 10
6. Wait for the reply message from the server
7. Receive the reply message sent by the server
8. Display the reply message received from the server
9. Repeat the steps from 3 to 8
10. Stop
Server
1. Start
2. Create UDP datagram socket, make it a listening socket
3. Receive the request message sent by the client
4. If the received message is “END” go to step 10
5. Retrieve the client’s IP address from the request message received
6. Display the received message
7. Get the reply message from the user
8. Send the reply message to the client
9. Repeat the steps from 3 to 8.
10. Stop.

PROGRAM
[Link]
import [Link].*;
import [Link].*;
class UDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(clientport);
[Link]("press ctrl+c to quit the program");
BufferedReader dis=new BufferedReader(new InputStreamReader([Link]));
InetAddress ia=[Link]();
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,[Link]);
12
[Link](p);
String psx=new String([Link](),0,[Link]());
[Link]("Client:" + psx);
[Link]("Server:");
String str=[Link]();
if([Link]("end"))
break;
buffer=[Link]();
[Link](new DatagramPacket(buffer,[Link](),ia,serverport));
}
}
}

[Link]
import java .io.*;
import [Link].*;
class UDPclient
{
public static DatagramSocket ds;
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader([Link]));
[Link]("server waiting");
InetAddress ia=[Link]();
while(true)
{
[Link]("Client:");
String str=[Link]();
if([Link]("end"))
break;
buffer=[Link]();
[Link](new DatagramPacket(buffer,[Link](),ia,clientport));
DatagramPacket p=new DatagramPacket(buffer,[Link]);
[Link](p);
String psx=new String([Link](),0,[Link]());
[Link]("Server:" + psx);
}
}
}

13
OUTPUT:
Server
C:\Program Files\Java\jdk1.5.0\bin>javac [Link]
C:\Program Files\Java\jdk1.5.0\bin>java UDPserver
press ctrl+c to quit the program
Client:Hai Server
Server:Hello Client
Client:How are You
Server:I am Fine
Client
C:\Program Files\Java\jdk1.5.0\bin>javac [Link]
C:\Program Files\Java\jdk1.5.0\bin>java UDPclient
server waiting
Client:Hai Server
Server:Hello Clie
Client:How are You
Server:I am Fine
Client:end

C. File Transfer
AIM:
To write a java program for file transfer using TCP Sockets.
Algorithm
Server
1. Import java packages and create class file server.
2. Create a new server socket and bind it to the port.
3. Accept the client connection
4. Get the file name and stored into the BufferedReader.
5. Create a new object class file and realine.
6. If file is exists then FileReader read the content until EOF is reached.
7. Stop the program.
Client
1. Import java packages and create class file server.
2. Create a new server socket and bind it to the port.
3. Now connection is established.
4. The object of a BufferReader class is used for storing data content which has been
retrieved from socket object.
5. The connection is closed.
6. Stop the program.

14
PROGRAM
File Server :
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]
public class FileServer
{
public static void main(String[] args) throws Exception
{
//Initialize Sockets
ServerSocket ssock = new ServerSocket(5000); Socket
socket = [Link]();
//The InetAddress specification
InetAddress IA = [Link]("localhost");
//Specify the file
File file = new File("e:\\[Link]");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis); //Get
socket's output stream
OutputStream os = [Link](); //Read
File Contents into contents array
byte[] contents;
long fileLength = [Link]();
long current = 0;
long start = [Link]();
while(current!=fileLength){
int size = 10000;
if(fileLength - current >= size)
current += size;
else{
size = (int)(fileLength - current);
current = fileLength;
}
contents = new byte[size];
[Link](contents, 0, size);
[Link](contents);
[Link]("Sending file ... "+(current*100)/fileLength+"% complete!");
}
[Link]();
15
//File transfer done. Close the socket connection!
[Link]();
[Link]();
[Link]("File sent succesfully!");
}}

File Client:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FileClient {
public static void main(String[] args) throws Exception{
//Initialize socket
Socket socket = new Socket([Link]("localhost"), 5000); byte[]
contents = new byte[10000];
//Initialize the FileOutputStream to the output file's full path. FileOutputStream fos = new
FileOutputStream("e:\\[Link]");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = [Link]();
//No of bytes read in one read() call
int bytesRead = 0;
while((bytesRead=[Link](contents))!=-1)
[Link](contents, 0, bytesRead);
[Link]();
[Link]();
[Link]("File saved successfully!");
}
}

Output
server
E:\nwlab>java FileServer
Sending file ... 9% complete!
Sending file ... 19% complete!
Sending file ... 28% complete!
Sending file ... 38% complete!
Sending file ... 47% complete!
Sending file ... 57% complete!
Sending file ... 66% complete!
Sending file ... 76% complete!
Sending file ... 86% complete!
16
Sending file ... 95% complete!
Sending file ... 100% complete!
File sent successfully!

E:\nwlab>client
E:\nwlab>java FileClient
File saved successfully!
E:\nwlab>

RESULT:
Thus the java application program using TCP Sockets was developed and executed
successfully.

17
EX. NO. 4 SIMULATION OF DNS USING UDP SOCKETS

AIM
To write a java program for DNS application

ALGORITHM
Server
1. Start
2. Create UDP datagram socket
3. Create a table that maps host name and IP address
4. Receive the host name from the client
5. Retrieve the client’s IP address from the received datagram
6. Get the IP address mapped for the host name from the table.
7. Display the host name and corresponding IP address
8. Send the IP address for the requested host name to the client
9. Stop.
Client
1. Start
2. Create UDP datagram socket.
3. Get the host name from the client
4. Send the host name to the server
5. Wait for the reply from the server
6. Receive the reply datagram and read the IP address for the requested host name
7. Display the IP address.
8. Stop.

PROGRAM
DNS Server
java import [Link].*;
import [Link].*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = [Link]();
for (int i=0; i < [Link]; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}

18
public static void main(String arg[])throws IOException
{
String[] hosts = {"[Link]", "[Link]","[Link]", "[Link]"};
String[] ip = {"[Link]", "[Link]","[Link]", "[Link]"};
[Link]("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata, [Link]);
[Link](recvpack);
String sen = new String([Link]());
InetAddress ipaddress = [Link]();
int port = [Link]();
String capsent;
[Link]("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = [Link]();
DatagramPacket pack = new DatagramPacket (senddata, [Link],ipaddress,port);
[Link](pack);
[Link]();
}}}

UDP DNS Client


java import [Link].*;
import [Link].*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if ([Link] == 0)
ipaddress = [Link]();
else
ipaddress = [Link](args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
19
int portaddr = 1362;
[Link]("Enter the hostname : ");
String sentence = [Link]();
Senddata = [Link]();
DatagramPacket pack = new DatagramPacket(senddata,[Link],
ipaddress,portaddr);
[Link](pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,[Link]);
[Link](recvpack);
String modified = new String([Link]());
[Link]("IP Address: " + modified);
[Link]();
}}

OUTPUT
Server
javac [Link]
java udpdnsserver
Press Ctrl + C to Quit Request for host [Link]
Request for host [Link]
Request for host [Link]

Client
>javac [Link]
>java udpdnsclient
Enter the hostname : [Link]
IP Address: [Link]
>java udpdnsclient
Enter the hostname : [Link]
IP Address: [Link]
>java udpdnsclient
Enter the hostname : [Link]
IP Address: Host Not Found

RESULT:
Thus the java application program using UDP Sockets to implement DNS was
developed and executed successfully

20
EXNO: 5 WRITE A CODE SIMULATING ARP /RARP PROTOCOLS

AIM
To write a java program for simulating ARP and RARP protocols using TCP.

ALGORITHM:
Client
1. Start the program
2. Create socket and establish connection with the server.
3. Get the IP address to be converted into MAC address from the user.
4. Send this IP address to server.
5. Receive the MAC address for the IP address from the server.
6. Display the received MAC address
7. Terminate the connection
Server
1. Start the program
2. Create the socket, bind the socket created with IP address and port number and make
it a listening socket.
3. Accept the connection request when it is requested by the client.
4. Server maintains the table in which IP and corresponding MAC addresses are
stored.
5. Receive the IP address sent by the client.
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 [Link].*;
import [Link].*;
import [Link].*;
class Clientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
Socket clsct=new Socket("[Link]",139)
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
21
[Link]("Enter the Logical address(IP):");
String str1=[Link]();
[Link](str1+'\n';
String str=[Link]();
[Link]("The Physical Address is: "+str);
[Link]();
}
catch (Exception e)
{
[Link](e);
}}
}

Server:
import [Link].*;
import [Link].*;
import [Link].*;
class Serverarp
{
public static void main(String args[])
{
try{
ServerSocket obj=new
ServerSocket(139); Socket
obj1=[Link]();
while(true)
{
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
String str=[Link]();
String ip[]={"[Link]","[Link]"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<[Link];i++)
{
if([Link](ip[i]))
{
[Link](mac[i]+'\n');
break;
}
}
[Link]();
}
}
22
catch(Exception e)
{
[Link](e);
}}
}

Output:
E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logical address(IP):
[Link]
The Physical Address is: 6A:08:AA:C2

(b) Program for Reverse Address Resolution Protocol (RARP) using UDP

ALGORITHM:
Client
1. Start the program
2. Create datagram socket
3. Get the MAC address to be converted into IP address from the user.
4. Send this MAC address to server using UDP datagram.
5. Receive the datagram from the server and display the corresponding IP address.
6. Stop
Server
1. Start the program.
2. Server maintains the table in which IP and corresponding MAC addresses are
stored.
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.
6. Display the corresponding IP address.
7. Stop

PROGRAM:
Client:
import [Link].*;
import [Link].*;
import [Link].*;
class Clientrarp12
{
public static void main(String args[])
{
try
23
{
DatagramSocket client=new DatagramSocket();
InetAddress addr=[Link]("[Link]");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the Physical address (MAC):")
String str=[Link](); sendbyte=[Link]();
DatagramPacket sender=newDatagramPacket(sendbyte,[Link],addr,1309);
[Link](sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,[Link]);
[Link](receiver);
String s=new String([Link]());
[Link]("The Logical Address is(IP): "+[Link]());
[Link]();
}
catch(Exception e)
{
[Link](e);
}}}

Server:
import [Link].*;
import [Link].*;
import [Link].*;
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,[Link]);
[Link](receiver);
String str=new String([Link]());
String s=[Link]();
InetAddress addr=[Link]();
int port=[Link]();
String ip[]={"[Link]","[Link]"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
24
for(int i=0;i<[Link];i++)
{
if([Link](mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender = new
DatagramPacket(sendbyte,[Link],addr,port);
[Link](sender);
break;
}}
break;
}}}catch(Exception e)
{
[Link](e);
}}}

Output:
I:\ex>java Serverrarp12
I:\ex>java Clientrarp12
Enter the Physical address (MAC):
6A:08:AA:C2
The Logical Address is(IP): [Link]

RESULT :
Thus the program for implementing to display simulating ARP and RARP protocols was
executed successfully and output is verified.

25
EX. NO. 6 STUDY OF NETWORK SIMULATOR (NS) AND SIMULATION OF
CONGESTION CONTROL ALGORITHMS USING NS

AIM
To Study Network simulator (NS).and Simulation of Congestion Control Algorithms
using NS

NET WORK SIMULATOR (NS2)


Ns Overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac

Ns functionalities
Routing, Transportation, Traffic sources,Queuing disciplines, QoS

Congestion Control Algorithms


Slow start
Additive increase/multiplicative decrease
Fast retransmit and Fast recovery

Case Study: A simple Wireless network.


Ad hoc routing, mobile IP, sensor-MAC
Tracing, visualization and various utilitie
NS(Network Simulators)
Most of the commercial simulators are GUI driven, while some network simulators are
CLI driven. The network model / configuration describes the state of the network
(nodes,routers, switches, links) and the events (data transmissions, packet error etc.). An
important output of simulations are the trace files. Trace files log every packet, every event that
occurred in the simulation and are used for analysis. Network simulators can also provide other
tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending
"events" is stored, and those events are processed in order, with some events triggering future
events—such as the event of the arrival of a packet at one node triggering the event of the
arrival of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high, then
estimation of the average occupancy is challenging because of high variance. To estimate the
likelihood of a buffer overflow in a network, the time required for an accurate answer can be
extremely large. Specialized techniques such as "control variates" and "importance sampling"
have been developed to speed simulation.

26
Examples of network simulators
There are many both free/open-source and proprietary network simulators. Examples of
notable network simulation software are, ordered after how often they are mentioned in
research papers:
1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)

Uses of network simulators


Network simulators serve a variety of needs. Compared to the cost and time involved in
setting up an entire test bed containing multiple networked computers, routers and data links,
network simulators are relatively fast and inexpensive. They allow engineers, researchers to test
scenarios that might be particularly difficult or expensive to emulate using real hardware – for
instance, simulating a scenario with several nodes or experimenting with a new protocol in the
network. Network simulators are particularly useful in allowing researchers to test new
networking protocols or changes to existing protocols in a controlled and reproducible
environment. A typical network simulator encompasses a wide range of networking
technologies and can help the users to build complex networks from basic building blocks such
as a variety of nodes and links. With the help of simulators, one can design hierarchical
networks using various types of nodes like computers, hubs, bridges, routers, switches, links,
mobile units etc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and
Local Area Network (LAN) technologies like Ethernet, token rings etc., can all be simulated
with a typical simulator and the user can test, analyze various standard results apart from
devising some novel protocol or strategy for routing etc. Network simulators are also widely
used to simulate battlefield networks in Network-centric warfare.
There are a wide variety of network simulators, ranging from the very simple to the very
complex. Minimally, a network simulator must enable a user to represent a network topology,
specifying the nodes on the network, the links between those nodes and the traffic between the
nodes. More complicated systems may allow the user to specify everything about the protocols
used to handle traffic in a network. Graphical applications allow users to easily visualize the
workings of their simulated environment. Text-based applications may provide a less intuitive
interface, but may permit more advanced forms of customization.

Packet loss
Packet loss occurs when one or more packets of data travelling across a computer
network fail to reach their destination. Packet loss is distinguished as one of the three main
error types encountered in digital communications; the other two being bit error and spurious
packets caused due to noise.
Packets can be lost in a network because they may be dropped when a queue in the
network node overflows. it is for transportlayer protocols to maintain high bandwidths, the

27
sensitivity to loss of individual packets, as well as to frequency and patterns of loss among
longer packet sequences is strongly dependent on the application itself.

Throughput
Throughput is the main performance measure characteristic, and most widely used. In
communication networks, such as Ethernet or packet radio, throughput or network throughput
is the average rate of successful message delivery over a communication channel. Throughput
is usually measured inbitsper second (bit/s orbps), and sometimes in data packets per second or
data packets per time slot. This measures how soon the receiver is able to get a certain amount
of data send by the sender. It is determined as the ratio of the total data received to the end to
end delay. Throughput is an important factor which directly impacts the network performance.

Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or
network ingress to destination premise or network degrees. The larger the value of delay, the
more difficult it is for transport layer protocols to maintain highbandwidths. We will calculate
end to end delay

Queue Length
A queuing system in networks can be described as packets arriving for service, waiting
for service if it is not immediate, and if having waited for service, leaving the system after
being served. Thus queue length is very important characteristic to determine that how well the
active queue management of the congestion control algorithm has been working.

Congestion control Algorithms


Slow-start is used in conjunction with other algorithms to avoid sending more data than
the network is capable of transmitting, that is, to avoid causing network congestion. The
additive increase/multiplicative decrease (AIMD) algorithm is a feedback control algorithm.
AIMD combines linear growth of the congestion window with an exponential reduction when a
congestion takes place. Multiple flows using AIMD congestion control will eventually
converge to use equal amounts of a contended link. Fast Retransmit is an enhancement to TCP
that reduces the time a sender waits before retransmitting a lost segment.

Program:
include <wifi_lte/wifi_lte_rtable.h>
struct r_hist_entry *elm, *elm2;
int num_later = 1;
elm = STAILQ_FIRST(&r_hist_);
while (elm != NULL && num_later <= num_dup_acks_){
num_later;
elm = STAILQ_NEXT(elm, linfo_);
}
if (elm != NULL){
28
elm = findDataPacketInRecvHistory(STAILQ_NEXT(elm,linfo_));
if (elm != NULL){
elm2 = STAILQ_NEXT(elm, linfo_);
while(elm2 != NULL){
if (elm2->seq_num_ < seq_num && elm2->t_recv_ <
time){
STAILQ_REMOVE(&r_hist_,elm2,r_hist_entry,linfo_);
delete elm2;
} else
elm = elm2;
elm2 = STAILQ_NEXT(elm, linfo_);
}}}}
void DCCPTFRCAgent::removeAcksRecvHistory(){
struct r_hist_entry *elm1 = STAILQ_FIRST(&r_hist_);
struct r_hist_entry *elm2;
int num_later = 1;
while (elm1 != NULL && num_later <= num_dup_acks_){
num_later;
elm1 = STAILQ_NEXT(elm1, linfo_);
}
if(elm1 == NULL)
return;
elm2 = STAILQ_NEXT(elm1, linfo_);
while(elm2 != NULL){
if (elm2->type_ == DCCP_ACK){
STAILQ_REMOVE(&r_hist_,elm2,r_hist_entry,linfo_);
delete elm2;
} else {
elm1 = elm2;
}
elm2 = STAILQ_NEXT(elm1, linfo_);
}}
inline r_hist_entry
*DCCPTFRCAgent::findDataPacketInRecvHistory(r_hist_entry *start){
while(start != NULL && start->type_ == DCCP_ACK)
start = STAILQ_NEXT(start,linfo_);
return start;
}

Result:
Thus we have Studied Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS.

29
[Link] STUDY OF TCP/UDP PERFORMANCE USING SIMULATION TOOL.

AIM
To simulate the performance of TCP/UDP using NS2.

TCP Performance
Algorithm
1. Create a Simulator object.
2. Set routing as dynamic.
3. Open the trace and nam trace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the tcp agent.
8. Connect tcp and tcp sink.
9. Run the simulation.

PROGRAM:
set ns [new Simulator]
$ns color 0 Blue
$ns color 1 Red
$ns color 2 Yellow
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set f [open [Link] w]
$ns trace-all $f
set nf [open [Link] w]
$ns namtrace-all $nf
$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-up
$ns duplex-link-op $n1 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
set tcp [new Agent/TCP]
$tcp set class_ 1
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $tcp
$ns attach-agent $n3 $sink
30
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 1.2 "$ftp start"
$ns at 1.35 "$ns detach-agent $n1 $tcp ; $ns detach-agent $n3 $sink"
$ns at 3.0 "finish"
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
puts "Running nam.."
exec xgraph [Link] -geometry 600x800 &
exec nam [Link] &
exit 0
}
$ns run

Output

31
UDP Performance
ALGORITHM :
1. Create a Simulator object.
2. Set routing as dynamic.
3. Open the trace and nam trace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the UDP agent.
8. Connect udp and null agents.
9. Run the simulation.

PROGRAM:
set ns [new Simulator]
$ns color 0 Blue
$ns color 1 Red
$ns color 2 Yellow
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set f [open [Link] w]
$ns trace-all $f
set nf [open [Link] w]
$ns namtrace-all $nf
$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-up
$ns duplex-link-op $n1 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
set udp1 [new Agent/UDP]
$ns attach-agent $n3 $udp1
$udp1 set class_ 0
set cbr1 [new Application/Traffic/CBR]
32
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
set null1 [new Agent/Null]
$ns attach-agent $n1 $null1
$ns connect $udp0 $null0
$ns connect $udp1 $null1
$ns at 1.0 "$cbr0 start"
$ns at 1.1 "$cbr1 start"
puts [$cbr0 set packetSize_]
puts [$cbr0 set interval_]
$ns at 3.0 "finish"
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
puts "Running nam.."
exec nam [Link] &
exit 0
}
$ns run

Output:

RESULT:
Thus the study of TCP/UDP performance is done successfully.

33
[Link] SIMULATION OF DISTANCE VECTOR/ LINK STATE
ROUTING ALGORITHM
AIM:
To simulate the Distance vector and link state routing protocols using NS2.

ALGORITHM:
1. Create a Simulator object.
2. Set routing as dynamic.
3. Open the trace and nam trace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the udp agent.
8. Connect udp and null..
9. At 1 sec the link between node 1 and 2 is broken.
10. At 2 sec the link is up again.
11. Run the simulation.

LINK STATE ROUTING PROTOCOL


PROGRAM
set ns [new Simulator]
$ns rtproto LS
set nf [open [Link] w]
$ns namtrace-all $nf
set f0 [open [Link] w]
$ns trace-all $f0
proc finish {} {
global ns f0 nf
$ns flush-trace
close $f0
close $nf
exec nam [Link] &
exit 0
}
for {set i 0} {$i <7} {incr i} {
set n($i) [$ns node]
}
for {set i 0} {$i <7} {incr i} {
$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}
set udp0 [new Agent/UDP]

34
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run

Output:

35
DISTANCE VECTOR ROUTING ALGORITHM
ALGORITHM:
1. Create a simulator object
2. Set routing protocol to Distance Vector routing
3. Trace packets on all links onto NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create eight nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology as a octagon
8. Add UDP agent for node n1
9. Create CBR traffic on top of UDP and set traffic parameters.
10. Add a sink agent to node n4
11. Connect source and the sink
12. Schedule events as follows:
a. Start traffic flow at 0.5
b. Down the link n3-n4 at 1.0
c. Up the link n3-n4 at 2.0
d. Stop traffic at 3.0
e. Call finish procedure at 5.0
13. Start the scheduler
14. Observe the traffic route when link is up and down
15. View the simulated events and trace file analyze it
16. Stop

PROGRAM
#Distance vector routing protocol – [Link]
#Create a simulator object
set ns [new Simulator]
36
#Use distance vector routing
$ns rtproto DV
#Open the nam trace file
set nf [open [Link] w]
$ns namtrace-all $nf
# Open tracefile
set nt [open [Link] w]
$ns trace-all $nt
#Define 'finish' procedure
proc finish {}
{
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam -a [Link] &
exit 0
}
# Create 8 nodes
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
# Specify link characterestics
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail
# specify layout as a octagon
$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
37
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left
#Create a UDP agent and attach it to node n1
set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
#Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
#Create a Null agent (a traffic sink) and attach it to node n4
set null0 [new Agent/Null]
$ns attach-agent $n4 $null0
#Connect the traffic source with the traffic sink
$ns connect $udp0 $null0
#Schedule events for the CBR agent and the network dynamics
$ns at 0.0 "$n1 label Source"
$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

38
OUTPUT

$ ns [Link]

39
RESULT:
Thus the simulation for Distance vector and link state routing protocols was done using
NS2.

40
[Link] PERFORMANCE EVALUATION OF ROUTING PROTOCOLS
USING SIMULATION TOOL.

AIM:
To write a ns2 program for implementing unicast routing protocol.

ALGORITHM:
1. Start the program.
2. Declare the global variables ns for creating a new simulator.
3. Set the color for packets.
4. Open the network animator file in the name of file2 in the write mode.
5. Open the trace file in the name of file 1 in the write mode.
6. Set the unicast routing protocol to transfer the packets in network.
7. Create the required no of nodes.
8. Create the duplex-link between the nodes including the delay time, bandwidth and
dropping queue mechanism.
9. Give the position for the links between the nodes.
10. Set a tcp reno connection for source node.
11. Set the destination node using tcp sink.
12. Setup a ftp connection over the tcp connection.
13. Down the connection between any nodes at a particular time.
14. Reconnect the downed connection at a particular time.
15. Define the finish procedure.
16. In the definition of the finish procedure declare the global variables ns, file1, and
file2.
17. Close the trace file and name file and execute the network animation file.
18. At the particular time call the finish procedure.
19. Stop the program.

PROGRAM:
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace file
set file1 [open [Link] w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open [Link] w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {}

41
{
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam [Link] &
exit 3
}
# Next line should be commented out to have the static routing
$ns rtproto DV
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n4 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail
#Give node position (for NAM)
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n1 $n4 orient up-left
$ns duplex-link-op $n3 $n5 orient left-up
$ns duplex-link-op $n4 $n5 orient right-up
#Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
$ns rtmodel-at 1.0 down $n1 $n4
42
$ns rtmodel-at 4.5 up $n1 $n4
$ns at 0.1 "$ftp start"
$ns at 6.0 "finish"
$ns run

Output:

(b) MULTICASTING ROUTING PROTOCOL

AIM:
To write a ns2 program for implementing multicasting routing protocol.

ALGORITHM:
1. Start the program.
2. Declare the global variables ns for creating a new simulator.
3. Set the color for packets.
4. Open the network animator file in the name of file2 in the write mode.
5. Open the trace file in the name of file 1 in the write mode.
6. Set the multicast routing protocol to transfer the packets in network.
7. Create the multicast capable no of nodes.
43
8. Create the duplex-link between the nodes including the delay time,bandwidth and
dropping queue mechanism.
9. Give the position for the links between the nodes.
10. Set a udp connection for source node.
11. Set the destination node ,port and random false for the source and destination files.
12. Setup a traffic generator CBR for the source and destination files.
13. Down the connection between any nodes at a particular time.
14. Create the receive agent for joining and leaving if the nodes in the group.
15. Define the finish procedure.
16. In the definition of the finish procedure declare the global variables.
17. Close the trace file and namefile and execute the network animation file.
18. At the particular time call the finish procedure.
19. Stop the program.

PROGRAM:
# Create scheduler
#Create an event scheduler wit multicast turned on
set ns [new Simulator -multicast on]
#$ns multicast
#Turn on Tracing
set tf [open [Link] w]
$ns trace-all $tf
# Turn on nam Tracing
set fd [open [Link] w]
$ns namtrace-all $fd
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
# Create links
$ns duplex-link $n0 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link $n3 $n4 1.5Mb 10ms DropTail
$ns duplex-link $n3 $n7 1.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 1.5Mb 10ms DropTail
$ns duplex-link $n4 $n6 1.5Mb 10ms DropTail
# Routing protocol: say distance vector
44
#Protocols: CtrMcast, DM, ST, BST
set mproto DM
set mrthandle [$ns mrtproto $mproto {}]
# Allocate group addresses
set group1 [Node allocaddr]
set group2 [Node allocaddr]
# UDP Transport agent for the traffic source
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
$udp0 set dst_addr_ $group1
$udp0 set dst_port_ 0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp0
# Transport agent for the traffic source
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
$udp1 set dst_addr_ $group2
$udp1 set dst_port_ 0
set cbr2 [new Application/Traffic/CBR]
$cbr2 attach-agent $udp1
# Create receiver
set rcvr1 [new Agent/Null]
$ns attach-agent $n5 $rcvr1
$ns at 1.0 "$n5 join-group $rcvr1 $group1"
set rcvr2 [new Agent/Null]
$ns attach-agent $n6 $rcvr2
$ns at 1.5 "$n6 join-group $rcvr2 $group1"
set rcvr3 [new Agent/Null]
$ns attach-agent $n7 $rcvr3
$ns at 2.0 "$n7 join-group $rcvr3 $group1"
set rcvr4 [new Agent/Null]
$ns attach-agent $n5 $rcvr1
$ns at 2.5 "$n5 join-group $rcvr4 $group2"
set rcvr5 [new Agent/Null]
$ns attach-agent $n6 $rcvr2
$ns at 3.0 "$n6 join-group $rcvr5 $group2"
set rcvr6 [new Agent/Null]
$ns attach-agent $n7 $rcvr3
$ns at 3.5 "$n7 join-group $rcvr6 $group2"
$ns at 4.0 "$n5 leave-group $rcvr1 $group1"
$ns at 4.5 "$n6 leave-group $rcvr2 $group1"
$ns at 5.0 "$n7 leave-group $rcvr3 $group1"
$ns at 5.5 "$n5 leave-group $rcvr4 $group2"
45
$ns at 6.0 "$n6 leave-group $rcvr5 $group2"
$ns at 6.5 "$n7 leave-group $rcvr6 $group2"
# Schedule events
$ns at 0.5 "$cbr1 start"
$ns at 9.5 "$cbr1 stop"
$ns at 0.5 "$cbr2 start"
$ns at 9.5 "$cbr2 stop"
#post-processing
$ns at 10.0 "finish"
proc finish {}
{
global ns tf
$ns flush-trace
close $tf
exec nam [Link] &
exit 0
}
# For nam
#Colors for packets from two mcast groups
$ns color 10 red
$ns color 11 green
$ns color 30 purple
$ns color 31 green
# Manual layout: order of the link is significant!
#$ns duplex-link-op $n0 $n1 orient right
#$ns duplex-link-op $n0 $n2 orient right-up
#$ns duplex-link-op $n0 $n3 orient right-down
# Show queue on simplex link n0->n1
#$ns duplex-link-op $n2 $n3 queuePos 0.5
# Group 0 source
$udp0 set fid_ 10
$n0 color red
$n0 label "Source 1"
# Group 1 source
$udp1 set fid_ 11
$n1 color green
$n1 label "Source 2"
$n5 label "Receiver 1"
$n5 color blue
$n6 label "Receiver 2"
$n6 color blue
$n7 label "Receiver 3"
$n7 color blue
46
#$n2 add-mark m0 red
#$n2 delete-mark m0"
# Animation rate
$ns set-animation-rate 3.0ms
$ns run
Output:

47
48
RESULT:
Thus the case study about the different routing algorithms to select the network path
with its optimum and economical during data transfer is done.

49
[Link] SIMULATION OF ERRORDETECTION CODE (LIKE CRC)

AIM:
To implement error checking code using java.

ALGORITHM:
1. Start the Program
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.
3. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and
determine the remainder R(x). This division is to be done using Modulo 2 Division.
4. Define T(x) = B(x) –R(x)
5. (T(x)/G(x) => remainder 0)
6. Transmit T, the bit string corresponding to T(x).
7. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial.
The receiver divides T1(x) by G(x). If there is a 0 remainder, the receiver concludes
T = T’ and no error occurred otherwise, the receiver concludes an error occurred and
requires a retransmission
8. Stop the Program

PROGRAM:
import [Link].*;
class crc_gen
{
public static void main(String args[]) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
[Link]("Enter number of data bits : "); data_bits=[Link]([Link]());
data=new int[data_bits];
[Link]("Enter data bits : ");
for(int i=0; i<data_bits; i++)
data[i]=[Link]([Link]());
[Link]("Enter number of bits in divisor : ");
divisor_bits=[Link]([Link]()); divisor=new int[divisor_bits];
[Link]("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)

50
divisor[i]=[Link]([Link]());
[Link]("Data bits are : ");
for(int i=0; i< data_bits; i++)
[Link](data[i]);
[Link]();
[Link]("divisor bits are : ");
for(int i=0; i< divisor_bits; i++)
[Link](divisor[i]);
[Link]();
*/
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<[Link];i++)
div[i]=data[i];
[Link]("Dividend (after appending 0's) are : "); for(int i=0; i< [Link]; i++)
[Link](div[i]);
[Link]();
for(int j=0; j<[Link]; j++){
rem[j] = div[j];
}
rem=divide(div, divisor, rem);
for(int i=0;i<[Link];i++)
{
//append dividend and remainder
crc[i]=(div[i]^rem[i]);
}
[Link]();
[Link]("CRC code : ");
for(int i=0;i<[Link];i++)
[Link](crc[i]);
/*-------------------ERROR DETECTION---------------------*/
[Link]();
[Link]("Enter CRC code of "+tot_length+" bits : "); for(int i=0; i<[Link]; i++)
crc[i]=[Link]([Link]());
[Link]("crc bits are : ");
for(int i=0; i< [Link]; i++)
[Link](crc[i]);
[Link]();
for(int j=0; j<[Link]; j++){
rem[j] = crc[j];
51
}
rem=divide(crc, divisor, rem);
for(int i=0; i< [Link]; i++)
{
if(rem[i]!=0)
{
[Link]("Error");
break;
}
if(i==[Link]-1)
[Link]("No Error");
}
[Link]("THANK YOU.... :)");
}
static int[] divide(int div[],int divisor[], int rem[])
{
int cur=0;
while(true)
{
for(int i=0;i<[Link];i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
while(rem[cur]==0 && cur!=[Link]-1)
cur++;
if(([Link]-cur)<[Link])
break;
}
return rem;
}
}

OUTPUT :
Enter number of data bits :
7
Enter data bits :
1
0
1
1
0
0
1
Enter number of bits in divisor :
3
52
Enter Divisor bits :
1
0
1
Dividend (after appending 0's) are : 101100100
CRC code :
101100111
Enter CRC code of 9 bits :
1
0
1
1
0
0
1
0
1
crc bits are : 101100101
Error
THANK YOU.... :)
BUILD SUCCESSFUL (total time: 1 minute 34 seconds)

RESULT:
Thus the above program for error checking code using was executed successfully.

53

You might also like