CN Record New

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

PRINCE DR K.

VASUDEVAN COLLEGE OF

ENGINEERING AND TECHNOLOGY,

PONMAR CHENNAI-600 127.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATASCIENCE

CS3591-COMPUTER NETWORKS
LABORATORY

2023-2024

NAME :
REGISTER NO. :
SEMESTER :
BRANCH :
Table of Content

Exp.
No. Title of Experiments Date Page No. Signature
1 Learn to use commands like tcpdump, netstat,
ifconfig, nslookup and traceroute. Capture ping
and trace route PDUs using a network protocol
analyzer and examine.
2 Write a HTTP web client program to download a
web page using TCP sockets.
3a Applications using TCP sockets like: Echo
client and echo server.
3b Applications using TCP sockets like: Chat
4 Simulation of DNS using UDP sockets.
5 Use a tool like Wireshark to capture packets
and examine the packets.
6 Write a code simulating ARP /RARP protocols.
7 Study of Network simulator (NS) and
Simulation of Congestion Control
Algorithms using NS.
8 Study of TCP/UDP performance
using Simulation tool.
9 Simulation of Distance Vector/ Link
State Routing algorithm.
10 Simulation of an error correction code
(like CRC)
REG NO : 411622243002

EXP.NO:01 Learn to use commands like tcpdump, netstat, ip config, nslookup and
traceroute. Capture ping and traceroute PDUs using a network
protocol analyzer and examine

AIM:

To Learn to use commands like tcpdump, netstat, ipconfig, nslookup and tracerouteping.

Commands:

1. Tcpdump:
Display traffic between 2 hosts:
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 fromonly a source (src) or destination (dst)
host: # tcpdump src host
# tcpdump dst host
Display traffic fora 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 ordestination port
To filter based on a sourceor destination port:
# tcpdump src port ftp
# tcpdump dst port
http

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

1
REG NO : 411622243002

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
Fromthe 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

2
REG NO : 411622243002

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 multipletimes (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 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
TTLvalue 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

3
REG NO : 411622243002

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, ifconfig, nslookup and traceroute ping
are executed successfully.

4
REG NO : 411622243002

EXP.NO:02 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 fromthe 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 fromthe client
4. Receive the image sent bythe client.
5. Displaythe image.
6. Close the connection.
7. Stop.

PROGRAM
Client
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
importjava.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Client

5
REG NO : 411622243002

{
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 fromdisk. ");
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();
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();
}
}

6
REG NO : 411622243002

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");
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 = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}

7
REG NO : 411622243002

OUTPUT:
When you runthe 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
REG NO : 411622243002

EXP.NO:03A Applications using TCP sockets like: A.Echo client and echo server B.Chat

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

a.Echo client and echo

server ALGORITHM:

Client
1. Start
2. Createthe TCP socket
3. Establish connection with the server
4. Get the message to be echoed fromthe user
5. Send the message to the server
6. Receive the message echoed by the server
7. Displaythe message received fromthe 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 bythe client for connection establishment
4. Receive the message sent bythe client
5. Displaythe received message
6. Send the received message to the client fromwhich it receives
7. Close the connection when client initiates termination and server becomes a listening
server, waiting for clients.
8. Stop.

9
REG NO : 411622243002

PROGRAM:
EchoServer.java
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)
{
System.out.println(e);
}
tr
y
{ 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);
}
}}
10
REG NO : 411622243002

EClient.java
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);
}
catch(IOException e)
{
System.out.println(e);
}
tr
y
{ 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!");
}
}
}
11
REG NO : 411622243002

OUTPUT
Server
C:\ProgramFiles\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:\ProgramFiles\Java\jdk1.5.0\bin>javac EClient.java
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!

12
REG NO : 411622243002

B.Chat

AIM:
To write a java program for application using TCP in Chat.
ALGORITHM:

1. It uses TCP socket communication. We have a server as well as a client.


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();
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 : ");
13
REG NO : 411622243002

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
{
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();
}}

14
REG NO : 411622243002

OUTPUT:
Server

E:\nwlab>javac charserver.java
E:\nwlab>java chatserver
Client : hi
Server : hi

Client
E:\nwlab>javac chatclient.java
E:\nwlab>java chatclient
Client : hi
Server : hi

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

15
REG NO : 411622243002

EXP.NO:04 Simulation of DNS using UDP


sockets.

AIM:

To write a java programfor DNS application

ALGORITHM:
Server
1. Start
2. Create UDP datagramsocket
3. Create atable that maps host name and IP address
4. Receive the host name fromthe client
5. Retrieve the client’s IP address fromthe received datagram
6. Get the IP address mapped for the host name fromthe table.
7. Displaythe 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 datagramsocket.
3. Get the host name fromthe client
4. Send the host name to the server
5. Wait for the reply fromthe server
6. Receive the replydatagramand read the IP address for the requested host name
7. Displaythe IP address.
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++){

16
REG NO : 411622243002

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];
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();
}
}
}

17
REG NO : 411622243002

UPD DNS CLIENT


import java.io.*;
import java.net.*;
public class udpdnsclient
{
publicstatic 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 = 1362;
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);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new
String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();

}
}

18
REG NO : 411622243002

OUTPUT:
Server
javac
udpdnsserver.ja
vajava
udpdnsserver
Press Ctrl+ C to Quit Request for host
yahoo.comRequest for host
cricinfo.com Request for host
youtube.com

Client
Javac
udpdnsclient.java Java
udpdnsclient Enter the
hostname :
yahoo.comIP Address:
68.180.206.184
java udpdnsclient
Enter the hostname :
cricinfo.comIP Address:
80.168.92.140
java udpdnsclient
Enter the hostname :
youtube.comIP Address:
Host Not Found

RESULT:
Thus the java application program using UDP Sockets to implement DNS was developed
19
REG NO : 411622243002

and executed successfully.

20
REG NO : 411622243002

EXP.NO:05 Use a tool like Wireshark to capture packets and examine the packets

Wireshark:

Wireshark is an open-source network protocol analysis software program, widely considered the
industry standard. A global organization of network specialists and software developers supports
Wireshark and continues to make updates for new network technologies and encryption methods.

When should Wireshark be used?

Wireshark can be used to understand how communication takes place across a network and to
analyse what went wrong when an issue in communication arises. It helps

 Network administrators troubleshoot problems across a network


 Security engineers examine security issues across a network
 QA engineers verify applications
 Developers debug protocol implementations
 Network users learn about a specific protocol

Installing Wireshark

Go to https://www.wireshark.org/download.html to visit the Wireshark download page.


Ensure To use the full URL.
The output will look similar to the following:

21
REG NO : 411622243002

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.

22
REG NO : 411622243002

Accept the default settings by pressing Next.


The following wizard will appear (see
below). Press Finish.

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:

23
REG NO : 411622243002

Double-click it and choose your network interface.


When your Wireshark console appears, it should look similar to that shown
below. If you need to change the interface, go to Capture and select Options.

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

24
REG NO : 411622243002

How to Capture Data Packets

One of the core functions of Wireshark as a network analysis tool is to capture packets
of data. Before you start to capture packets, there are three things you need to do:

Make sure that you have the administrative privileges to start a live capture on
your device

Choose the correct network interface to capture packet data from

Capture packet data from the correct location in your network

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:

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:

25
REG NO : 411622243002

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:

Promiscuous Mode

Promiscuous mode is an interface mode where Wireshark details every packet it


sees. When this mode is deactivated, you lose transparency over your network and only develop a
limited snapshot of your network (this makes it more difficult to conduct any analysis).

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:

26
REG NO : 411622243002

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:

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

27
REG NO : 411622243002

Taking the time to check through your network infrastructure will ensure Wireshark
receives all the necessary packets of data.

How to Examine Captured Packets

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.

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.

Result:
Thus Wireshark tool is used to Capture packets and examine the packets.

28
REG NO : 411622243002

EXP.NO:06 Write a code simulating ARP /RARP protocols

(A) Program for Address Resolution Protocol (ARP) using TCP

AIM:
To write a java program for simulating ARP and 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 fromthe user.
4. Send this IP address to server.
5. Receive the MAC address for the IP address fromthe server.
6. Displaythe 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 alistening socket.
3. Accept the connection request when it is requested bythe client.
4. Server maintains the table in which IP and corresponding
MAC addresses arestored.
5. Receive the IP address sent bythe 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 serverwaiting for the connection request fromother
clients
8. Stop

29
REG NO : 411622243002

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);
}}
}

Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try{

30
REG NO : 411622243002

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);
}}
}

Output:
E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logicaladdress(IP):
165.165.80.80
The Physical Address
is: 6A:08:AA:C2

31
REG NO : 411622243002

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

UDP AIM:
To write a java program for simulating RARP and protocols using UDP

ALGORITHM:
Client
1. Start the program
2. Create datagramsocket
3. Get the MAC address to be converted into IP address fromthe user.
4. Send this MAC address to server using UDP datagram.
5. Receive the datagram fromthe 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 datagramsent bythe client and read the MAC address sent.
5. Retrieve the IP address for the received MAC address fromthe table.
6. Displaythe corresponding IP address.
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):")

33
REG NO : 411622243002

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);
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]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender =
new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
} server.send(sender);
} break;
break;

}}}catch(Exception e)
34
REG NO : 411622243002

RE

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

35
REG NO : 411622243002

EXP.NO:7a Study of Network simulator


(NS)

AIM:
To studyabout NS2 simulator in detail.

THEORY:
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 behaviors. 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 Defense 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:

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 byassembling 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 OTcldomain, a handle acts as a frontend which interacts with users and other OTcl objects. It

36
REG NO : 411622243002

defines 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. 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 (atthe 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
Tcl is a generalpurpose scripting language. [Interpreter]
• Tclruns on most ofthe platforms such as Unix, Windows, andMac.
• The strength of Tcl is its simplicity.
• It is not necessaryto declare a data type for variable prior to the usage.

Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!} Hello, World!
Variables
Command Substitution seta 5
set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Wired TCL Script Components
Create the event scheduler
Open new files & turnonthe
tracing Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
37
REG NO : 411622243002

Set the time of traffic generation (e.g., CBR,


FTP) Terminate the simulation

NS Simulator Preliminaries.
1. Initialization and termination aspects of the simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The namvisualization tool.
5. Tracing and randomvariables.

Initialization and Termination of TCL Script in NS-2


An ns simulation starts with the command
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 ―opencommand:

#Open the Trace file

set tracefile1 [open out.tr w]


$ns trace-all $tracefile1

#Open the NAM trace file


set namfile [open out.nam
w]
$ns namtrace-all $namfile
Define a “finish‟ procedure Proc finish { }
{ global ns tracefile1 namfile
$ns flush-trace Close $tracefile1 Close $namfile Exec namout.nam& Exit 0
}

38
REG NO : 411622243002

Definition of a network of links and nodes


The wayto define a node is
set n0 [$ns node]
Once we define several nodes, we can define the links that connect them. An example of a
definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail

Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacityof 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace ―duplex-link
by simplex-link.
In ns, an output queue of a node is implemented as a part of each link whose input is that node.
We should also define the buffer capacityof the queue related to each link. An example would
be:
#set Queue Size of link (n0-n2) to 20

$ns queue-limit $n0 $n2 20


FTP over TCP
TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created bythe
destinationto know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas. The
type of agentappears in the first line:
set tcp [new Agent/TCP]
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.
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1
$udp set null [new
Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_2

#setup a CBR over UDP connection


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
39
REG NO : 411622243002

$tcp $sink finally makes the TCP connection between the source and destination nodes.

40
REG NO : 411622243002

set cbr [new Application/Traffic/CBR]


$cbrattach-agent $udp
$cbrset packetsize_ 100
$cbr set rate_ 0.01Mb
$cbrset random_ false

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 toanother 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
Thus the Network Simulator 2 has been studied in detail.

41
REG NO : 411622243002

EXP.NO:7b CONGESTION CONTROL IN TCP

CONGESTION CONTROL:
Congestion refers to a network state where a node or link carries so much data that it may
deterioratenetwork service quality, resulting in queuing delay, frame or data packet loss and the blocking of
new connections. In Congestion control, end systems throttle back in order to avoid congesting the
network. The mechanism
is similar to end-to-end flow controls, but the intention is to reduce congestion in the network, not the
receiver.
Network simulator 2 (Ns2 Program for congestion controloutputs better results).

Techniques available in congestion control:

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.
o Implicit feedback.
o Choke packet.

42
REG NO : 411622243002

TCL SCRIPT FOR CONGESTION CONTROL IN TCP

TCL SCRIPT FOR CONGESTION CONTROL IN TCP


set ns [new Simulator]
set f [ open congestion.tr w ]
$ns trace-all $f
set nf [ open congestion.namw ]
$ns namtrace-all $nf
$ns color 1 Red
$ns color 2 Blue
$ns color 3 White
$ns color
4 Green
#to 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]
# to create the link between the nodes with bandwidth, delay and queue
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 200ms DropTail
$ns duplex-link $n3 $n4 0.5Mb 40ms DropTail
43
REG NO : 411622243002

$ns duplex-link $n3 $n5 0.5Mb


30ms DropTail # Sending node with
agent as Reno Agent
set tcp1 [new Agent/TCP/Reno]
$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
44
REG NO : 411622243002

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 $p0
set 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"
45
REG NO : 411622243002

$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 tcp-reno.cc
file proc plotWindow {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

46
REG NO : 411622243002

OUTPUT:

RESULT:
Thus the Congestion Control Algorithm has been Simulated and studied.

47
REG NO : 411622243002

EXP.NO:08
Study of TCP/UDP performance using Simulation tool.

AIM:

To simulate the studyof tcp and udp using NS2

TRANSMISSION CONTROL PROTOCOL:


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
partshave been discarded falls to TCP.
TCP manages the flow of datagram’s from the higher layers, as well as incoming datagram’s 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 datagram’s, as well as failures in the
lower layers. TCP also must maintain a state table of alldata streams in and out ofthe 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.
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 datagram’s, 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 modelthan the IP layer.

User Datagram Protocol:

set ns [new Simulator] set nf [open out.nam w]


$ns namtrace-all $nf
set nt [open out.tr w]
$ns trace-all $nt
proc finish {} {
global ns nf
$ns flush-trace close $nf
exec namout.nam& exit 0
}

set h1 [$ns node]


48
REG NO : 411622243002

set r1 [$ns node]


set h2 [$ns
node] set h3
[$ns node] set r2
[$ns node] set
h4 [$ns node]
$ns duplex-link $h1 $r1 10Mb 20ms DropTail
$ns duplex-link $h2 $r1 10Mb 20ms DropTail
$ns duplex-link $r1 $r2 1.5Mb 20ms DropTail
$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]
$ns attach-agent $h3 $sink
$ns connect $udp $null
$ns connect $tcp $sink
$ns at 0.0 "$cbr start"
$ns at 0.0 "$ftp start"
$ns at 10.0 "finish"
$ns run
49
REG NO : 411622243002

50
REG NO : 411622243002

OUTPUT:

RESULT:
Thus the NS2 with TCP and UDP packets has been Simulated and studied.

51
REG NO : 411622243002

EXP.NO:9a SIMULATION OF DISTANCE VECTOR ROUTING ALGORITHM

AIM:
To simulate and studythe Distance Vector routing algorithmusing simulation.

SOFTWARE REQUIRED:
NS-2

THEORY:
Distance Vector Routing is one of the routing algorithms in a Wide Area Network for
computing shortest path between source and destination. The Router is one main device used in a
wide area network. The main task of the router is Routing. It forms the routing table and delivers the
packets depending upon the routes in the table- either directly or via an intermediate device.
Each router initially has information about its all neighbors. Then this information will be shared
among nodes.

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 tracefile.
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 protocolto transmit data fromsender to receiver.
10. Schedule events and run the program.

PROGRAM:
routing1.tcl
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 routing1.tr w]
$ns trace-all $file1

#Open the NAM trace file


set file2 [open routing1.nam w]
$ns namtrace-all $file2

#Define a 'finish'
52
REG NO : 411622243002

53
REG NO : 411622243002

procedureproc finish {} {
global ns file1 file2
$ns flush-traceclose $file1 close $file2
exec nam routing1.nam &exit 0
}

# 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 n3 [$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-down
$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


$ns rtmodel-at 3.0 up $n1 $n4

$ns at 0.1 "$ftp start"

$ns at 6.0 "finish"

54
REG NO : 411622243002

$ns run

55
REG NO : 411622243002

OUTPUT:

RESULT:
Thus the Distance vector Routing Algorithm has been Simulated and studied.

56
REG NO : 411622243002

EXP.NO:9b SIMULATION OF LINK STATE ROUTING ALGORITHM

AIM:
To simulate and studythe link state routing algorithmusing simulation.

SOFTWARE REQUIRED: NS-2

THEORY:
In link state routing, each router shares its knowledge of its neighborhood with every other
router in the internetwork. (i) Knowledge about Neighborhood: 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 itschosen node. These nodes and their arcs are added temporarily to the tree.
The last two steps are repeated until every node in the network has become a
permanent part of the tree.

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 tracefile.
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 protocolto transmit data fromsender to receiver.
10. Schedule events and run the program.

57
REG NO : 411622243002

PROGRAM:

set ns [new Simulator]


set nr [openthro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]

$ns namtrace-all
$nfproc finish {
}{
global ns nr nf
$ns flush-trace
close$nf
close$nr
exec namthro.nam&
exit 0
}
for { set i 0 } { $i< 12} { incr i 1 }
{ setn($i) [$ns node]}

for {set i 0} {$i< 8} {incri} {


$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 set udp0 [new Agent/UDP]
$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 setnull0 [new
Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new
Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]

58
REG NO : 411622243002

$cbr1 set packetSize_ 500


$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
setnull0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$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)
$udp0 set fid_1
$udp1 set fid_2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0start"
$ns at 2.0 "$cbr1start"
$ns at 45 "finish"
$ns run

56
REG NO : 411622243002

55

OUTPUT:

RESULT:

Thus the Link State Routing Algorithm has been Simulated and studied.

57
REG NO : 411622243002

SIMULATION OF ERROR DETECTION CODE


EXP.NO:10 (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 ofthe 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 java.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc=new
Scanner(System.in);
int m,g[],n,d[],z[],r[],msb,i,j,k;
System.out.print("Enter no. of data bits :
"); n=sc.nextInt();
System.out.print("Enter no. of generator bits :
"); m=sc.nextInt();
d=new
int[n+m];
g=new int[m];
System.out.print("Enter data bits :
"); for(i=0;i<n;i++)
d[i]=sc.nextInt();
System.out.print("Enter generator bits :
"); for(j=0;j<m;j++)
g[j]=sc.nextInt();
for(i=0;i<m-1;i+
+) d[n+i]=0;
58
REG NO : 411622243002

r=new int[m+n];for(i=0;i<m;i++)r[i]=d[i];
z=new int[m];
for(i=0;i<m;i++)z[i]=0;
for(i=0;i<n;i++)
{ k=0;
msb=r[i];
for(j=i;j<m+i;j++)
{
if(msb==0) r[j]=xor(r[j],z[k]);
else
r[j]=xor(r[j],g[k]
);k++;
}
r[m+i]=d[m+i];
}
System.out.print("The code bits added are :
"); for(i=n;i<n+m-1;i++)
{
d[i]=r[i];
System.out.print(d[i]);
}
System.out.print("\nThe code data is :
"); for(i=0;i<n+m-1;i++)
{
System.out.print(d[i]);
}
}
public static int xor(int x,int y)
{
if(x==y)
return(0);
else
return(1);
}
}

59
REG NO : 411622243002

OUTPUT:

Enter no. of data bits : 14


Enter no. of generator bits :
4 Enter data bits:11
0
1
0
0
1
1
1
0
1
1
0
0
Enter generator bits :
10 1
1
The code bits added are : 100
The code data is : 11010011101100100

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

60

You might also like