You are on page 1of 69

CS8581 NETWORKS LABORATORY

LIST OF EXPERIMENTS

1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and


traceroute. Capture ping and traceroute PDUs using a network protocol analyzer
and examine.
2. Write a HTTP web client program to download a web page using TCP sockets.
3. Applications using TCP sockets like:
 Echo client and echo server
 Chat
 File Transfer
4. Simulation of DNS using UDP sockets.
5. Write a code simulating ARP /RARP protocols.
6. Study of Network simulator (NS) and Simulation of Congestion Control
Algorithms using NS.
7. Study of TCP/UDP performance using Simulation tool.
8. Simulation of Distance Vector/ Link State Routing algorithm.
9. Performance evaluation of Routing protocols using Simulation tool.
10. Simulation of error correction code (like CRC).
Exp #1 Network Utitilities
Date:

1. ping
Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control
Message Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply
messages are displayed, along with round-trip times. Ping is the primary TCP/IP command
used to troubleshoot connectivity, reachability, and name resolution.

To test a TCP/IP configuration, ping the loopback address by typing ping 127.0.0.1
The results should tell if the connection was successful or if there is any lost packets due to
poor network connection or congestion.

2. ifconfig / ipconfig
Displays basic current TCP/IP network configuration. It is very useful to troubleshoot
networking problems. ipconfig/all is used to provide detailed information such as IP
address, subnet mask, MAC address, DNS server, DHCP server, default gateway etc.
ipconfig/renew is used to renew a DHCP assigned IP address whereas
ipconfig/release is used to discard the assigned DHCP IP address.

3. traceroutet / tracert
Displays the path taken to a destination by sending ICMP Echo Request messages to the
destination with TTL field values. The path displayed is the list of nearest router interfaces
taken along each hop in the path between source host and destination.

1
4. netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet
statistics, IP routing table, IPv4 statistics and IPv6 statistics. It indicates state of a TCP
connection. it's a helpful tool in finding problems and determining the amount of traffic on
the network as a performance measurement.

5. nslookup
It provides a command-line utility for querying DNS table of a DNS Server. It returns IP
address for the given host name.

2
6. tcpdump
tcpdump is a most powerful and widely used command-line packets sniffer or package
analyzer tool which is used to capture or filter TCP/IP packets that received or transferred
over a network on a specific interface for analysis.

Result
Thus TCP/IP network command utilities were executed.

3
Exp# 1a Ping Command
Date:

Aim
To test the communication between hosts at IP level using Ping command.

Algorithm
1. Get IP address / domain name from the user.
2. Create a runtime environment.
3. Execute ping command with given input as parameter.
4. Analyse the output
5. Stop

4
Program

// PingServer.java : Simple Ping Program

import java.io.*;
import java.net.*;

class PingServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print("Enter IP address/domain name: ");
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
String ip = buf1.readLine();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("ping " + ip);
InputStream in = p.getInputStream();
BufferedReader buf2 = new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine()) != null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

5
Output

$ javac PingServer.java
$ java PingServer
Enter IP address/domain name: gmail.com

PING gmail.com (216.58.199.165) 56(84) bytes of data.

64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=1 ttl=58 time=34.7 ms


64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=2 ttl=58 time=36.2 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=3 ttl=58 time=32.0 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=4 ttl=58 time=32.4 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=5 ttl=58 time=31.5 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=6 ttl=58 time=32.8 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=7 ttl=58 time=31.1 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=8 ttl=58 time=32.7 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=9 ttl=58 time=31.8 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=10 ttl=58 time=31.4 ms

^C

--- gmail.com ping statistics ---

10 packets transmitted, 10 received, 0% packet loss, time


9011ms

rtt min/avg/max/mdev = 31.148/32.724/36.287/1.547 ms

Result
Thus using Ping command, connective and communicative status is determined.

6
Exp# 1b Traceroute Command
Date:

Aim
To trace the path traversed by a packet from host to destination using Traceroute
command.

Algorithm
1. Get domain name from the user.
2. Create a runtime environment.
3. Execute traceroute command with given input as parameter.
4. Analyse the output
5. Stop

7
Program

// TraceServer.java : Traceroute Program

import java.io.*;
import java.net.*;

class TraceServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print("Enter domain name : ");
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
String ip = buf1.readLine();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("tracert " + ip);
InputStream in = p.getInputStream();
BufferedReader buf2 = new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine()) != null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

8
Output

$ javac TraceServer.java
$ java TraceServer
Enter domain name: yahoo.com

Tracing route to yahoo.com [206.190.36.45]


over a maximum of 30 hops:

1 <1 ms <1 ms <1 ms 172.16.4.4


2 18 ms 17 ms 10 ms 182.19.59.114
3 154 ms 184 ms 158 ms 182.19.115.233
4 158 ms 156 ms 155 ms ae5-xcr2.lsw.cw.net [166.63.217.41]
5 232 ms 224 ms 230 ms ae11-xcr1.lns.cw.net [195.2.25.206]
6 155 ms 155 ms 170 ms ae1-xcr1.ltw.cw.net [195.2.24.125]
7 233 ms 234 ms 232 ms et-9-1-0-xcr2.nyk.cw.net [195.2.8.46]
8 243 ms 230 ms 228 ms pat1.nyc.yahoo.com [198.32.118.24]
9 230 ms 260 ms 231 ms ae7.pat1.dce.yahoo.com [216.115.104.120]
10 243 ms 245 ms 244 ms ae-6.pat1.che.yahoo.com [216.115.96.81]
11 334 ms 318 ms 294 ms ae-5.pat1.dnx.yahoo.com [216.115.96.34]
12 303 ms 313 ms 335 ms ae-8.pat2.gqb.yahoo.com [216.115.96.204]
13 314 ms 319 ms 316 ms et-18-1-0.msr2.gq1.yahoo.com [66.196.67.115]
14 * 301 ms 304 ms et-19-1-0.clr2-a-gdc.gq1.yahoo.com [67.195.37.99]
15 306 ms 311 ms 305 ms UNKNOWN-67-195-1-X.yahoo.com [67.195.1.251]
16 307 ms 309 ms 300 ms po-16.bas2-7-prd.gq1.yahoo.com [206.190.32.43]
17 303 ms 312 ms 303 ms ir1.fp.vip.gq1.yahoo.com [206.190.36.45]

Trace complete.

Result
Thus using traceroute command, path traversed by the packet is determined.

9
Exp# 2 WebPage Download
Date:

Aim
To download a web page using java URL method.

Algorithm
1. Get URL from the user.
2. Create a file instance to store the downloaded page.
3. Download the page using java URL methods.
4. View the download page
5. Stop

10
Program

// Java file to download a Web page – DownloadPage.java

import java.io.*;
import java.net.*;

class MyDownload
{
public void Download() throws Exception
{
try
{
String WebPage, MyPage;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

// URL Instance
System.out.print("Enter the URL : ");
WebPage = br.readLine();
URL url = new URL(WebPage);

// File Instance
System.out.print("Enter filename to store : ");
MyPage = br.readLine();
File Out = new File(MyPage);
FileOutputStream FOS = new FileOutputStream(Out);

// Dowload the page


InputStream in = url.openStream();
byte buf[] = new byte[1024];
int i, len;
while( (len = in.read(buf)) > 0 )
{
for(i = 0; i < len; i++)
{
FOS.write((char)buf[i]);
}
}

// Close the streams


in.close();
FOS.close();

}
catch (MalformedURLException M)
{
System.out.println(M);
}

11
catch (Exception E)
{
System.out.println(E);
}
}
}

class DownloadPage
{
public static void main(String args[]) throws Exception
{
String Choice;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
MyDownload MDP = new MyDownload();
MDP.Download();
System.out.println("Download complete. View the file");
}
}

12
Output

$ javac DownloadPage.java
$ java DownloadPage
Enter the URL : http://www.google.co.in
Enter filename to store : mypage.html
Download complete. View the file

Result
Thus using java URL methods, a webpage is downloaded.

13
TCP Sockets

A socket is an endpoint of a two-way communication link between two programs running on


the network. Socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent. User-level process/services generally use port
number value > 1024. TCP provides a reliable, point-to-point communication channel that
client-server application on the Internet use to communicate with each other. Examples are
FTP and Telnet.

To communicate over TCP, a client program and a server program establish a connection to
one another. Each program binds a socket to its end of the connection. A server runs on a
specific computer and has a socket that is bound to a specific port number. The server waits,
listening to the socket for a connection request from the client.

On the client-side, the client knows the hostname of the machine on which the server is
running and the port number on which the server is listening. To make a connection request,
the client tries to make contact with the server on the server's machine and port. The client
also needs to identify itself to the server so it binds to a local port number that it will use
during this connection.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address
and port of the client. It needs a new socket so that it can continue to listen to the original
socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server. The client and server can now
communicate by writing to or reading through I/O streams from their sockets and eventually
close it.

The two key classes from the java.net package used in creation of server and client programs
are:
ServerSocket
Socket

14
Exp# 3a TCP Echo Server/Client
Date:

Aim
To implement echo server and client in java using TCP sockets.

Algorithm

Server
1. Create a server socket.
2. Wait for client to be connected.
3. Read text from the client
4. Echo the text back to the client.
5. Repeat steps 4-5 until ‘bye’ or ‘null’ is read.
6. Close the I/O streams
7. Close the server socket
8. Stop

Client
1. Create a socket and establish connection with the server
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send text to the server.
5. Display the text echoed by the server
6. Repeat steps 2-4
7. Close the I/O streams
8. Close the client socket
9. Stop

15
Program

// TCP Echo Server--tcpechoserver.java

import java.net.*;
import java.io.*;

public class tcpechoserver


{
public static void main(String[] arg) throws IOException
{
ServerSocket sock = null;
BufferedReader fromClient = null;
OutputStreamWriter toClient = null;
Socket client = null;
try
{
sock = new ServerSocket(4000);
System.out.println("Server Ready");
client = sock.accept();
System.out.println("Client Connected");
fromClient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
toClient = new
OutputStreamWriter(client.getOutputStream());
String line;
while (true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();
toClient.close();
client.close();
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);
}
}
}

16
//TCP Echo Client--tcpechoclient.java

import java.net.*;
import java.io.*;

public class tcpechoclient


{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser = null;
PrintWriter toServer = null;
Socket sock = null;
try
{
if (args.length == 0)
sock = new Socket(InetAddress.getLocalHost(),
4000);
else
sock = new Socket(InetAddress.getByName(args[0]),
4000);
fromServer = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),
true
String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)
{
System.out.print("Enter msg to server : ");
Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye");
break;
}
else
toServer.println(Usrmsg);
Srvmsg = fromServer.readLine();
System.out.println(Srvmsg);
}
fromUser.close();
fromServer.close();
toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}

17
}
}

Output

Server Console
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready
Client Connected
Client [ hello ]
Client [ how are you ]
Client [ i am fine ]
Client [ ok ]
Client Disconnected

Client Console
$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye

Result
Thus data from client to server is echoed back to the client to check reliability/noise level
of the channel.

18
Exp# 3b TCP Chat Server/Client
Date:

Aim
To implement a chat server and client in java using TCP sockets.

Algorithm

Server
1. Create a server socket
2. Wait for client to be connected.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop

Client
1. Create a client socket and establish connection with the server
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop

19
Program
// TCP Chat Server--tcpchatserver.java
import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " +
CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
}
catch (Exception E)
{
System.out.println(E.getMessage());
}
}
}

20
// TCP Chat Client--tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
if (args.length > 1)
{
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),
5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
}

21
Output

Server Console
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected

Server <<< hi
Message to Client : hello

Server <<< how r u?


Message to Client : fine

Server <<< me too


Message to Client : bye

Client Disconnected

Client Console
$ javac tcpchatclient.java
$ java tcpchatclient
Type "end" to Quit

Message to Server : hi
Client <<< hello

Message to Server : how r u?


Client <<< fine

Message to Server : me too


Client <<< bye

Message to Server : end

Result
Thus both the client and server exchange data using TCP socket programming.

22
Exp# 3c TCP File Server/Client
Date:

Aim
To implement a file server and client in java using TCP sockets.

Algorithm

Server
1. Create a server socket
2. Wait for client to be connected.
3. Read filename from client
4. Open the file using java File methods
5. Write file contents onto stream until EOF
6. Close all streams
7. Close the server and client socket
8. Stop

Client
1. Create a client socket and establish connection with the server
2. Get filename from user and send it to server
3. Read file contents from server stream and display it
4. Close all input/output streams
5. Close the client socket
6. Stop

23
Program
// TCP File Server -- FileServer.java

import java.io.*;
import java.net.*;

public class FileServer


{
public static void main(String[] args) throws Exception
{
File dir;
ServerSocket ss;
Socket conn;
BufferedReader br;
PrintWriter pw;

if(args.length == 0)
dir = new File("./");
else
dir = new File(args[0]);
if(!dir.exists() || !dir.isDirectory())
{
System.out.println("Directory does not exist");
System.exit(-1);
}

try
{
ss = new ServerSocket(3210);
conn = ss.accept();
br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
pw = new PrintWriter(conn.getOutputStream());

String name = br.readLine().trim();


File F = new File(dir, name);
if((!F.exists()) || F.isDirectory())
pw.println("File does not exists");
else
{
pw.println("\n");
BufferedReader fin = new BufferedReader(new
FileReader(F));
while(true)
{
String line = fin.readLine();
if(line == null)
break;
pw.println(line);
}

24
System.out.println("File Transferred\n");
}
pw.flush();
pw.close();
}
catch(Exception e) {
System.out.println("Error: " + e);
}
}
}

// TCP File Client -- FileClient.java


import java.io.*;
import java.net.*;
class FileClient
{
public static void main(String args[])throws Exception
{
try
{
Socket Clt;
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),
3210);
else
Clt = new
Socket(InetAddress.getByName(args[0]),3210);

PrintWriter OS =new PrintWriter(new


BufferedWriter(new OutputStreamWriter(Clt.getOutputStream())),
true);
BufferedReader IS = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;

System.out.print("\nFilename : ");
CltMsg = br.readLine();
OS.println(CltMsg);

while ((SrvMsg = IS.readLine()) != null)


System.out.println(SrvMsg);
}
catch(Exception E) {
System.out.println(E.getMessage());
}
}
}
25
Output

Server Console
$ javac FileServer.java
$ java FileServer
File Transferred

Client Console

$ javac FileClient.java
$ java FileClient
Filename : hello.java

import java.io.*;
class hello
{
public static void main(String args[])
{
System.out.println("hello");
}
}

Result
Thus file contents was sent from server to client using TCP socket programming.

26
UDP Sockets

TCP guarantees the delivery of packets and preserves their order on destination. Sometimes
these features are not required, since they do not come without performance costs, it would
be better to use a lighter transport protocol such as UDP (User Datagram Protocol). UDP is
an unreliable protocol, i.e., it does not include software mechanisms for retrying on
transmission failures or data corruption (unlike TCP), and has restrictions on message length
(< 65536 bytes). Examples are NFS, DNS, SNMP, Clock Server, Ping, VoIP, online games
etc.

Unlike TCP there is no concept of a connection, UDP is a protocol that sends independent
packets of data, called datagrams, from one computer to another with no guarantees
about arrival and sequencing. No packet has any knowledge of the preceding or following
packet. The recipient does not acknowledge packets, thereby the sender does not know
whether the transmission was successful. The format of datagram packet is

Message Length Host Server Port

A program can use a single UDP socket to communicate with more than one host and port
number, but it is convenient for most UDP client programs to maintain the fiction that there is
a connection, by keeping a local record of each server host and port number. A UDP server
does not have to listen for and accept client connections, and a UDP client need not connect
to a server.

Java supports datagram communication through the following classes:


DatagramPacket
DatagramSocket

The DatagramPacket object is the data container, while the DatagramSocket is the
mechanism used to send or receive the DatagramPackets.

27
Exp# 4 UDP DNS Server/Client
Date:

Aim
To implement a DNS server and client in java using UDP sockets.

Algorithm

Server
1. Define a array of hosts and its corresponding IP address in another array
2. Create a datagram socket
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Construct a datagram packet to send response back to the client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop

Client
1. Create a datagram socket
2. Get domain name from user
3. Construct a datagram packet to send domain name to the server
4. Create a datagram packet to receive server message
5. If it contains IP address then display it, else display "Domain does not exist"
6. Close the client socket
7. Stop

28
Program

// UDP DNS Server -- udpdnsserver.java

import java.io.*;
import java.net.*;

public class udpdnsserver


{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}

public static void main(String arg[])throws IOException


{
String[] hosts = {"yahoo.com", "gmail.com",
"cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19",
"80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");

while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
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);

29
serversocket.close();
}
}
}

//UDP DNS Client -- udpdnsclient.java

import java.io.*;
import java.net.*;

public class udpdnsclient


{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
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();
}
}

30
Output

Server Console
$ javac udpdnsserver.java
$ java udpdnsserver
Press Ctrl + C to Quit
Request for host yahoo.com

Client Console
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184

Result
Thus domain name requests by the client are resolved into their respective logical
address using lookup method.

31
Address Resolution

A host or router to send an IP datagram, needs to know both the logical and physical
address of the destination.

Address Resolution Protocol (ARP)


Address Resolution Protocol (ARP) enables a source host to know the physical
address of another node when the logical address is known.
ARP relies on broadcast support from physical networks such as ethernet, token ring,
etc.
ARP is a request/reply protocol
o ARP Request packet is broadcasted by the source host
o ARP Reply packet is sent by destination host to source host
ARP enables each host on a network to build up a mapping table between IP address
and physical address.

Reverse Address Resolution Protocol (RARP)


A diskless workstation booted from its ROM or newly booted workstation does not
know its IP address as it is assigned by the network administrator.
Reverse Address Resolution protocol (RARP) allows a host to find its IP address
using RARP request (broadcasted) and RARP reply.
RARP is replaced by protocols such as BOOTP and DHCP.

32
Exp# 5a ARP Client/Server
Date:

Aim
To know the physical address of a host when its logical address is known using ARP
protocol.

Algorithm

Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read IP address from the client request
4. Check its configuration file and compare with its logical address.
5. If there is a match, send the host physical address.
6. Stop

Client
1. Create a socket.
2. Send IP address to the target machine
3. Receive target's response
4. If it is a MAC address then display it and go to step 6
5. Display "Host not found"
6. Stop

33
Program

// ARP Server -- arpserver.java


import java.io.*;
import java.net.*;

class arpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
String str;

PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin=new BufferedReader(new
InputStreamReader(p.getInputStream()));
String haddr = "";
String ipaddr = br.readLine();
int flag = 0;

while((str = pin.readLine())!=null)
{
System.out.println(str);
if((str.indexOf("HWaddr")) != -1)
{
int tlen = str.length();
int hlen = tlen - 19;
haddr = str.substring(hlen,tlen);
}
else if ((str.indexOf(ipaddr)) != -1)
{
flag = 1;
}
}
if (flag == 1)
ps.println(haddr);

ps.close();
br.close();
pin.close();
client.close();

34
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}

// ARP Client -- arpclient.java


import java.io.*;
import java.net.*;

class arpclient
{
public static void main(String args[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String ipaddr,haddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));

System.out.print("Enter the IP address : ");


ipaddr = br.readLine();
ps.println(ipaddr);
haddr = sin.readLine();
if (haddr == null)
System.out.println("Host does not exist");
else
System.out.println("Physical Address " + haddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}
}
}

35
Output

Server
$ javac arpserver.java
$ java arpserver
Server started
eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06
inet addr:172.16.12.251 Bcast:172.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TX packets:127 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)
Interrupt:16

Client
$ javac arpclient.java
$ java arpclient
Enter the IP address : 172.16.12.251
Physical Address B8:AC:6F:1B:AB:06

Result
Thus using ARP protocol, server’s MAC address is obtained.

36
Exp# 5b RARP Client/Server
Date:

Aim
To know the logical address of a host when its physical address is known using RARP
protocol.

Algorithm

Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read MAC address from the client request
4. Check its configuration file and compare with its physical address.
5. If there is a match, send the host logical address.
6. Stop

Client
1. Create a socket.
2. Send physical address to the target machine
3. Receive target's response
4. If it is a IP address then display it and go to step 6
5. Display "Host not found"
6. Stop

37
Program

// RARP Server -- rarpserver.java


import java.io.*;
import java.net.*;
class rarpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
String str;
PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String ipaddr = "";
String haddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if ((str.indexOf(haddr)) != -1)
{
flag = 1;
}
else if((str.indexOf("inet addr")) != -1)
{
int pos = str.indexOf("inet addr:") + 10;
int offset = pos + 13;
ipaddr = str.substring(pos,offset);
}
}
if (flag == 1)
ps.println(ipaddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();

38
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}

// RARP Client -- rarpclient.java


import java.io.*;
import java.net.*;

class rarpclient
{
public static void main(String args[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String haddr,ipaddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
System.out.print("Enter the physical address : ");
haddr = br.readLine();
ps.println(haddr);
ipaddr = sin.readLine();
if (ipaddr == null)
System.out.println("Host does not exist");
else
System.out.println("Logical Address " + ipaddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}
}
}

39
Output

Server
$ javac rarpserver.java
$ java rarpserver
Server started
eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06
inet addr:172.16.12.251 Bcast:172.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TX packets:127 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)
Interrupt:16

Client
$ javac rarpclient.java
$ java rarpclient
Enter the physical address : B8:AC:6F:1B:AB:06
Logical Address 172.16.12.251

Result
Thus using RARP protocol, IP address of the server is obtained.

40
Exp#6 NS2 SIMULATION
Date:

A simulator is a device, software or system which behaves or operates like a given system
when provided with a set of controlled inputs. The need for simulators is:
Provide users with practical feedback such as accuracy, efficiency, cost, etc., when
designing real world systems.
Permit system designers to study at several different levels of abstraction
Simulation can give results that are not experimentally measurable with our current
level of technology.
Simulations take the building/rebuilding phase out of the loop by using the model
already created in the design phase.
Effective means for teaching or demonstrating concepts to students.
A few popular network simulators are NS-2, OPNET, GLOMOSIM, etc.
Network Simulator NS2
NS2 is an object-oriented, discrete event driven network simulator developed at UC Berkley
written in C++ and OTcl (Object-oriented Tool Command Language). NS is useful for
simulating local and wide area networks. NS2 is an open-source simulation tool that
primarily runs on Linux (cygwin for Windows). The features of NS2 are:
Is a discrete event simulator for networking research
Works at packet level.
Provide support to simulate bunch of protocols like TCP, UDP, FTP, etc.
Simulate wired and wireless network.
Is a standard experiment environment in research community.
Class Hierarchy

Network Animator (NAM)


NS together with NAM forms a very powerful set of tools for teaching networking concepts.
With NAM protocols can be visualized as animations. The NAM graphical editor is the latest
addition to NAM. With this editor, one can create their network topology and simulate
various protocols and traffic sources by dragging the mouse.

41
Create Visualize
Terrestrial, satellite and wireless Packet flow, queue build-up and packet
network with various routing algorithm drops.
(DV, LS, PIM, DSR). Protocol behavior: TCP slow start, self-
Traffic sources like web, ftp, telnet, cbr, clocking, congestion control, fast
and stochastic traffic. retransmit and recovery.
Failures, including deterministic, Node movement in wireless networks.
probabilistic loss, link failure, etc. Annotations to highlight important
Various queuing disciplines (drop-tail, events.
RED, FQ, SFQ, etc.) and QoS Protocol state (e.g., TCP cwnd).

NS2 Execution
The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and
Interpreter. NS simulation results can be observed through graphs by analyzing the trace file
or viewing animations with NAM.

$ ns filename.tcl

NS2 Program Elements

Event Scheduler
a Creating event scheduler
set ns [new Simulator]
b Schedule events
$ns at time "event"
c Start scheduler
$ns run

42
Creating Network
a Create set of Nodes
set n0 [$ns node]
set n1 [$ns node]
b Create links and queuing
$ns duplex-link $n0 $n1 bandwidth delay queue_type
Bandwidth is generally in MB
Delay is generally in ms
Queue type is either DropTail, RED, CBQ, FQ, SFQ, etc
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
c Layout
$ns duplex-link-op $n0 $n2 orient position
where position is either right, right-up, right-down, left, left-
up, left-down, up, down
d Marking flows
$ns color 1 Blue
$ns color 2 Red
$udp0 set class_ 1
$udp1 set class_ 2
Tracing
a NAM Trace all links (must succeed scheduler creation)
set nf [open out.nam w]
$ns namtrace-all $nf
b Trace all links (must succeed scheduler creation)
set tf [open out.tr w]
$ns trace-all $tf
Trace file ouput format
event, time, from_node, to_node, pkt type, pkt size, flags, fid, src_addr, dst_addr,
seq_num, pkt_id
where events are r received, + enqueued, - dequeued, d dropped
c Tracing specific links
$ns trace-queue $n0 $n1
$ns namtrace-queue $n0 $n1

43
Connection
a UDP
set udp [new Agent/UDP]
set null [new Agent/Null]
$ns attach-agent $n0 $udp0
$ns attach-agent $n1 $null
$ns connect $udp0 $null
b TCP
set tcp0 [new Agent/TCP/FullTcp]
$tcp0 set window_ 30
$tcp0 set segsize_ 536
$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCP/FullTcp]
$ns attach-agent $n5 $sink0
$sink0 listen
$ns connect $tcp0 $sink0
Traffic Generation
a UDP
set src [new Application/Traffic/type]
$src attach-agent $udp0
where type is either CBR, Exponential, Pareto
b TCP
set ftp [new Application/FTP]
$ftp attach-agent $tcp
set telnet [new Application/Telnet]
$telnet attach-agent $tcp
Finish procedure
a Flush NS tracing, Close tracing files and execute any post-analysis programs (display
results, run NAM, etc)
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}

Result
Thus simulator NS2 and its basic commands was studied.

44
Exp# 7a Study of UDP Performance
Date:

Aim
To study the performance of UDP by simulating a simple network

Algorithm
1. Create a simulator object
2. Define different color for data flows
3. Trace all events in a nam file.
4. Create four nodes n0, n1, n2 and n3
5. Describe their layout topology
6. Specify the link capacity between nodes
7. Monitor queue on the link n2 to n3 vertically 90°
8. Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively
9. Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively
10. Create a traffic sink and attach it to node n3
11. Connect sources to the sink
12. Label the nodes
13. Schedule cbr0 to start at 0.5 and stop at 4.5 seconds
14. Schedule cbr1 to start at 1.0 and stop at 4.0 seconds
15. Call finish procedure at 5.0 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe simulated events on the NAM and packet flow on link n2 to n3
19. Stop

45
Program

#Study of UDP performance - UDP.tcl

#Create a simulator object


set ns [new Simulator]

#Define different colors for data flows


$ns color 1 Blue
$ns color 2 Red

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#Create links between the nodes


$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms SFQ

#Specify layout of nodes


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#Monitor the queue for the link 2 3 vertically


$ns duplex-link-op $n2 $n3 queuePos 0.5

#Create a UDP agent and attach it to node n0


set udp0 [new Agent/UDP]
$udp0 set class_ 1
$ns attach-agent $n0 $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 UDP agent and attach it to node n1


set udp1 [new Agent/UDP]
$udp1 set class_ 2
$ns attach-agent $n1 $udp1

46
# Create a CBR traffic source and attach it to udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

#Create a Null agent (a traffic sink) and attach it to node n3


set null0 [new Agent/Null]
$ns attach-agent $n3 $null0

#Connect traffic sources with the traffic sink


$ns connect $udp0 $null0
$ns connect $udp1 $null0

#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 out.nam &
exit 0
}

#Define label for nodes


$ns at 0.0 "$n0 label Sender1"
$ns at 0.0 "$n1 label Sender2"
$ns at 0.0 "$n2 label Router"
$ns at 0.0 "$n3 label Receiver"

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 1.0 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

47
Output

$ ns UDP.tcl

Result
Thus the performance of UDP and basic network terminologies were studied using
NS2.

48
Exp# 7b Study of TCP Performance
Date:

Aim
To study the performance of a TCP network with droptail queue mechanism on the
gateway

Algorithm
1. Create a simulator object
2. Define different flows for data flows
3. Trace all events in a nam file and text file
4. Create source nodes (s1, s2, s3), gateway (G) and receiver (r)
5. Describe their layout topology
6. Specify the link between nodes
7. Define the queue size between nodes G and r as 5
8. Monitor queue on all links vertically 90°
9. Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3 respectively
10. Create three TCP sinks and attach it to node r
11. Connect traffic sources to the sink
12. Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3 respectively
13. Label the nodes at start time
14. Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0 seconds
15. Call finish procedure at 5.25 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe the simulated events on the NAM editor and packet flow on link G to r
19. View the trace file and analyse the events
20. Stop

49
Program

#Study of TCP performance - TCP.tcl

#Create a simulator object


set ns [new Simulator]

#Open trace files


set f [open droptail-queue-out.tr w]
$ns trace-all $f

#Open the nam trace file


set nf [open droptail-queue-out.nam w]
$ns namtrace-all $nf

#s1, s2 and s3 act as sources.


set s1 [$ns node]
set s2 [$ns node]
set s3 [$ns node]

#G acts as a gateway
set G [$ns node]
#r acts as a receiver
set r [$ns node]

#Define different colors for data flows


$ns color 1 red
$ns color 2 SeaGreen
$ns color 3 blue

#Create links between the nodes


$ns duplex-link $s1 $G 6Mb 10ms DropTail
$ns duplex-link $s2 $G 6Mb 10ms DropTail
$ns duplex-link $s3 $G 6Mb 10ms DropTail
$ns duplex-link $G $r 3Mb 10ms DropTail

#Define the layout of the nodes


$ns duplex-link-op $s1 $G orient right-up
$ns duplex-link-op $s2 $G orient right
$ns duplex-link-op $s3 $G orient right-down
$ns duplex-link-op $G $r orient right

#Define the queue size for the link between node G and r
$ns queue-limit $G $r 5

#Monitor the queues for links vertically


$ns duplex-link-op $s1 $G queuePos 0.5
$ns duplex-link-op $s2 $G queuePos 0.5
$ns duplex-link-op $s3 $G queuePos 0.5
$ns duplex-link-op $G $r queuePos 0.5

50
#Create a TCP agent and attach it to node s1
set tcp1 [new Agent/TCP/Reno]
$ns attach-agent $s1 $tcp1
$tcp1 set window_ 8
$tcp1 set fid_ 1

#Create a TCP agent and attach it to node s2


set tcp2 [new Agent/TCP/Reno]
$ns attach-agent $s2 $tcp2
$tcp2 set window_ 8
$tcp2 set fid_ 2

#Create a TCP agent and attach it to node s3


set tcp3 [new Agent/TCP/Reno]
$ns attach-agent $s3 $tcp3
$tcp3 set window_ 4
$tcp3 set fid_ 3

#Create TCP sink agents and attach them to node r


set sink1 [new Agent/TCPSink]
set sink2 [new Agent/TCPSink]
set sink3 [new Agent/TCPSink]
$ns attach-agent $r $sink1
$ns attach-agent $r $sink2
$ns attach-agent $r $sink3

#Connect the traffic sources with the traffic sinks


$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
$ns connect $tcp3 $sink3

#Create FTP applications and attach them to agents


set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set ftp3 [new Application/FTP]
$ftp3 attach-agent $tcp3

#Define a 'finish' procedure


proc finish {} {
global ns
$ns flush-trace
puts "running nam..."
exec nam -a droptail-queue-out.nam &
exit 0
}

51
#Define label for nodes
$ns at 0.0 "$s1 label Sender1"
$ns at 0.0 "$s2 label Sender2"
$ns at 0.0 "$s3 label Sender3"
$ns at 0.0 "$G label Gateway"
$ns at 0.0 "$r label Receiver"

#Schedule ftp events


$ns at 0.1 "$ftp1 start"
$ns at 0.1 "$ftp2 start"
$ns at 0.1 "$ftp3 start"
$ns at 5.0 "$ftp1 stop"
$ns at 5.0 "$ftp2 stop"
$ns at 5.0 "$ftp3 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.25 "finish"

#Run the simulation


$ns run

52
Output

$ ns TCP.tcl

Result
Thus the behaviour of TCP was observed and the basic terminologies of TCP
transmission were understood.

53
Exp# 8a Distance Vector Routing Protocol
Date:

Aim
To simulate a link failure and to observe distance vector routing protocol in action.

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

54
Program

#Distance vector routing protocol – distvect.tcl

#Create a simulator object


set ns [new Simulator]

#Use distance vector routing


$ns rtproto DV

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

# Open tracefile
set nt [open trace.tr 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 out.nam &
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

55
# 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
$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

56
Output

$ ns distvect.tcl

57
Result
Thus, performance of distance vector protocol and routing path was studied using NS2.

58
Exp. No. 8b Link State Routing Protocol
Date:

Aim
To simulate a link failure and to observe link state routing protocol in action.

Algorithm
1. Create a simulator object
2. Set routing protocol to Link State 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 twelve nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology in an adhoc manner.
8. Create CBR traffic on top of UDP and set traffic parameters.
9. Create source and sink and connect them
10. Schedule events as follows:
a. Start traffic flows at 1.0 and 2.0
b. Down the link n5-n11 at 10.0 and restore it at 30.0
c. Down the link n7-n6 at 15.0 and restore it at 20.0
d. Call finish procedure at 45.0
11. Start the scheduler
12. Observe the traffic route when link is up and down
13. View the simulated events and trace file analyze it
14. Stop

59
Program

set ns [new Simulator]


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

$ns namtrace-all $nf


proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}

for { set i 0 } { $i < 12 } { incr i 1 } {


set n($i) [$ns node]}

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


$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }

$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail


$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail

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
set null0 [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]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0

60
$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 "$cbr0 start"


$ns at 2.0 "$cbr1 start"

$ns at 45 "finish"
$ns run

Output

$ ns ls.tcl

61
Result:

Thus performance of link state protocol and its routing path was simulated using NS2.

62
Exp# 10 CRC Error Detection
Date:

Aim
To detect whether the given data is corrupted or not using CRC method.

Algorithm
1. Read number of data bits.
2. Read the data bit-by-bit
3. Read number of divisor bits
4. Enter the divisor bit-by-bit
5. Append zeroes to the message
6. Generate remainder by using XOR division
7. Subtract remainder from message using XOR
8. Display the CRC code word
9. Accept transmitted message as receiver side data
10. Peroform polynomial division using XOR
11. If remainder is zero then display “No error” else display “Error”
12. Stop

63
Program

import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;

System.out.println("Enter number of data bits : ");


data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];

System.out.println("Enter data bits : ");


for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());

System.out.println("Enter no. of bits in divisor: ");


divisor_bits=Integer.parseInt(br.readLine());
divisor=new int[divisor_bits];

System.out.println("Enter Divisor bits : ");


for(int i=0; i<divisor_bits; i++)
divisor[i]=Integer.parseInt(br.readLine());

tot_length=data_bits+divisor_bits-1;

div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];

/*------------------ CRC GENERATION---------------------*/


for(int i=0;i<data.length;i++)
div[i]=data[i];

System.out.print("Dividend (after appending 0's): ");


for(int i=0; i< div.length; i++)
System.out.print(div[i]);
System.out.println();

for(int j=0; j<div.length; j++)


rem[j] = div[j];

64
rem=divide(div, divisor, rem);

for(int i=0;i<div.length;i++) //append dividend & rem


{
crc[i]=(div[i]^rem[i]);
}

System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);

/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of " + tot_length
+ " bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());

for(int j=0; j<crc.length; j++)


rem[j] = crc[j];

rem=divide(crc, divisor, rem);

for(int i=0; i< rem.length; i++)


{
if(rem[i]!=0)
{
System.out.println("Error");
break;
}
if(i==rem.length-1)
System.out.println("No Error");
}
}

static int[] divide(int div[],int divisor[], int rem[])


{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);

while(rem[cur]==0 && cur!=rem.length-1)


cur++;

if((rem.length-cur)<divisor.length)
break;
}
return rem;

65
}
}

Output

$javac crc_gen.java

$java crc_gen
Enter number of data bits :
8
Enter data bits :
1
0
0
1
1
0
1
0
Enter no. of bits in divisor:
4
Enter Divisor bits :
1
1
0
1
Dividend (after appending 0's): 10011010000

CRC code :
10011010101
Enter CRC code of 11 bits :
1
0
0
1
1
0
1
0
1
0
1
No Error

Result
Thus error detection is done using cyclic redundancy check method.

66
EX NO 10: PERFORMANCE EVALUATION OF ROUTING PROTOCOL-RIP
AIM:
To evaluate the performance of RIP routing protocol using Cisco Packet Tracer.
CISCO PACKET TRACER:
The Cisco Packet Tracer e-learning software was developed to help Networking Academy
students gain practical networking technology skills in a rapidly changing environment. Students
seeking ICT skills can now benefit from the accessibility of online curricula and new
opportunities for social learning, collaboration, and competition. Cisco®Packet Tracer is a
powerful network simulation program that allows students to experiment with network behavior
and ask “what if” questions. As an integral part of the Networking Academy comprehensive
learning experience, Packet Tracer provides simulation, visualization, authoring, assessment, and
collaboration capabilities to facilitate the teaching and learning of complex technology concepts.
ALGORITHM:
1. Open up the program.
2. Go to (end devices), in the bottom left and drag two (generic routers) to the workspace.
3. Go to (switches), in the bottom left and drag two (Generic switch) to the workspace.
4. Go to (end devices), in the bottom left and drag two (generic PCs) to the workspace.
5. Go to (end devices), in the bottom left and click the connection and select the cable (Copper
straight) to connect the devices.
6. Now click on the PC, it should bring up a menu and then click on the first Ethernet port.
7. Now connect the end of the wire to the first Ethernet port on the switch.
8. Repeat the steps 6 and 7 to connect the PCs to the switch.
9. Now click on the Switch it should bring up a menu a then click on the first Ethernet port.
10. Now connect the end of the wire to the first Ethernet port on the router. Repeat the same for the
other router.
11. Go to the (end devices), in the bottom left and click the connection and select the cable (Serial
DTE) to connect the routers.
12. Now click the router, it should bring up a menu and then click on the first serial port
(eg:Serial2/0).
13.Now connect the end of the wire to the first serial port on the other router.
14. Label between the Routers (192.168.01).
15. Label between the 2 PCs and switch as (192.168.0.0) and other side as (192.168.2.0).
16 Double Click on the PC and go to the desktop tab. Select the IP configurations icon. In the next
window set the IP address for the PC as (192.168.0.2) and also the Gateway as (192.168.0.1).
17. Repeat the same for all the PCs by setting the IP address and default gateway.
18. Double Click on the Switch and go to Config tab. select the interface side menu and mark the
check box to make active the port status. Also type the default gateway IP address. Repeat the same
for the other Switch.
18. Double Click on the Router and go to Config tab. select the serial side menu and mark the check
box to make active the port status. Also type the default gateway IP address. Repeat the same for the
other router.
19.Now double Click the Router and select the Config tab. Select the RIP side menu and add all the IP
addresses that the router is being connected with. Repeat the same with other router.
20. Run the simulation setup by placing the packets in the PCs to view that the connection is
successful.
OUTPUT:

RESULT:
Thus the cisco packet tracer tool was used to implement the routing protocols to see its performance.

You might also like