Cs3591 CN Lab Manual PDF
Cs3591 CN Lab Manual PDF
SrinivasaNagar,Kalamavur,Pudukkottai– 622502
CS3591–Computer Networks
(Regulation–2021)
SYLLABUS
CS3591 COMPUTER NETWORKS LTPC
0042
OBJECTIVES:
Tolearnandusenetworkcommands.
Tolearnsocket programming.
Toimplementandanalyzevariousnetworkprotocols.
Tolearnandusesimulationtools.
Tousesimulationtoolstoanalyzetheperformanceofvariousnetworkprotocols.
LISTOFEXPERIMENTS
1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and
traceroute.CapturepingandtraceroutePDUsusinganetworkprotocol
analyzer and examine.
2. WriteaHTTPwebclientprogramtodownloadawebpageusingTCPsockets.
3. ApplicationsusingTCPsocketslike:
Echoclientandechoserver
Chat
4. SimulationofDNSusingUDPsockets.
5. Illustrate a tool like wireshark to capture and examine the packets.
6. WriteacodesimulatingARP/RARPprotocols.
7. StudyofNetworksimulator(NS)andSimulationofCongestionControlAlgorithms using
NS.
8. StudyofTCP/UDPperformanceusingSimulationtool.
9. SimulationofDistanceVector/LinkStateRoutingalgorithm.
10. Simulationoferrorcorrectioncode(likeCRC).
TOTAL:60PERIODS
OUTCOMES:
UponCompletionofthecourse,thestudentswillbeable to:
ImplementvariousprotocolsusingTCPandUDP.
Comparetheperformanceofdifferenttransportlayerprotocols.
Usesimulationtoolstoanalyzetheperformanceofvariousnetworkprotocols.
Analyzevariousroutingalgorithms.
Implementerrorcorrectioncodes.
STUDENTS:LABORATORYREQUIREMENTFOR
BATCHOF30STUDENTS:
HARDWARE:
1. Standalonedesktops 30 Nos
SOFTWARE:
2. C/C++/Java/Python/EquivalentCompiler 30
3. NetworksimulatorlikeNS2/Glomosim/OPNET/PacketTracer/Equivalent
Exp #1 Networking Commands
Date:
1. ping
VerifiesIP-levelconnectivity toanotherTCP/IPcomputer by sending InternetControl Message
Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply messages
aredisplayed,along with round-trip times.Ping is theprimary TCP/IP command used to
troubleshoot connectivity, reachability, and name resolution.
TotestaTCP/IPconfiguration,pingtheloopbackaddressby typingping127.0.0.1
Theresultsshouldtelliftheconnectionwassuccessfulorifthereisanylostpacketsdueto poor network
connection or congestion.
2. ifconfig/ipconfig
Displays basic current TCP/IP network configuration. It is very useful to troubleshoot
networking problems.ipconfig/allis 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/releaseis used to discardthe 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 interfacestaken
along each hop in the path between source host and destination.
1
4. netstat
DisplaysactiveTCPconnections,portsonwhichthecomputerislistening,Ethernet statistics, IP
routing table, IPv4 statistics and IPv6 statistics. It indicates state of a TCP
connection.it'sahelpfultoolin findingproblemsanddeterminingtheamountoftrafficon the network
as a performance measurement.
5. nslookup
It provides a command-line utility for querying DNS table of a DNS Server. It returns IPaddress
for the given host name.
2
6. tcpdump
tcpdumpisa most powerful andwidely usedcommand-linepacketssniffer orpackage
analyzertoolwhichisusedtocaptureorfilterTCP/IPpacketsthatreceivedortransferred over a
network on a specific interface for analysis.
Result
ThusTCP/IPnetworkcommandutilitieswereexecuted.
3
Exp# 1a PingCommand
Date:
Aim
TotestthecommunicationbetweenhostsatIPlevelusingPingcommand.
Algorithm
1. GetIPaddress/domainnamefromtheuser.
2. Createaruntimeenvironment.
3. Executepingcommandwithgiveninputas parameter.
4. Analysetheoutput
5. Stop
4
Program
import java.io.*;
importjava.net.*;
classPingServer
{
publicstaticvoidmain(Stringargs[])
{
try
{
Stringstr;
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();
BufferedReaderbuf2=newBufferedReader(new
InputStreamReader(in));while((
str=buf2.readLine()) != null)
{
System.out.println(""+str);
}
}
catch(Exceptione)
{
System.out.println(e.getMessage());
}
}
}
5
Output
$javacPingServer.java
$javaPingServer
EnterIPaddress/domainname:gmail.com
PINGgmail.com(216.58.199.165)56(84)bytesofdata.
^C
---gmail.compingstatistics---
rttmin/avg/max/mdev=31.148/32.724/36.287/1.547ms
Result
ThususingPingcommand,connectiveandcommunicativestatusisdetermined.
6
Exp# 1b TracerouteCommand
Date:
Aim
TotracethepathtraversedbyapacketfromhosttodestinationusingTraceroute command.
Algorithm
1. Getdomainnamefromtheuser.
2. Createaruntimeenvironment.
3. Executetraceroutecommandwithgiveninputasparameter.
4. Analysetheoutput
5. Stop
7
Program
import java.io.*;
importjava.net.*;
classTraceServer
{
publicstaticvoidmain(Stringargs[])
{
try
{
Stringstr;
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();
BufferedReaderbuf2=newBufferedReader(new
InputStreamReader(in));while((
str=buf2.readLine()) != null)
{
System.out.println(""+str);
}
}
catch(Exceptione)
{
System.out.println(e.getMessage());
}
}
}
8
Output
$javacTraceServer.java
$javaTraceServer
Enterdomainname:yahoo.com
Tracingroutetoyahoo.com[206.190.36.45]
over a maximum of 30 hops:
Tracecomplete.
Result
Thususingtraceroutecommand,pathtraversedbythepacketisdetermined.
9
Exp#2 WebPageDownload
Date:
Aim
TodownloadawebpageusingjavaURLmethod.
Algorithm
1. GetURLfromtheuser.
2. Createafileinstancetostorethedownloadedpage.
3. DownloadthepageusingjavaURLmethods.
4. Viewthedownloadpage
5. Stop
10
Program
import java.io.*;
importjava.net.*;
classMyDownload
{
publicvoidDownload()throwsException
{
try
{
StringWebPage,MyPage;
BufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));
// URL Instance
System.out.print("Enter the URL : ");
WebPage = br.readLine();
URLurl=newURL(WebPage);
//FileInstance
System.out.print("Enter filename to store : ");
MyPage = br.readLine();
FileOut=newFile(MyPage);
FileOutputStreamFOS=newFileOutputStream(Out);
//Dowloadthepage
InputStream in = url.openStream();
byte buf[] = new byte[1024];
inti,len;
while((len=in.read(buf))>0)
{
for(i=0;i<len;i++)
{
FOS.write((char)buf[i]);
}
}
}
catch(MalformedURLExceptionM)
{
System.out.println(M);
}
11
catch(ExceptionE)
{
System.out.println(E);
}
}
}
classDownloadPage
{
publicstaticvoidmain(Stringargs[])throwsException
{
StringChoice;
BufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));MyDownloa
d MDP = new MyDownload();
MDP.Download();
System.out.println("Downloadcomplete.Viewthefile");
}
}
12
Output
$javacDownloadPage.java
$javaDownloadPage
Enter the URL : http://www.google.co.in
Enter filename to store : mypage.html
Download complete. View the file
Result
ThususingjavaURLmethods,awebpageisdownloaded.
13
TCPSockets
To communicate over TCP, a client program anda server program establish a connection toone
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.
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
newsocketboundtothesamelocal portandalsohasitsremoteendpointsettothe address andport of the
client. It needs anew socket so that it can continue to listen to the original socket for connection
requests while tending to the needs of the connectedclient.
On the client side, if the connection is accepted, a socket is successfully created and the client
canusethesockettocommunicatewiththeserver.Theclientandservercannow 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 TCPEchoServer/Client
Date:
Aim
ToimplementechoserverandclientinjavausingTCPsockets.
Algorithm
Server
1. Createaserversocket.
2. Waitforclienttobeconnected.
3. Readtextfromtheclient
4. Echothetextbacktotheclient.
5. Repeatsteps 4-5until‘bye’or‘null’isread.
6. ClosetheI/Ostreams
7. Closetheserversocket
8. Stop
Client
1. Createasocketandestablishconnectionwiththeserver
2. Getinputfromuser.
3. If equaltobyeornull,thengotostep7.
4. Sendtexttotheserver.
5. Displaythetextechoedbytheserver
6. Repeatsteps2-4
7. ClosetheI/Ostreams
8. Closetheclientsocket
9. Stop
15
Program
import java.net.*;
importjava.io.*;
publicclasstcpechoserver
{
publicstaticvoidmain(String[]arg)throwsIOException
{
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("ClientDisconnected");
}
catch(IOExceptionioe)
{
System.err.println(ioe);
}
}
}
16
//TCPEchoClient--tcpechoclient.java
import java.net.*;
import java.io.*;
publicclasstcpechoclient
{
publicstaticvoidmain(String[]args)throwsIOException
{
BufferedReader fromServer = null, fromUser = null;
PrintWriter toServer = null;
Socket sock = null;
try
{
if(args.length==0)
sock=newSocket(InetAddress.getLocalHost(),
4000);
else
sock=newSocket(InetAddress.getByName(args[0]),
4000);
fromServer=newBufferedReader(new
InputStreamReader(sock.getInputStream()));fromUse
r = 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(IOExceptionioe)
{
System.err.println(ioe);
}
17
}
}
Output
ServerConsole
$javactcpechoserver.java
$ java tcpechoserver
Server Ready
Client Connected
Client [ hello ]
Client [ how are you ]
Client [ i am fine ]
Client [ ok ]
ClientDisconnected
ClientConsole
$javactcpechoclient.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 ]
Entermsgtoserver:bye
Result
Thus data from client toserver is echoed back to the client to check reliability/noise level
of the channel.
18
Exp# 3b TCPChatServer/Client
Date:
Aim
Toimplementachatserverandclientin javausingTCPsockets.
Algorithm
Server
1. Createaserversocket
2. Waitforclienttobeconnected.
3. ReadClient'smessageanddisplayit
4. Getamessagefromuserandsendittoclient
5. Repeatsteps 3-4untiltheclientsends"end"
6. Closeall streams
7. Closetheserverandclientsocket
8. Stop
Client
1. Createaclientsocketandestablishconnectionwiththeserver
2. Getamessagefromuserandsendittoserver
3. Readserver'sresponseanddisplay it
4. Repeatsteps2-3untilchatisterminatedwith"end"message
5. Closeallinput/outputstreams
6. Closetheclientsocket
7. Stop
19
Program
// TCP Chat Server--tcpchatserver.java
import java.io.*;
import java.net.*;
class tcpchatserver
{
publicstaticvoidmain(Stringargs[])throwsException
{
PrintWritertoClient;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=newBufferedReader(new
InputStreamReader(Clt.getInputStream()));fro
mUser = 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(ExceptionE)
{
System.out.println(E.getMessage());
}
}
}
20
// TCP Chat Client--tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
publicstaticvoidmain(Stringargs[])throwsException
{
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=newSocket(InetAddress.getByName(args[0]),
5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer=newBufferedReader(new
InputStreamReader(Clt.getInputStream()));fro
mUser = 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(ExceptionE)
{
System.out.println(E.getMessage());
}
}
}
21
Output
ServerConsole
$javactcpchatserver.java
$ java tcpchatserver
Server started
Client connected
Server<<<hi
MessagetoClient:hello
ClientDisconnected
ClientConsole
$javactcpchatclient.java
$ java tcpchatclient
Type "end" to Quit
Message to Server : hi
Client <<< hello
MessagetoServer:end
Result
ThusboththeclientandserverexchangedatausingTCPsocketprogramming.
22
UDPSockets
TCP guarantees the delivery of packets and preserves their order on destination. Sometimes
thesefeaturesarenotrequired,sincetheydonotcomewithoutperformancecosts,itwould
bebettertousealightertransportprotocolsuchasUDP(UserDatagramProtocol).UDPis an unreliable
protocol, i.e., it does not include software mechanisms for retrying ontransmissionfailuresor
datacorruption (unlikeTCP),andhasrestrictionson messagelength (<
65536bytes).ExamplesareNFS,DNS,SNMP,Clock Server,Ping,VoIP,onlinegames etc.
Unlike TCP there is no concept of a connection, UDPis a protocol that sends independent
packetsof data,calleddatagrams,fromonecomputertoanotherwithnoguarantees about arrival and
sequencing. No packet has any knowledge of the preceding or following
packet.Therecipientdoesnotacknowledgepackets,thereby thesenderdoesnotknow whether the
transmission was successful. The format of datagram packet is
A program can use a single UDP socket to communicate with more than one host and port
number, butitisconvenientformostUDPclientprogramstomaintain thefictionthatthereis a
connection, by keeping a local record of each serverhost and port number.A UDP server
doesnothavetolistenforandacceptclientconnections,andaUDPclientneednotconnect to a server.
Javasupportsdatagramcommunicationthroughthefollowingclasses:
DatagramPacket
DatagramSocket
23
Exp#4 UDPDNSServer/Client
Date:
Aim
ToimplementaDNSserverandclientinjavausingUDPsockets.
Algorithm
Server
1. DefineaarrayofhostsanditscorrespondingIPaddressinanotherarray
2. Createadatagramsocket
3. Createadatagrampackettoreceiveclientrequest
4. Readthedomainnamefromclienttoberesolved
5. Lookupthehostarrayforthedomainname
6. Iffoundthenretrievecorrespondingaddress
7. Constructadatagrampackettosendresponsebacktotheclient
8. Repeatsteps3-7toresolvefurtherrequestsfromclients
9. Closetheserversocket
10. Stop
Client
1. Createadatagramsocket
2. Getdomainnamefromuser
3. Constructadatagrampackettosenddomainnametotheserver
4. Createadatagrampackettoreceiveservermessage
5. IfitcontainsIPaddressthendisplayit,elsedisplay"Domaindoesnotexist"
6. Closetheclientsocket
7. Stop
24
Program
import java.io.*;
importjava.net.*;
publicclassudpdnsserver
{
privatestaticintindexOf(String[]array,Stringstr)
{
str=str.trim();
for(inti=0;i<array.length;i++)
{
if (array[i].equals(str))
return i;
}
return-1;
}
publicstaticvoidmain(Stringarg[])throwsIOException
{
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("PressCtrl+CtoQuit");
while(true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[]receivedata=newbyte[1021];
if(indexOf(hosts,sen)!=-1) capsent =
ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata=capsent.getBytes();
DatagramPacketpack=newDatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
25
serversocket.close();
}
}
}
import java.io.*;
importjava.net.*;
publicclassudpdnsclient
{
publicstaticvoidmain(Stringargs[])throwsIOException
{
BufferedReaderbr=newBufferedReader(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;
DatagramPacketrecvpack=newDatagramPacket(receivedata,
receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}
26
Output
ServerConsole
$javacudpdnsserver.java
$ java udpdnsserver
Press Ctrl + C to Quit
Requestforhostyahoo.com
ClientConsole
$javacudpdnsclient.java
$javaudpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184
Result
Thusdomainnamerequestsbytheclientareresolvedintotheirrespectivelogical address using
lookup method.
27
EXP #5: Illustrate wireshark tool to capture and examine the packets
Aim:
Algorithm:
Open Wireshark.
Set a capture filter, and select the interface on which to capture.
Start the capture.
Generate traffic by connecting to a website, pinging a remote device or attempting any
other network connection.
Stop the capture.
28
Result:
Thus the above experiment was successfully executed and completed.
29
AddressResolution
AddressResolutionProtocol(ARP)
AddressResolutionProtocol(ARP)enablesasourcehosttoknowthephysical address of
another node when the logical address is known.
ARP relies on broadcast support from physical networks such as ethernet, token
ring,etc.
ARPisarequest/replyprotocol
o ARPRequestpacketisbroadcastedbythesourcehost
o ARPReplypacketissentbydestinationhosttosourcehost
ARPenables eachhoston anetwork tobuildupa mappingtablebetweenIPaddress and
physical address.
ReverseAddressResolutionProtocol(RARP)
AdisklessworkstationbootedfromitsROMornewlybootedworkstationdoesnot know its IP
address as it is assigned by the network administrator.
ReverseAddressResolutionprotocol(RARP)allowsahosttofinditsIPaddress using RARP
request (broadcasted) and RARP reply.
RARPisreplacedbyprotocolssuchasBOOTPandDHCP.
30
Exp# 6a ARPClient/Server
Date:
Aim
ToknowthephysicaladdressofahostwhenitslogicaladdressisknownusingARP protocol.
Algorithm
Target/Server
1. Createaserversocket.
2. Acceptclientconnection.
3. ReadIPaddressfromtheclientrequest
4. Checkitsconfigurationfileandcomparewithitslogicaladdress.
5. Ifthereisamatch,sendthehostphysicaladdress.
6. Stop
Client
1. Createasocket.
2. SendIPaddresstothetargetmachine
3. Receivetarget'sresponse
4. IfitisaMACaddressthendisplayitandgotostep6
5. Display "Hostnotfound"
6. Stop
31
Program
classarpserver
{
publicstaticvoidmain(Stringargs[])throwsIOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
String str;
PrintStreamps=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()));S
tring 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);
}
elseif((str.indexOf(ipaddr))!=-1)
{
flag=1;
}
}
if (flag == 1)
ps.println(haddr);
ps.close();
br.close();
pin.close();
client.close();
32
soc.close();
}
catch(IOExceptionio)
{
System.err.println("Exception:"+io.toString());
}
}
}
classarpclient
{
publicstaticvoidmain(Stringargs[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStreamps=new
PrintStream(client.getOutputStream());St
ring ipaddr,haddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
33
Output
Server
$javacarpserver.java
$ java arpserver
Server started
eth0 Linkencap:EthernetHWaddrB8:AC:6F:1B:AB:06
inetaddr:172.16.12.251Bcast:172.255.255.255Mask:255.0.0.0
inet6addr:fe80::baac:6fff:fe1b:ab06/64Scope:Link
UP BROADCAST RUNNING MULTICASTMTU:1500Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TXpackets:127errors:0dropped:0overruns:0carrier:0
collisions:0 txqueuelen:1000
RXbytes:48118(46.9KiB)TXbytes:21025(20.5KiB)
Interrupt:16
Client
$javacarpclient.java
$javaarpclient
Enter the IP address : 172.16.12.251
Physical Address B8:AC:6F:1B:AB:06
Result
ThususingARPprotocol,server’sMACaddressisobtained.
34
Exp# 6b RARPClient/Server
Date:
Aim
ToknowthelogicaladdressofahostwhenitsphysicaladdressisknownusingRARP protocol.
Algorithm
Target/Server
1. Createaserversocket.
2. Acceptclientconnection.
3. ReadMACaddressfromtheclientrequest
4. Checkitsconfigurationfileandcomparewithitsphysicaladdress.
5. Ifthereisamatch,sendthehostlogicaladdress.
6. Stop
Client
1. Createasocket.
2. Sendphysicaladdresstothetargetmachine
3. Receivetarget'sresponse
4. Ifit isaIPaddressthen displayitandgotostep6
5. Display "Hostnotfound"
6. Stop
35
Program
36
}
catch(IOExceptionio)
{
System.err.println("Exception:"+io.toString());
}
}
}
classrarpclient
{
publicstaticvoidmain(Stringargs[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStreamps=new
PrintStream(client.getOutputStream());St
ring 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(IOExceptionio)
{
System.err.println(io.toString());
}
}
}
37
Output
Server
$javacrarpserver.java
$ java rarpserver
Server started
eth0 Linkencap:EthernetHWaddrB8:AC:6F:1B:AB:06
inetaddr:172.16.12.251Bcast:172.255.255.255Mask:255.0.0.0
inet6addr:fe80::baac:6fff:fe1b:ab06/64Scope:Link
UP BROADCAST RUNNING MULTICASTMTU:1500Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TXpackets:127errors:0dropped:0overruns:0carrier:0
collisions:0 txqueuelen:1000
RXbytes:48118(46.9KiB)TXbytes:21025(20.5KiB)
Interrupt:16
Client
$javacrarpclient.java
$javararpclient
Enter the physical address : B8:AC:6F:1B:AB:06
Logical Address 172.16.12.251
Result
ThususingRARPprotocol,IPaddressoftheserverisobtained.
38
Exp#7 NS2SIMULATION
Date:
NetworkSimulatorNS2
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
simulatinglocalandwideareanetworks.NS2isanopen-sourcesimulationtoolthat primarily runs on
Linux (cygwin for Windows). The features of NS2 are:
Isadiscreteeventsimulatorfornetworkingresearch
Worksatpacketlevel.
ProvidesupporttosimulatebunchofprotocolslikeTCP,UDP,FTP,etc.
Simulatewiredandwirelessnetwork.
Isastandardexperimentenvironmentinresearchcommunity.
ClassHierarchy
NetworkAnimator(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
additiontoNAM.Withthiseditor,onecancreatetheirnetworktopologyandsimulate various protocols
and traffic sources by dragging the mouse.
39
Create Visualize
Terrestrial, satellite and wirelessnetwork Packet flow, queue build-up and packet
with various routing algorithm (DV, LS, drops.
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, Nodemovementinwirelessnetworks.
probabilistic loss, link failure, etc. Annotations to highlight important
Variousqueuingdisciplines(drop-tail, events.
RED,FQ,SFQ,etc.)andQoS Protocolstate(e.g.,TCPcwnd).
NS2Execution
The overall simulation procedure in NS is shown below. NS is composed of OTcl Script and
Interpreter.NSsimulation resultscanbeobservedthroughgraphsby analyzingthetracefile or
viewing animations with NAM.
$nsfilename.tcl
NS2ProgramElements
EventScheduler
a Creatingeventscheduler
setns[newSimulator]
b Scheduleevents
$nsattime"event"
c Startscheduler
$nsrun
40
CreatingNetwork
a CreatesetofNodes
set n0 [$ns node]
setn1[$nsnode]
b Createlinksandqueuing
$ns duplex-link $n0 $n1bandwidth delay queue_type
Bandwidth is generally in MB
Delayisgenerallyinms
QueuetypeiseitherDropTail,RED,CBQ,FQ,SFQ,etc
$nsduplex-link$n0$n21Mb10msDropTail
c Layout
$nsduplex-link-op$n0$n2orientposition
where position is either right, right-up, right-down, left, left-
up, left-down, up, down
d Markingflows
$nscolor1Blue
$nscolor2Red
$udp0setclass_1
$udp1setclass_2
Tracing
a NAMTracealllinks(mustsucceedschedulercreation)
setnf[openout.namw]
$nsnamtrace-all$nf
b Tracealllinks(mustsucceedschedulercreation)
settf[openout.trw]
$nstrace-all$tf
Tracefileouputformat
event,time,from_node,to_node,pkttype,pktsize,flags,fid,src_addr,dst_addr, seq_num,
pkt_id
whereeventsarerreceived,+enqueued,-dequeued,ddropped
c Tracingspecificlinks
$nstrace-queue$n0$n1
$nsnamtrace-queue$n0$n1
41
Connection
a UDP
set udp [new Agent/UDP]
set null [new Agent/Null]
$nsattach-agent$n0$udp0
$nsattach-agent$n1$null
$nsconnect$udp0$null
b TCP
settcp0[newAgent/TCP/FullTcp]
$tcp0setwindow_30
$tcp0setsegsize_536
$nsattach-agent$n0$tcp0
setsink0[newAgent/TCP/FullTcp]
$nsattach-agent$n5$sink0
$sink0listen
$nsconnect$tcp0$sink0
TrafficGeneration
a UDP
setsrc[newApplication/Traffic/type]
$srcattach-agent$udp0
wheretypeiseitherCBR,Exponential,Pareto
b TCP
setftp[newApplication/FTP]
$ftpattach-agent$tcp
settelnet[newApplication/Telnet]
$telnetattach-agent$tcp
Finishprocedure
a Flush NS tracing, Close tracing files and execute any post-analysis programs
(displayresults, run NAM, etc)
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
Result
ThussimulatorNS2anditsbasiccommandswasstudied.
42
Exp# 8a StudyofUDPPerformance
Date:
Aim
TostudytheperformanceofUDPbysimulatingasimplenetwork
Algorithm
1. Createasimulatorobject
2. Definedifferentcolorfordataflows
3. Tracealleventsin anamfile.
4. Createfournodesn0,n1,n2andn3
5. Describetheirlayouttopology
6. Specifythelinkcapacitybetweennodes
7. Monitorqueue onthelinkn2ton3vertically90°
8. CreateaUDPagentsudp0,udp1andattachittonodesn0andn1respectively
9. CreateaCBRtrafficcbr0,cbr1and attachittoudp0andudp1respectively
10. Createatrafficsinkandattachittonoden3
11. Connectsourcestothesink
12. Labelthenodes
13. Schedulecbr0tostartat0.5andstopat4.5seconds
14. Schedulecbr1tostartat1.0andstopat4.0seconds
15. Callfinishprocedureat5.0seconds
16. Runthesimulation
17. ExecuteNAMonthetracefile
18. ObservesimulatedeventsontheNAMandpacketflowonlinkn2ton3
19. Stop
43
Program
#Definedifferentcolorsfordataflows
$nscolor1Blue
$nscolor2Red
#Createlinksbetweenthenodes
$nsduplex-link$n0$n21Mb10msDropTail
$nsduplex-link$n1$n21Mb10msDropTail
$nsduplex-link$n3$n21Mb10msSFQ
#Specifylayoutofnodes
$nsduplex-link-op$n0$n2orientright-down
$nsduplex-link-op$n1$n2orientright-up
$nsduplex-link-op$n2$n3orientright
#Monitorthequeueforthelink2—3vertically
$nsduplex-link-op$n2$n3queuePos0.5
44
# Create a CBR traffic source and attach it to udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1setpacketSize_500
$cbr1setinterval_0.005
$cbr1attach-agent$udp1
#Connecttrafficsourceswiththetrafficsink
$nsconnect$udp0$null0
$nsconnect$udp1$null0
#Definelabelfornodes
$nsat0.0"$n0labelSender1"
$nsat0.0"$n1labelSender2"
$nsat0.0"$n2labelRouter"
$nsat0.0"$n3labelReceiver"
#ScheduleeventsfortheCBRagents
$nsat0.5"$cbr0start"
$nsat1.0"$cbr1start"
$nsat4.0"$cbr1stop"
$nsat4.5"$cbr0stop"
#Callfinishprocedureafter5secondsofsimulationtime
$nsat5.0"finish"
#Runthesimulation
$nsrun
45
Output
$nsUDP.tcl
Result
ThustheperformanceofUDPandbasicnetworkterminologieswerestudiedusing
NS2.
46
Exp# 8b StudyofTCPPerformance
Date:
Aim
TostudytheperformanceofaTCPnetworkwithdroptailqueuemechanismonthe gateway
Algorithm
1. Createasimulatorobject
2. Definedifferentflowsfordataflows
3. Tracealleventsinanamfileandtext file
4. Createsourcenodes(s1,s2,s3),gateway(G)andreceiver(r)
5. Describetheirlayouttopology
6. Specifythelinkbetweennodes
7. DefinethequeuesizebetweennodesGandras 5
8. Monitorqueue onalllinksvertically90°
9. CreateTCPagentstcp1,tcp2,tcp3andattachittonodess1,s2ands3respectively
10. CreatethreeTCPsinksandattachittonoder
11. Connecttrafficsourcestothesink
12. CreateFTPagentsftp1, ftp2,ftp3andattachittotcp1,tcp2andtcp3respectively
13. Labelthenodesatstarttime
14. Scheduleftp1,ftp2,ftp3tostartat0.1andstopat5.0seconds
15. Callfinishprocedureat5.25seconds
16. Runthesimulation
17. ExecuteNAMonthetracefile
18. ObservethesimulatedeventsontheNAMeditorandpacketflowonlinkGtor
19. Viewthetracefileandanalysetheevents
20. Stop
47
Program
#Opentracefiles
setf[opendroptail-queue-out.trw]
$nstrace-all$f
#Openthenamtracefile
setnf[opendroptail-queue-out.namw]
$nsnamtrace-all$nf
#G acts as a gateway
set G[$ns node]
#r acts as a receiver
set r [$ns node]
#Definedifferentcolorsfordataflows
$nscolor1red
$nscolor2SeaGreen
$nscolor3blue
#Createlinksbetweenthenodes
$nsduplex-link$s1$G6Mb10msDropTail
$nsduplex-link$s2$G6Mb10msDropTail
$nsduplex-link$s3$G6Mb10msDropTail
$nsduplex-link$G$r3Mb10msDropTail
#Definethelayoutofthenodes
$nsduplex-link-op$s1$Gorientright-up
$nsduplex-link-op$s2$Gorientright
$nsduplex-link-op$s3$Gorientright-down
$nsduplex-link-op$G$rorientright
#DefinethequeuesizeforthelinkbetweennodeGandr
$nsqueue-limit$G$r5
#Monitorthequeuesforlinksvertically
$nsduplex-link-op$s1$GqueuePos0.5
$nsduplex-link-op$s2$GqueuePos0.5
$nsduplex-link-op$s3$GqueuePos0.5
$nsduplex-link-op$G$rqueuePos0.5
48
#Create a TCP agent and attach it to node s1
set tcp1 [new Agent/TCP/Reno]
$ns attach-agent$s1$tcp1
$tcp1setwindow_8
$tcp1setfid_ 1
#Connectthetrafficsourceswiththetrafficsinks
$nsconnect$tcp1$sink1
$nsconnect$tcp2$sink2
$nsconnect$tcp3$sink3
#Define a 'finish'procedure
proc finish {} {
globalns
$nsflush-trace
puts"runningnam."
exec nam -a droptail-queue-out.nam &
exit 0
}
49
#Definelabelfornodes
$nsat0.0"$s1labelSender1"
$nsat0.0"$s2labelSender2"
$nsat0.0"$s3labelSender3"
$nsat0.0"$GlabelGateway"
$nsat0.0"$rlabelReceiver"
#Scheduleftpevents
$nsat0.1"$ftp1start"
$nsat0.1"$ftp2start"
$nsat0.1"$ftp3start"
$nsat5.0"$ftp1stop"
$nsat5.0"$ftp2stop"
$nsat5.0"$ftp3stop"
#Callfinishprocedureafter5secondsofsimulationtime
$nsat5.25"finish"
#Runthesimulation
$nsrun
50
Output
$nsTCP.tcl
Result
ThusthebehaviourofTCPwasobservedandthebasicterminologiesofTCPtransmission were
understood.
51
Exp# 9a DistanceVectorRoutingProtocol
Date:
Aim
Tosimulatealinkfailureandtoobservedistancevectorroutingprotocolinaction.
Algorithm
1. Createasimulatorobject
2. SetroutingprotocoltoDistanceVectorrouting
3. TracepacketsonalllinksontoNAMtraceandtexttracefile
4. Definefinishproceduretoclosefiles,flushtracingandrunNAM
5. Createeightnodes
6. Specifythelinkcharacteristicsbetweennodes
7. Describetheirlayouttopologyasaoctagon
8. AddUDPagentfornoden1
9. CreateCBRtrafficontopofUDPandsettrafficparameters.
10. Addasink agenttonoden4
11. Connectsourceandthesink
12. Scheduleeventsasfollows:
a. Starttrafficflowat0.5
b. Downthelinkn3-n4at1.0
c. Upthelinkn3-n4at2.0
d. Stoptrafficat3.0
e. Callfinishprocedureat5.0
13. Startthescheduler
14. Observethetrafficroutewhenlinkisupanddown
15. Viewthesimulatedeventsandtracefileanalyzeit
16. Stop
52
Program
#Usedistancevectorrouting
$nsrtprotoDV
#Opentracefile
setnt[opentrace.trw]
$nstrace-all$nt
#Define 'finish'procedure
proc finish {} {
globalnsnf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit0
}
# 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]
setn8[$nsnode]
#Specifylinkcharacterestics
$nsduplex-link$n1$n21Mb10msDropTail
$nsduplex-link$n2$n31Mb10msDropTail
$nsduplex-link$n3$n41Mb10msDropTail
$nsduplex-link$n4$n51Mb10msDropTail
$nsduplex-link$n5$n61Mb10msDropTail
$nsduplex-link$n6$n71Mb10msDropTail
$nsduplex-link$n7$n81Mb10msDropTail
$nsduplex-link$n8$n11Mb10msDropTail
53
#specifylayoutasaoctagon
$nsduplex-link-op$n1$n2orientleft-up
$nsduplex-link-op$n2$n3orientup
$nsduplex-link-op$n3$n4orientright-up
$nsduplex-link-op$n4$n5orientright
$nsduplex-link-op$n5$n6orientright-down
$nsduplex-link-op$n6$n7orientdown
$nsduplex-link-op$n7$n8orientleft-down
$nsduplex-link-op$n8$n1orientleft
#Connectthetrafficsourcewiththetrafficsink
$nsconnect$udp0$null0
#ScheduleeventsfortheCBRagentandthenetworkdynamics
$nsat0.0 "$n1labelSource"
$nsat0.0 "$n4labelDestination"
$nsat0.5"$cbr0start"
$nsrtmodel-at1.0down$n3$n4
$nsrtmodel-at2.0up$n3$n4
$nsat4.5"$cbr0stop"
#Callthefinishprocedureafter5secondsofsimulationtime
$nsat5.0"finish"
#Runthesimulation
$nsrun
54
Output
$nsdistvect.tcl
55
Result
Thus,performanceofdistancevectorprotocolandroutingpathwasstudiedusingNS2.
56
Exp.No.9b LinkStateRoutingProtocol
Date:
Aim
Tosimulatealinkfailureandtoobservelinkstateroutingprotocolinaction.
Algorithm
1. Createasimulatorobject
2. SetroutingprotocoltoLinkStaterouting
3. TracepacketsonalllinksontoNAMtraceandtexttracefile
4. Definefinishproceduretoclosefiles,flushtracingandrunNAM
5. Createtwelvenodes
6. Specifythelinkcharacteristicsbetweennodes
7. Describetheirlayouttopologyinanadhocmanner.
8. CreateCBRtrafficontopofUDPandsettrafficparameters.
9. Createsourceandsinkandconnectthem
10. Scheduleeventsasfollows:
a. Starttrafficflowsat1.0and2.0
b. Downthelinkn5-n11at10.0andrestoreitat30.0
c. Downthelinkn7-n6at15.0andrestoreitat20.0
d. Callfinishprocedureat45.0
11. Startthescheduler
12. Observethetrafficroutewhenlinkisupanddown
13. Viewthesimulatedeventsandtracefileanalyzeit
14. Stop
57
Program
for{seti0}{$i<8}{incri}{
$nsduplex-link$n($i)$n([expr$i+1])1Mb10msDropTail}
$nsduplex-link$n(0)$n(8)1Mb10msDropTail
$nsduplex-link$n(1)$n(10)1Mb10msDropTail
$nsduplex-link$n(0)$n(9)1Mb10msDropTail
$nsduplex-link$n(9)$n(11)1Mb10msDropTail
$nsduplex-link$n(10)$n(11)1Mb10msDropTail
$nsduplex-link$n(11)$n(5)1Mb10msDropTail
setudp0[newAgent/UDP]
$nsattach-agent$n(0)$udp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_500
$cbr0setinterval_0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$nsattach-agent$n(5)$null0
$nsconnect$udp0$null0
setudp1[newAgent/UDP]
$nsattach-agent$n(1)$udp1
setcbr1[newApplication/Traffic/CBR]
$cbr1setpacketSize_500
$cbr1setinterval_0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$nsattach-agent$n(5)$null0
$nsconnect$udp1$null0
58
$nsrtprotoLS
$nsrtmodel-at10.0down$n(11)$n(5)
$nsrtmodel-at15.0down$n(7)$n(6)
$nsrtmodel-at30.0up$n(11)$n(5)
$nsrtmodel-at20.0up$n(7)$n(6)
$udp0setfid_1
$udp1setfid_2
$nscolor1Red
$nscolor2Green
$nsat1.0"$cbr0start"
$nsat2.0"$cbr1start"
$nsat45"finish"
$nsrun
Output
$nsls.tcl
59
Result:
Thusperformanceoflinkstateprotocolanditsroutingpathwassimulatedusing NS2.
60
Exp# 10 CRCErrorDetection
Date:
Aim
TodetectwhetherthegivendataiscorruptedornotusingCRCmethod.
Algorithm
1. Readnumberofdatabits.
2. Readthedatabit-by-bit
3. Readnumberofdivisorbits
4. Enterthedivisorbit-by-bit
5. Appendzeroestothemessage
6. GenerateremainderbyusingXORdivision
7. SubtractremainderfrommessageusingXOR
8. DisplaytheCRCcodeword
9. Accepttransmittedmessageasreceiversidedata
10. PeroformpolynomialdivisionusingXOR
11. Ifremainderiszerothendisplay“Noerror”elsedisplay“Error”
12. Stop
61
Program
import java.io.*;
class crc_gen
{
publicstaticvoidmain(Stringargs[])throwsIOException
{
BufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[]crc;
intdata_bits,divisor_bits,tot_length;
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=newint[tot_length];
/* CRCGENERATION */
for(int i=0;i<data.length;i++)
div[i]=data[i];
62
rem=divide(div,divisor,rem);
for(inti=0;i<div.length;i++)//appenddividend&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]);
/* ERRORDETECTION */
System.out.println();
System.out.println("EnterCRCcodeof"+tot_length
+"bits:");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
staticint[]divide(intdiv[],intdivisor[],intrem[])
{
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;
}
returnrem;
63
}
}
Output
$javaccrc_gen.java
$java crc_gen
Enter numberofdata bits:
8
Enter databits:
1
0
0
1
1
0
1
0
Enter no. of bits in divisor:
4
Enter Divisorbits:
1
1
0
1
Dividend(afterappending 0's): 10011010000
CRC code :
10011010101
EnterCRCcodeof11bits :
1
0
0
1
1
0
1
0
1
0
1
NoError
Result
Thuserrordetectionisdoneusingcyclicredundancycheckmethod.
64