Professional Documents
Culture Documents
CS8581 - Computer Networks Lab (PTR@9119) Manual
CS8581 - Computer Networks Lab (PTR@9119) Manual
CS8581 - Computer Networks Lab (PTR@9119) Manual
LAB MANUAL
Regulation : 2017
Branch : B.E., (CSE)
Year & Semester : III Year / V Semester
AFFILIATED INSTITUTIONS
REGULATIONS – 2017
CHOICE BASED CREDIT SYSTEM
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).
TOTAL : 60 PERIODS
Aim :
To Learn to use commands like netstat, ipconfig, nslookup and traceroute. Capture
ping and traceroute PDUs using a network protocol analyzer and examine them.
Parameters
Used without
displays active TCP connections.
parameters
Shows connections for the protocol specified by proto; proto may be any
of: TCP, UDP, TCPv6, or UDPv6. If used with the -s option to display
-p proto
per-protocol statistics, proto may be any of: IP, IPv6, ICMP, ICMPv6,
TCP, TCPv6, UDP, or UDPv6.
General Syntax
> ipconfig [/allcompartments] [/all] [/renew [<Adapter>]]
[/release [Adapter]] [/renew6 [<Adapter>]] [/release6
[<Adapter>]] [/flushdns] [/displaydns][/registerdns]
[/showclassid <Adapter] [/setclassid <Adapter> [<ClassID>]]
Parameters
Displays the full TCP/IP configuration for all adapters. Adapters can
/all represent physical interfaces, such as installed network adapters, or
logical interfaces, such as dial-up connections.
/allcompartments Displays the full TCP/IP configuration for all compartments.
Flushes and resets the contents of the DNS client resolver cache.
During DNS troubleshooting, you can use this procedure to discard
/flushdns
negative cache entries from the cache, as well as any other entries
that have been added dynamically.
Active Connections
Windows IP Configuration
Windows IP Configuration
Host Name . . . . . . . . . . . . : PTR-PC
Primary Dns Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Hybrid
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
C:\Users\PTR-PC>ipconfig /displaydns
Windows IP Configuration
1.0.0.127.in-addr.arpa
----------------------------------------
Record Name . . . . . : 1.0.0.127.in-addr.arpa.
Record Type . . . . . : 12
Time To Live . . . . : 86400
Data Length . . . . . : 8
Section . . . . . . . : Answer
PTR Record . . . . . : localhost
123.37.1.23.in-addr.arpa
----------------------------------------
Record Name . . . . . : 123.37.1.23.in-addr.arpa
Record Type . . . . . : 12
Time To Live . . . . : 25681
Data Length . . . . . : 8
Section . . . . . . . : Answer
PTR Record . . . . . : a23-1-37-123.deploy.static.akamaitechnologies.com
localhost
----------------------------------------
Record Name . . . . . : localhost
Record Type . . . . . : 1
Time To Live . . . . : 1200
Data Length . . . . . : 4
Section . . . . . . . : Question
A (Host) Record . . . : 127.0.0.1
localhost
----------------------------------------
Record Name . . . . . : localhost
Record Type . . . . . : 28
Time To Live . . . . : 1200
Data Length . . . . . : 16
Section . . . . . . . : Question
AAAA Record . . . . . : ::1
relay-1db3655a.net.anydesk.com
----------------------------------------
Record Name . . . . . : relay-1db3655a.net.anydesk.com
Record Type . . . . . : 1
Time To Live . . . . : 78432
Data Length . . . . . : 4
Section . . . . . . . : Answer
A (Host) Record . . . : 54.36.108.171
[option]
C:\Users\PTR-PC>nslookup www.ptrcet.org
Server: UnKnown
Address: 192.168.43.1
Non-authoritative answer:
Name: ptrcet.org
Address: 208.91.199.125
Aliases: www.ptrcet.org
C:\Users\PTR-PC>nslookup 208.91.199.125
Server: UnKnown
Address: 192.168.43.1
Name: bh-9.webhostbox.net
Address: 208.91.199.125
Non-authoritative answer:
ptrcet.org
primary name server = ns1.elysiumhosting.com
responsible mail addr = ka.sundaresh.gmail.com
serial = 2019090500
refresh = 3600 (1 hour)
retry = 7200 (2 hours)
expire = 1209600 (14 days)
default TTL = 86400 (1 day)
Non-authoritative answer:
ptrcet.org nameserver = ns1.elysiumhosting.com
[option]
[option]
This option prevents tracert from resolving IP_addresses to
-d
hostnames, often resulting in much faster results.
Result :
C:\Users\PTR-PC>ping www.ptrcet.org
C:\Users\PTR-PC>tracert www.ptrcet.org
1 5 ms 1 ms 1 ms 192.168.43.1
3 96 ms 59 ms 43 ms 10.40.14.125
4 88 ms 48 ms 66 ms 10.0.66.157
Trace complete.
Aim :
To write a java program for HTTP web client program to Download a Web page
using TCP Sockets.
Algorithm :
1. Create a URL object and pass URL as string to download the web page.
URL url=new URL(pass url of webpage we want to download)
2. Create Buffered Reader object and pass openStream(). Method of URL in Input
Stream object.
3. Create a string object to read each line one by one from stream.
4. Write each line in html file where webpage will be downloaded.
5. Close all objects.
6. Catch exceptions if url failed to download.
Program :
WebClient.java
import java.io.*;
import java.net.*;
public class WebClient
{
public static void main(String args[])throws Exception
{
URL url=new URL("http://www.ptrcet.org");
BufferedReader reader=new BufferedReader(new
InputStreamReader(url.openStream()));
BufferedWriter writer=new BufferedWriter(new
FileWriter("ptrorg.php"));
String line;
while((line=reader.readLine())!=null)
{
writer.write(line);
writer.newLine();
}
System.out.println(".------------------.");
System.out.println("| File Downloaded. |");
System.out.println(".------------------.");
reader.close();
writer.close();
}
}
Result :
Output :
C:\Users\PTR-PC\Desktop\Computer Networks\WebClient>javac
WebClient.java
}
};
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script> <script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
document.onkeydown = function(e) {
if (e.ctrlKey &&
(e.keyCode === 67 ||
e.keyCode === 86 ||
e.keyCode === 85 ||
e.keyCode === 117)) {
return false;
} else {
return true;
}
};
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);
function mischandler(){
return false;
}
function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;
</script>
<meta http-equiv="Refresh" content="0; url=ptrorg.php" ">
</head>
<body>
</body>
</html>
Aim :
To write a java program for applications using TCP Sockets like Echo Client and
Echo Server.
Algorithm :
1. Start the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If our frames reach the server it will send ACK signal to client otherwise it will send
NACK signal to client.
6. Stop the program
Program :
EchoServer.java
//TCP Echo Client--tcpechoclient.java
import java.io.*;
import java.net.*;
public class EchoServer
{
public static void main(String args[]) throws Exception
{
try
{
ServerSocket sok =new ServerSocket(9999);
System.out.println(" Server is Ready To Receive a Message. ");
System.out.println(" Waiting ..... ");
Socket so=sok.accept();
if(so.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=so.getInputStream();
OutputStream ou=so.getOutputStream();
PrintWriter pr=new PrintWriter(ou);
BufferedReader buf=new BufferedReader(new InputStreamReader(in));
String str=buf.readLine();
System.out.println(" Message Received From Client : " + str);
System.out.println(" This Message is Forwarded To Client. ");
CS8581 – NETWORKS LABORATORY 18
https://www.ptrcet.org Department of Computer Science and Engineering
pr.println(str);
pr.flush();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
EchoClient.java
//TCP Echo Client--tcpechoclient.java
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args)throws Exception
{
try
{
Socket sok = new Socket("localhost",9999);
if(sok.isConnected()==true)
System.out.println(" Server socket is connected Successfully.");
InputStream in=sok.getInputStream();
OutputStream out=sok.getOutputStream();
PrintWriter w = new PrintWriter(out);
BufferedReader br1 = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
String str1,str2;
System.out.println(" Enter the Message : ");
str1=br1.readLine();
w.println(str1);
w.flush();
System.out.println(" Message Send Successfully");
str2=br2.readLine();
System.out.println(" Message From Server : "+str2);
}
catch(Exception e)
{
System.out.println("Error : "+e.getMessage());
}
}
}
Result :
Output : (First run the Server_Program and then run Client_Program)
(EchoServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>javac EchoServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>java EchoServer
Server is Ready To Receive a Message.
Waiting .....
Client Socket is Connected Succecfully.
Message Received From Client : Welcome to PTRCET
This Message is Forwarded To Client.
(EchoClient.java)
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>javac EchoClient.java
C:\Users\PTR-PC\Desktop\Computer Networks\Echo>java EchoClient
Server socket is connected Successfully.
Enter the Message :
Welcome to PTRCET
Message Send Successfully
Message From Server : Welcome to PTRCET
Aim :
To write a java program implement a CHAT application, where the Client establishes
a connection with the server. The Client and Server can send as well as receive messages.
Both the Client and Server exchange messages.
Algorithm :
Server Client
1. Start the Program and create server 1. Start the Program and create a client
and client sockets. socket that connects to the required
2. Use input Streams to get message host and port.
from user. 2. Use input Streams to read message
3. Use output Streams to Send message given by server and print it.
to the Client. 3. Use input Streams; get the message
4. Wait for Client to display this from user to be given to the server..
message and write a new one to be 4. Use output Streams to write message
displayed by the server. to the server.
5. Display message given at Client 5. Stop the program
using input Streams read from
socket.
6. Stop the program.
Program :
ServerChat.java
import java.net.*;
import java.io.*;
public class ServerChat
{
public static void main( String args[]) throws Exception
{
ServerSocket srs = new ServerSocket(1234);
System.out.println("Server is running...");
Socket ss=srs.accept();
System.out.println("connection establised\n");
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(ss.getInputStream()));
DataOutputStream dos = new
DataOutputStream(ss.getOutputStream());
while(true)
{
//System.out.println("server repeat as long as client not send
null");
String s2,s3;
while((s2=br.readLine())!=null)
{
System.out.println("Client said : "+s2);
System.out.println("\nEnter text ");
s3 = kb.readLine();
//System.out.println("Answer send to client machine");
dos.writeBytes(s3+"\n");
}
System.out.println("Terminated..");
ss.close();
srs.close();
dos.close();
kb.close();
System.exit(0);
}
}
}
ClientChat.java
import java.net.*;
import java.io.*;
public class ClientChat
{
public static void main( String args[]) throws Exception
{
Socket cs = new Socket("localhost",1234);
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
DataOutputStream dos = new
DataOutputStream(cs.getOutputStream());
System.out.println("\nEnter text..");
System.out.println(" if Client want to 'quit' type ==>exit");
String s1,s4=null;
while(!(s1=kb.readLine()).equals("exit"))
{
Result :
(ServerChat.java)
CS8581 – NETWORKS LABORATORY 23
https://www.ptrcet.org Department of Computer Science and Engineering
Client said : OK
Enter text
Bye
Terminated..
(ClientChat.java)
C:\Users\PTR-PC\Desktop\Computer Networks\CHAT>javac ClientChat.java
C:\Users\PTR-PC\Desktop\Computer Networks\CHAT>java ClientChat
Enter text..
if Client want to 'quit' type ==>exit
Welcome to PTRCET
Server said : Welcome
Enter text
What do you feel about Network Lab..??
Server said : It is very interesting to learn
Enter text
OK
Server said : Bye
Enter text
exit
Terminated..
Aim :
To write a java program for File Transfer using TCP Sockets.
Algorithm :
Server Client
1. Import java packages and create 1. Import java packages and create
class file server. class file server.
2. Create a new server socket and bind 2. Create a new server socket and bind
it to the port. it to the port.
3. Accept the Client connection. 3. Now Connection is established.
4. Get the file name and stored into the 4. The object of a BufferedReader class
BufferedReader. is used for storing data content which
5. Create a new object class file and has been retrieved from socket
readLine. object.
6. If file exists then FileReader read the 5. The content of file is displayed in the
content until EOF is reached. client window and the Connection is
7. Stop the program. closed.
6. Stop the program
Program :
FileServer.java
import java.io.*;
import java.net.*;
public class FileServer extends Thread
{
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 100;
@Override
public void run()
{
try {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server is Ready to Transfer...!");
System.out.println("Waiting...\n");
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception
{
ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new
ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
// 1. Read file name.
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(o.toString());
} else {
throwException("Something is wrong");
}
// 2. Read file to the end.
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[])o;
// 3. Write data to output file.
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println(" .-----------------------.");
System.out.println(" | File transfer success |");
System.out.println(" .-----------------------.");
fos.close();
ois.close();
oos.close();
System.exit(0);
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new FileServer().start();
}
}
FileClient.java
import java.io.*;
import java.util.*;
import java.lang.*;
import java.net.*;
public class FileClient
{
public static void main(String[] args) throws Exception
{
String fileName = null;
System.out.println("Connection Established..!\n");
try {
fileName = args[0];
} catch (Exception e)
{
System.out.println("Enter the name of the file :");
Scanner scanner = new Scanner(System.in);
String file_name = scanner.nextLine();
File file = new File(file_name);
Socket socket = new Socket("localhost", 3332);
ObjectInputStream ois = new
ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new
ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[FileServer.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
System.exit(0);
}
}
}
Result :
(FileServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>javac
FileServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>java
FileServer
Server is Ready to Transfer...!
Waiting
.-----------------------.
| File transfer success |
.-----------------------.
(FileClient.java)
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>javac
FileClient.java
C:\Users\PTR-PC\Desktop\Computer Networks\FileTransfer>java
FileClient
Enter the name of the file :
C:\Users\PTR-PC\Desktop\Applications using TCP sockets like Chat.pdf
(Now, the corresponding file store in the location of where the server program is stored.)
Aim :
To write a java program for Simulating DNS using UDP Sockets.
Algorithm :
Server Client
Program :
UDPdnsServer.java
// 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 = {"ptrcet.org","yahoo.com",
"gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"208.91.199.125","68.180.206.184",
"209.85.148.19","80.168.92.140","69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true){
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new
DatagramPacket(senddata,senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}
UDPdnsClient.java
//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;
Result :
(UDPdnsServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>javac
UDPdnsServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>java UDPdnsServer
Press Ctrl + C to Quit
Request for host ptrcet.org
Request for host facebook.com
Request for host youtube.com.com
(UDPdnsClient.java)
C:\Users\PTR-PC\Desktop\Computer Networks\UDP_DNS>javac
UDPdnsClient.java
Aim :
To write a java program for Simulating Address Resolution Protocol (ARP) using
TCP Sockets.
Algorithm :
Server Client
Program :
ARPServer.java
import java.io.*;
import java.net.*;
import java.util.*;
import java.lang.*;
class ARPServer
{
public static void main(String args[])
{
System.out.println(" Send IP Address...\n Server is Waiting...\n");
try{
ServerSocket obj=new ServerSocket(1391);
Socket obj1=obj.accept();
while(true){
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1","192.168.1.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA","6E:AD:9D:F5","not
found"};
for(int i=0;i<ip.length;i++){
if(str.equals(ip[i])){
dout.writeBytes(mac[i]+'\n');
System.out.println(" .******************************************.");
System.out.println(" |Successfully Transferred PhysiCAl ADDreSS |");
System.out.println(" .******************************************.");
break;
}
}
dout.writeBytes(mac[3]+'\n');
System.out.println(" .________________.");
System.out.println(" |===INVALID IP===|");
System.out.println(" .________________.");
obj.close();
}
}
catch(Exception e){}
}
}
ARPClient.java
import java.io.*;
import java.net.*;
import java.util.*;
class ARPClient
{
public static void main(String args[])
{
try{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",1391);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String
str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e){}
}
}
Result :
Sample Output 1 : (First run the Server_Program and then run Client_Program)
(ARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\ARP>javac ARPServer.java
C:\Users\PTR-PC\Desktop\Computer Networks\ARP>java ARPServer
Send IP Address...
Server is Waiting...
.******************************************.
|Successfully Transferred PhysiCAl ADDreSS |
.******************************************.
(ARPClient.java)
Sample Output 2 : (First run the Server_Program and then run Client_Program)
(ARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\ARP>java ARPServer
Send IP Address...
Server is Waiting...
.________________.
|===INVALID IP===|
.________________.
(ARPClient.java)
Aim :
To write a java program for Simulating Reverse Address Resolution Protocol (RARP)
using UDP Sockets.
Algorithm :
Server Client
Program :
RARPServer.java
import java.io.*;
import java.net.*;
import java.util.*;
class RARPServer
{
public static void main(String args[])
{
try{
DatagramSocket server=new DatagramSocket(1309);
while(true){
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1","192.168.1.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA","6E:AD:9D:F5"};
for(int i=0;i<ip.length;i++){
if(s.equals(mac[i])){
CS8581 – NETWORKS LABORATORY 36
https://www.ptrcet.org Department of Computer Science and Engineering
sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
System.out.println("\n .************************************.");
System.out.println(" |Successfully Transferred IP ADDreSS |");
System.out.println(" .************************************.");
break;
}
}
break;
}
}
catch(Exception e){}
}
}
RARPClient.java
import java.io.*;
import java.net.*;
import java.util.*;
class RARPClient
{
public static void main(String args[])
{
try{
DatagramSocket client=new DatagramSocket();
InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):");
String str=in.readLine();
sendbyte=str.getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("The Logical Address is(IP):"+s.trim());
client.close();
}
catch(Exception e){}
}
}
Result :
Sample Output 1 : (First run the Server_Program and then run Client_Program)
(RARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\RARP>javac RARPServer.java
.************************************.
|Successfully Transferred IP ADDreSS |
.************************************.
(ARPClient.java)
Sample Output 2 : (First run the Server_Program and then run Client_Program)
(RARPServer.java)
C:\Users\PTR-PC\Desktop\Computer Networks\RARP>javac RARPServer.java
(ARPClient.java)
Aim :
To study about NS2 simulator in detail.
Theory :
Network Simulator (Version 2), widely known as NS2, is simply an event driven
simulation tool that has proved useful in studying the dynamic nature of communication
networks. Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2. In general, NS2 provides users with a way of
specifying such network protocols and simulating their corresponding behaviors. Due to its
flexibility and modular nature, NS2 has gained constant popularity in the networking research
community since its birth in 1989. Ever since, several revolutions and revisions have marked
the growing maturity of the tool, thanks to substantial contributions from the players in the
field. Among these are the University of California and Cornell University who developed the
REAL network simulator,1 the foundation which NS is based on. Since 1995 the Defense
Advanced Research Projects Agency (DARPA) supported development of NS through the
Virtual Inter Network Testbed (VINT) project. Currently the National Science Foundation
(NSF) has joined the ride in development. Last but not the least, the group of Researchers and
developers in the community are constantly working to keep NS2 strong and versatile.
Concept Overview :
NS uses two languages because simulator has two different kinds of things it needs to
do. On one hand,detailed simulations of protocols requires a systems programming language
which can efficiently manipulate bytes, packet headers, and implement algorithms that run
over large data sets. For these tasks run-time speed is important and turn-around time (run
simulation, find bug, fix bug, recompile, re-run) is less important. On the other hand, a large
part of network research involves slightly varying parameters or configurations, or quickly
exploring a number of scenarios.
In these cases, iteration time (change the model and re-run) is more important. Since
configuration runs once (at the beginning of the simulation), run-time of this part of the task is
less important. ns meets both of these needs with two languages, C++ and OTcl.
Basic Architecture :
Figure 2.1 shows the basic architecture of NS2. NS2 provides users with an executable
command ns which takes on input argument, the name of a Tcl simulation scripting file. Users
are feeding the name of a Tcl simulation script (which sets up a simulation) as an input
argument of an NS2 executable command ns.
In most cases, a simulation trace file is created, and is used to plot graph and/or to create
animation. NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend) of the
simulation objects, the OTcl sets up simulation by assembling and configuring the objects as
well as scheduling discrete events (i.e., a frontend).
The C++ and the OTcl are linked together using TclCL. Mapped to a C++
object, variables in the OTcl domains are sometimes referred to as handles. Conceptually, a
handle (e.g., n as a Node handle) is just a string (e.g.,_o10) in the OTcl domain, and does not
contain any functionality. Instead, the functionality (e.g., receiving a packet) is defined in the
mapped C++ object (e.g., of class Connector). In the OTcl domain, a handle acts as a frontend
which interacts with users and other OTcl objects. It may defines its own procedures and variables
to facilitate the interaction. Note that the member procedures and variables in the OTcl domain are
called instance procedures (instprocs) and instance variables (instvars), respectively. Before
proceeding further, the readers are encouraged to learn C++ and OTcl languages. We refer the
readers to [14] for the detail of C++, while a brief tutorial of Tcl and OTcl tutorial are given in
Appendices A.1 and A.2, respectively.
NS2 provides a large number of built-in C++ objects. It is advisable to use these C++
objects to set up a simulation using a Tcl simulation script. However, advance users may find
these objects insufficient. They need to develop their own C++ objects, and use a OTcl
configuration interface to put together these objects. After simulation, NS2 outputs either text-
based or animation-based simulation results. To interpret these results graphically and
interactively, tools such as NAM (Network AniMator) and XGraph are used. To analyze a
particular behaviour of the network, users can extract a relevant subset of text-based data and
transform it to a more conceivable presentation.
TCL SCRIPTING :
Tcl is a general purpose scripting language. [Interpreter]
Tcl runs on most of the platforms such as Unix, Windows, and Mac.
The strength of Tcl is its simplicity.
It is not necessary to declare a data type for variable prior to the usage.
BASICS OF TCL :
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!} Hello, World!
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using ―open command:
#Open the Trace file
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
The above creates a dta trace file called out.tr and a nam visualization trace file called out.nam.
Within the tcl script, these files are not called explicitly by their names, but instead by pointers
that are declared above and called ―tracefile1 and ―namfile respectively. Remark that they
begins with a # symbol. The second line open the file ―out.tr to be used for writing, declared
with the letter ―w. The third line uses a simulator method called trace-all that have as
parameter the name of the file where the traces will go.
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command set sink [new Agent /TCPSink] Defines the behavior of the destination node
of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes.This can be
changed to another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them
with different colors in the visualization part. This is done by the command $tcp set fid_ 1 that
assigns to the TCP connection a flow identification of ―1.We shall later give the flow
identification of ―2‖ to the UDP connection.
Result :
Aim :
To study TCP / UDP performance using simulaton tool.
Features
• TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has
bright clue about whether the data packet is reached the destination or it needs to resend
it.
• TCP ensures that the data reaches intended destination in the same order it was sent.
• TCP is connection oriented. TCP requires that connection between two remote points
be established before sending actual data.
• TCP provides error-checking and recovery mechanism.
• TCP provides end-to-end communication.
• TCP provides flow control and quality of service.
• TCP operates in Client/Server point-to-point mode.
• TCP provides full duplex server, i.e. it can perform roles of both receiver and sender.
Header
The length of TCP header is minimum 20 bytes long and maximum 60 bytes.
• Source Port (16-bits) - It identifies source port of the application process on the
sending device.
• Destination Port (16-bits) - It identifies destination port of the application process on
the receiving device.
• Sequence Number (32-bits) - Sequence number of data bytes of a segment in a session.
• Acknowledgement Number (32-bits) - When ACK flag is set, this number contains
the next sequence number of the data byte expected and works as acknowledgement of
the previous data received.
• Data Offset (4-bits) - This field implies both, the size of TCP header (32-bit words)
and the offset of data in current packet in the whole TCP segment.
• Reserved (3-bits) - Reserved for future use and all are set zero by default.
• Flags (1-bit each) o NS - Nonce Sum bit is used by Explicit Congestion Notification
signaling process.
CWR - When a host receives packet with ECE bit set, it sets Congestion
Windows Reduced to acknowledge that ECE received.
ECE -It has two meanings:
If SYN bit is clear to 0, then ECE means that the IP packet has its CE
(congestion experience) bit set.
If SYN bit is set to 1, ECE means that the device is ECT capable.
URG - It indicates that Urgent Pointer field has significant data and
should be processed.
ACK - It indicates that Acknowledgement field has significance. If
ACK is cleared to 0, it indicates that packet does not contain any
acknowledgement.
PSH - When set, it is a request to the receiving station to PUSH data (as
soon as it comes) to the receiving application without buffering it. o RST - Reset
flag has the following features:
It is used to refuse an incoming connection.
It is used to reject a segment.
It is used to restart a connection.
SYN - This flag is used to set up a connection between hosts.
FIN - This flag is used to release a connection and no more data is
exchanged thereafter. Because packets with SYN and FIN flags have sequence
numbers, they are processed in correct order.
• Windows Size - This field is used for flow control between two stations and indicates
the amount of buffer (in bytes) the receiver has allocated for a segment, i.e. how much
data is the receiver expecting.
• Checksum - This field contains the checksum of Header, Data and Pseudo Headers.
• Urgent Pointer - It points to the urgent data byte if URG flag is set to 1.
• Options - It facilitates additional options which are not covered by the regular header.
Option field is always described in 32-bit words. If this field contains data less than 32-
bit, padding is used to cover the remaining bits to reach 32-bit boundary.
Addressing
TCP communication between two remote hosts is done by means of port numbers (TSAPs).
Ports numbers can range from 0 – 65535 which are divided as:
System Ports (0 – 1023)
User Ports (1024 – 49151)
Private Dynamic Ports (49152 – 65535)
Connection Management
TCP communication works in Server/Client model. The client initiates the connection and the
server either accepts or rejects it. Three-way handshaking is used for connection management.
Establishment
Client initiates the connection and sends the segment with a Sequence number. Server
acknowledges it back with its own Sequence number and ACK of client’s segment which is
one more than client’s Sequence number. Client after receiving ACK of its segment sends an
acknowledgement of Server’s response.
Release
Either of server and client can send TCP segment with FIN flag set to 1. When the receiving
end responds it back by ACKnowledging FIN, that direction of TCP communication is closed
and connection is released.
Bandwidth Management
TCP uses the concept of window size to accommodate the need of Bandwidth management.
Window size tells the sender at the remote end, the number of data byte segments the receiver
at this end can receive. TCP uses slow start phase by using window size 1 and increases the
window size exponentially after each successful communication.
For example, the client uses windows size 2 and sends 2 bytes of data. When the
acknowledgement of this segment received the windows size is doubled to 4 and next sent the
segment sent will be 4 data bytes long. When the acknowledgement of 4-byte data segment is
received, the client sets windows size to 8 and so on.
If an acknowledgement is missed, i.e. data lost in transit network or it received NACK, then
the window size is reduced to half and slow start phase starts again.
If the sequence number of a segment recently received does not match with the
sequence number the receiver was expecting, then it is discarded and NACK is sent back. If
two segments arrive with the same sequence number, the TCP timestamp value is compared
to make a decision.
Multiplexing
The technique to combine two or more data streams in one session is called
Multiplexing. When a TCP client initializes a connection with Server, it always refers to a
well-defined port number which indicates the application process. The client itself uses a
randomly generated port number from private port number pools.
This enables the client system to receive multiple connection over single virtual
connection. These virtual connections are not good for Servers if the timeout is too long.
Congestion Control
When large amount of data is fed to system which is not capable of handling it, congestion
occurs. TCP controls congestion by means of Window mechanism. TCP sets a window size
telling the other end how much data segment to send. TCP may use three algorithms for
congestion control:
Additive increase, Multiplicative Decrease
Slow Start
Timeout React
Timer Management
TCP uses different types of timer to control and management various tasks:
CS8581 – NETWORKS LABORATORY 47
https://www.ptrcet.org Department of Computer Science and Engineering
Keep-alive timer:
This timer is used to check the integrity and validity of a connection.
When keep-alive time expires, the host sends a probe to check if the connection still
exists.
Retransmission timer:
This timer maintains stateful session of data sent.
If the acknowledgement of sent data does not receive within the Retransmission time,
the data segment is sent again.
Persist timer:
TCP session can be paused by either host by sending Window Size 0.
To resume the session a host needs to send Window Size with some larger value.
If this segment never reaches the other end, both ends may wait for each other for
infinite time.
When the Persist timer expires, the host re-sends its window size to let the other end
know.
Persist Timer helps avoid deadlocks in communication.
Timed-Wait:
After releasing a connection, either of the hosts waits for a Timed-Wait time to
terminate the connection completely.
This is in order to make sure that the other end has received the acknowledgement of
its connection termination request.
Timed-out can be a maximum of 240 seconds (4 minutes).
Crash Recovery
TCP is very reliable protocol. It provides sequence number to each of byte sent in segment. It
provides the feedback mechanism i.e. when a host receives a packet, it is bound to ACK that
packet having the next sequence number expected (if it is not the last segment).
When a TCP Server crashes mid-way communication and re-starts its process it sends TPDU
broadcast to all its hosts. The hosts can then send the last data segment which was never
unacknowledged and carry onwards.
Features
UDP is used when acknowledgement of data does not hold any significance. UDP is
good protocol for data flowing in one direction.
UDP is simple and suitable for query based communications.
UDP is not connection oriented.
UDP does not provide congestion control mechanism.
UDP does not guarantee ordered delivery of data.
UDP is stateless.
UDP is suitable protocol for streaming applications such as VoIP, multimedia
streaming.
UDP Header
UDP header is as simple as its function.
Destination Port - This 16 bits information, is used identify application level service
on destination machine.
Length - Length field specifies the entire length of UDP packet (including header). It
is 16bits field and minimum value is 8-byte, i.e. the size of UDP header itself.
Checksum - This field stores the checksum value generated by the sender before
sending. IPv4 has this field as optional so when checksum field does not contain any
value it is made 0 and all its bits are set to zero.
UDP application
Here are few applications where UDP is used to transmit data:
Domain Name Services
Simple Network Management Protocol
Trivial File Transfer Protocol
Routing Information Protocol
Kerberos
Result :
Aim :
To simulate and study the Distance Vector routing algorithm using simulation.
Software Required :
NS-2
THEORY:
Distance Vector Routing is one of the routing algorithm in a Wide Area Network for
computing shortest path between source and destination. The Router is one main devices used
in a wide area network. The main task of the router is Routing. It forms the routing table and
delivers the packets depending upon the routes in the tableeither directly or via an
intermediate devices.
Each router initially has information about its all neighbors. Then this information will
be shared among nodes.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute
nam on trace file
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose distance vector routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.
Program :
$ns rtproto DV
$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)
$ns at 45 "finish"
$ns run
Result :
Output :
Aim :
To simulate and study the Link State routing algorithm using simulation.
Software Required :
NS-2
Theory :
In link state routing, each router shares its knowledge of its neighborhood with every other
router in the internet work.
(i) Knowledge about Neighborhood: Instead of sending its entire routing table a
router sends info about its neighborhood only.
(ii) To all Routers: each router sends this information to every other router on the
internet work not just to its neighbor. It does so by a process called flooding.
(iii) Information sharing when there is a change: Each router sends out information
about the neighbors when there is change.
Procedure :
The Dijkstra algorithm follows four steps to discover what is called the shortest path
tree (routing table) for each router. The algorithm begins to build the tree by identifying its
roots. The root router’s trees the router itself. The algorithm then attaches all nodes that can
be reached from the root. The algorithm compares the tree’s temporary arcs and identifies the
arc with the lowest cumulative cost. This arc and the node to which it connects are now a
permanent part of the shortest path tree. The algorithm examines the database and identifies
every node that can be reached from its chosen node. These nodes and their arcs are added
temporarily to the tree.
The last two steps are repeated until every node in the network has become a permanent
part of the tree.
Algorithm :
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and
execute nam on trace file.
4. Create n number of nodes using for loop
Program :
$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)
$ns at 45 "finish"
$ns run
Result :
Output :
Aim :
To create scenario and study the performance of CSMA / CA and CSMA / CD protocol
through simulation.
Software Required :
NS-2
Theory :
Ethernet is a LAN (Local area Network) protocol operating at the MAC (Medium
Access Control) layer. Ethernet has been standardized as per IEEE 802.3. The underlying
protocol in Ethernet is known as the CSMA / CD – Carrier Sense Multiple Access / Collision
Detection. The working of the Ethernet protocol is as explained below, A node which has data
to transmit senses the channel. If the channel is idle then, the data is transmitted. If the channel
is busy then, the station defers transmission until the channel is sensed to be idle and then
immediately transmitted. If more than one node starts data transmission at the same time, the
data collides. This collision is heard by the transmitting nodes which enter into contention
phase. The contending nodes resolve contention using an algorithm called Truncated binary
exponential back off.
Algorithm :
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute
nam on trace file.
4. Create six nodes that forms a network numbered from 0 to 5
5. Create duplex links between the nodes and add Orientation to the nodes for setting a
LAN topology
6. Setup TCP Connection between n(0) and n(4)
7. Apply FTP Traffic over TCP
8. Setup UDP Connection between n(1) and n(5)
9. Apply CBR Traffic over UDP.
10. Apply CSMA/CA and CSMA/CD mechanisms and study their performance
11. Schedule events and run the program.
Program :
CSMA / CA
CSMA / CD
Result :
Aim :
To write a java program to find CRC of a given number.
Theory:
The upper layers work on some generalized view of network architecture and are not
aware of actual hardware data processing. Hence, the upper layers expect error-free
transmission between the systems. Most of the applications would not function expectedly if
they receive erroneous data. Applications such as voice and video may not be that affected
and with some errors they may still function well. Data-link layer uses some error control
mechanism to ensure that frames (data bit streams) are transmitted with certain level of
accuracy. But to understand how errors is controlled, it is essential to know what types of
errors may occur. CRC is a different approach to detect if the received frame contains valid
data. This technique involves binary division of the data bits being sent. The divisor is
generated using polynomials. The sender performs a division operation on the bits being sent
and calculates the remainder. Before sending the actual bits, the sender adds the remainder at
the end of the actual bits. Actual data bits plus the remainder is called a codeword. The sender
transmits data bits as codewords.
Algorithm :
Program :
CS8581 – NETWORKS LABORATORY 65
https://www.ptrcet.org Department of Computer Science and Engineering
import java.io.*;
import java.util.*;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
//Input Data Stream
System.out.println("Enter Data Stream :");
String datastream=sc.nextLine();
System.out.println("Enter generator :");
String generator=sc.nextLine();
int data[]=new int[datastream.length() + generator.length() -
1];
int divisor[]=new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i]=Integer.parseInt(datastream.charAt(i)+"");
for(int i=0;i<generator.length();i++)
divisor[i]=Integer.parseInt(generator.charAt(i)+"");
//Calculation of CRC
for(int i=0;i<datastream.length();i++)
{
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j]^=divisor[j];
}
//Display CRC
System.out.println("The CRC Code is :");
for(int i=0;i<datastream.length();i++)
data[i]=Integer.parseInt(datastream.charAt(i)+"");
for(int i=0;i<data.length;i++)
System.out.print(data[i]);
System.out.println();
for(int i=0;i<generator.length();i++)
divisor[i]=Integer.parseInt(generator.charAt(i)+"");
//Calculation of Remainder
for(int i=0;i<datastream.length();i++)
{
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j]^=divisor[j];
}
if(valid==true)
System.out.println("Data stream is valid");
else
System.out.println("Data stream is invalid. CRC error
occured...!");
}
}
Result :
Sample Output 1 :
Sample Output 2 :