CS8581 Networks Lab Manual (R2017)
CS8581 Networks Lab Manual (R2017)
D ENGINEERING COLLEGE
R.S.M. NAGAR, KAVARAIPETTAI – 601206
LABORATORY MANUAL
CS8581
NETWORKS LABORATORY
V Semester (R-2017)
OUTCOMES
Upon Completion of the course, the students will be able to:
· Implement various protocols using TCP and UDP.
· Compare the performance of different transport layer protocols.
· Use simulation tools to analyze the performance of various network protocols.
· Analyze various routing algorithms.
· Implement error correction codes.
GUI based tool called Wireshark (Network Protocol Analyzier) that reads tcpdump pcap format files.
Ste
p 3 -> First determines the ID of the Network Interface Card (NIC). The following command lists the set of
NICs: windump -D
Wh
ere :
-i is the interface no (i.e 1)
-q is quit mode
-w – Write – to write the capture logs
-r – Read – to see capture logs on console window
path where you want to save the capture file.
Now change the file name extension with (.pcap ) and open with wireshark
3
CS8581- Networks Laboratory
2. netstat
• The netstat command, meaning network statistics, is a Command Prompt command used to display
very detailed information about how our computer is communicating with other computers or network
devices.
• Specifically, the netstat command can show details about individual network connections, overall and
protocol-specific networking statistics, and much more, all of which could help troubleshoot certain kinds
of networking issues.
• Netstat provides statistics for the following:
o Proto - The name of the protocol (TCP or UDP).
Local Address - The IP address of the local computer and the port number being used. The name of the
local computer that corresponds to the IP address and the name of the port is shown unless the -n
parameter is specified. If the port is not yet established, the port number is shown as an asterisk (*).
o Foreign Address - The IP address and port number of the remote computer to which the socket is
connected. The names that corresponds to the IP address and the port are shown unless the -n parameter
is specified. If the port is not yet established, the port number is shown as an asterisk (*).
• Indicates the state of a TCP connection. The possible states are as follows:
State Description
Indicates that the server has received an ACK signal from the client and the
CLOSED connection is
closed
CLOSE_WAIT Indicates that the server has received the first FIN signal from the client and the
connection is in the process of being closed
ESTABLISHE Indicates that the server received the SYN signal from the client and the session
D is
established
FIN_WAIT_1 Indicates that the connection is still active but not currently being used
Indicates that the client just received acknowledgment of the first FIN signal from
FIN_WAIT_2 the
server
LAST_ACK Indicates that the server is in the process of sending its own FIN signal
SYN_RECEIV
ED Indicates that the server just received a SYN signal from the client
Syntax: netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]
Used
without Displays the IP address, subnet mask, and default gateway for all adapters.
parameters
Displays all active TCP connections and the TCP and UDP ports on which the
-a
computer is Listening
Displays Ethernet statistics, such as the number of bytes and packets sent and received.
-e
This parameter can be combined with -s.
Displays active TCP connections, however, addresses and port numbers are expressed
-n
numerically and no attempt is made to determine names.
Displays active TCP connections and includes the process ID (PID) for each
-o connection. You can find the application based on the PID on the Processes tab in
Windows Task Manager. This parameter can be combined with -a, -n, and -p.
Shows connections for the protocol specified by Protocol. In this case, the Protocol can
-p be tcp, udp, tcpv6, or udpv6. If this parameter is used with -s to display statistics by
protocol, Protocol can be tcp, udp, icmp, ip, tcpv6, udpv6, icmpv6, or ipv6.
Displays statistics by protocol. By default, statistics are shown for the TCP, UDP,
ICMP, and IP protocols. If the IPv6 protocol for Windows XP is installed, statistics are
-s
shown for the TCP over IPv6, UDP over IPv6, ICMPv6, and IPv6 protocols. The -p
parameter can be used to specify a set of protocols.
Displays the contents of the IP routing table. This is equivalent to the route print
-r
command.
Redisplays the selected information every Interval seconds. Press CTRL+C to stop the
Interval
redisplay. If this parameter is omitted, netstat prints the selected information only once.
/? - Displays help at the command prompt.
Examples
S.
Comma
N Description
nd
o
1 netstat -b To find out which programs are making connections with the outside world
2 netstat -f Shows all active TCP connections.
3 netstat -o Display Connection or Ports Process ID
The -a parameter lists all the computer’s connections and listening ports,
4 netstat -an while the - n parameter displays addresses and port numbers in numerical
format.
To find out for any received header error, received address error, discarded
5 netstat –s packet, etc. It will list out statistics from IPv4, IPv6, ICMPv4, ICMPv6, TCP,
UDP, etc.
6 netstat –r To display Route Table
7 netstat –e To view the status of all interface. This will display Received & Sent details.
8 netstat –f Display Fully Qualified Domain Name
10 netstat -a Display All TCP and UDP Connections with Listening Ports
3. ipconfig
• Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings.
• This command is most useful on computers that are configured to obtain an IP address
automatically.
• This enables users to determine which TCP/IP configuration values have been configured by DHCP,
Automatic Private IP Addressing (APIPA), or an alternate configuration.
• If the Adapter name contains any spaces, use quotation marks around the adapter name (that is,
"Adapter Name").
• For adapter names, ipconfig supports the use of the asterisk (*) wildcard character to specify either
adapters with names that begin with a specified string or adapters with names that contain a specified
string.
• For example, Local* matches all adapters that start with the string Local and *Con* matches all
adapters that contain the string Con.
Syntax
ipconfig [/all] [/renew [Adapter]] [/release [Adapter]] [/flushdns] [/displaydns] [/registerdns]
[/shwclassid Adapter] [/setclassid Adapter [ClassID]]
Parameters
Used without
displays the IP address, subnet mask, and default gateway for all adapters.
parameters
Renews DHCP configuration for all adapters (if an adapter is not specified) or
/renew for a
[Adapter]
specific adapter if the Adapter parameter is included.
Sends a DHCPRELEASE message to the DHCP server to release the current DHCP
/release configuration and discard the IP address configuration for either all adapters (if
[Adapter] an
adapter is not specified) or for a specific adapter if the Adapter parameter is
included.
/flushdns Flushes and resets the contents of the DNS client resolver cache.
6
CS8581- Networks Laboratory
Displays the contents of the DNS client resolver cache, which includes both
entries preloaded from the local Hosts file and any recently obtained resource
/displaydns records for name queries resolved by the computer.
Initiates manual dynamic registration for the DNS names and IP addresses that
/registerdns are configured at a computer.
Adapter Displays the DHCP class ID for a specified adapter. To see the DHCP
class ID for all adapters, use the asterisk (*) wildcard character in place of
Adapter. This parameter is available only on computers with adapters that are
/showclassid configured to obtain an IP address automatically.
Adapter [ClassID] Configures the DHCP class ID for a specified adapter. To set
the DHCP class ID for all adapters, use the asterisk (*) wildcard character in
/setclassid place of Adapter.
Examples:
ipconfig - To display the basic TCP/IP configuration for all adapters
ipconfig /all - To display the full TCP/IP configuration for all adapters
ipconfig /renew "Local Area - To renew a DHCP-assigned IP address configuration for only the
ipconfig /flushdns - To flush the DNS resolver cache when troubleshooting DNS name resolution problems
ipconfig /showclassid Local - To display the DHCP class ID for all adapters with names that start with
Local
ipconfig /setclassid "Local Area - To set the DHCP class ID for the Local Area Connection adapter to
4. nslookup
o nslookup is the name of a program that lets an Internet server administrator or any computer
user enter a host name (for example, "whatis.com") and find out the corresponding IP address.
7
CS8581- Networks Laboratory
o It will also do reverse name lookup and find the host name for an IP address you specify.
Description Command
5. Traceroute
• Traceroute is a network diagnostic tool that displays the route taken by packets across a
network and measures any transit delays.
tracert 64.13.192.208
Result
Thus a study on different networking commands were made successfully
8
CS8581- Networks Laboratory
Description
• Wireshark is a free and open source packet analyzer used for network troubleshooting and
analysis.
• The following activities will show us how to use Wireshark to capture and analyze
tracert/traceroute traffic.
• Tracing routes is accomplished through the use of Internet Control Message Protocol (ICMP)
Time Exceeded.
Preparation
To prepare for this activity:
• Start Windows.
• Log in if necessary.
• Install Wireshark.
Activity 1 - Capture Tracert Traffic
To capture ICMP tracert traffic:
• Start a Wireshark capture.
• Open a command prompt.
• Type tracert -d 8.8.8.8 and press Enter to trace the route to one of Google's public DNS
servers. The -d option prevents DNS name resolution, which in this case will improve performance
and reduce the amount of captured traffic.
• When the trace is complete, close the command prompt.
• Stop the Wireshark capture.
Activity 2 - Analyze Tracert Traffic
To analyze tracert traffic:
• Observe the traffic captured in the top Wireshark packet list pane. Look for traffic with
ICMP listed as the protocol. To view only ICMP traffic, type icmp (lower case) in the Filter box and
press Enter.
• Select the first ICMP packet, labeled Echo (ping) request.
• Observe the packet details in the middle Wireshark packet details pane.
9
CS8581- Networks Laboratory
RESULT
EX.NO:2 HTTP WEB CLIENT PROGRAM TO DOWNLOAD A WEB PAGE USING TCP SOCKETS
DATE:
AIM:
To write a HTTP web client program to download a web page using TCP sockets in python.
ALGORITHM
• Create socket
• Get server IP address from domain name
• Connect to server using IP address
• Send request to server
• Receive data (webpage)
PROGRAM
import socket
request = b"GET / HTTP/1.1\nHost: google.com\n\n"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("google.com", 80))
s.send(request) result =
s.recv(10000) while
(len(result) > 0):
print(result)
result = s.recv(10000)
11
CS8581- Networks Laboratory
Sample Output
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 13 Apr 2019 07:00:51 GMT
Expires: Mon, 13 May 2019 07:00:51 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Age: 10184
X-Cache: HIT from tg22819a
X-Cache-Lookup: HIT from tg22819a:3120
Via: 1.1 tg22819a (squid/3.5.20)
Connection: keep-alive
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY> <H1>301 Moved</H1>
RESULT
Thus the HTTP web client program to download a web page using TCP sockets was executed
and output was verified.
12
CS8581- Networks Laboratory
EX.NO. 3 (a) TCP SOCKET APPLICATION -ECHO CLIENT AND ECHO SERVER
DATE:
AIM
To write a Java program for ECHO using TCP Sockets
ALGORITHM
Client Side Programming
• Establish a Socket Connection
To connect to other machine we need a socket connection.
A socket connection means the two machines have information about each other’s network
location (IP Address) and TCP port.
The java.net.Socket class represents a Socket.
To open a socket: Socket socket = new Socket(“127.0.0.1”, 5000)
First argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where code
will run on single stand-alone machine).
Second argument – TCP Port. (Just a number representing which application to run on a
server. o For example, HTTP runs on port 80. Port number can be from 0 to 65535)
• Communication
To communicate over a socket connection, streams are used to both input and output the data.
• Closing the connection
1. The socket connection is closed explicitly once the message to server is sent.
In the program, Client keeps reading input from user and sends to the server until “Over” is
typed.
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
14
CS8581- Networks Laboratory
}}
Server Programming
• Establish a Socket Connection
o To write a server application two sockets are needed.
o A ServerSocket which waits for the client requests (when a client makes a new Socket())
o A plain old Socket socket to use for communication with the client.
• Communication
o getOutputStream() method is used to send the output through the socket.
• Close the Connection
o After finishing, it is important to close the connection by closing the socket as well as
input/output streams.
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with
port public Server(int
port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
} }
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}}
16
CS8581- Networks Laboratory
OUTPUT
Open two windows one for Server and another for Client
1. First run the Server application as , $ java Server Server started Waiting for a client …
2. Then run the Client application on another terminal as, $ java Client It will show – Connected and
the server accepts the client and shows, Client accepted
3. Then start typing messages in the Client window. Here is a sample input to the
Client Hello
I made my first socket connection Over
Which the Server simultaneously receives and shows, Hello
I made my first socket connection Over
Closing connection
Sending “Over” closes the connection between the Client and the Server just like said before.
RESULT
Thus the data from client to server is echoed using TCP connection
17
CS8581- Networks Laboratory
AIM
To write a java program to initiate a chat between client and server.
ALGORITHM
CLIENT
1. Start the program
2. Include necessary package in java
3. Create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accept the connection and to send the data from client to server.
6. The client communicates the server to send the end of the message
7. Stop the program.
SERVER
PROGRAM
TCPserver1.java
import java.net.*;
import java.io.*;
public class TCPserver1
{
public static void main(String arg[])
{
ServerSocket s=null;
String line;
DataInputStream is=null,is1=null;
PrintStream os=null;
Socket c=null;
try
{
s=new ServerSocket(9999);
}
catch(IOException e)
{
System.out.println(e);
18
CS8581- Networks Laboratory
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
is1=new DataInputStream(System.in);
os=new PrintStream(c.getOutputStream());
do
{
line=is.readLine();
System.out.println("Client:"+line);
System.out.println("Server:");
line=is1.readLine();
os.println(line);
}
while(line.equalsIgnoreCase("quit")==false);
is.close();
os.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
TCPclient1.java
import java.net.*;
import java.io.*;
public class TCPclient1
{
public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("10.0.200.36",9999);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
19
CS8581- Networks Laboratory
is1=new DataInputStream(c.getInputStream());
do
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}
while(line.equalsIgnoreCase("quit")==false);
is1.close();
os.close();
}
catch(IOException e)
{
System.out.println("Socket Closed!Message Passing is over");
}}
OUTPUT:
SERVER
C:\Program Files\Java\jdk1.5.0\bin>javac TCPserver1.java
Note: TCPserver1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPserver1
Client: Hai Server
Server:Hai Client
Client: How are you
Server:Fine
Client: quit
Server:quit
CLIENT
C:\Program Files\Java\jdk1.5.0\bin>javac TCPclient1.java
Note: TCPclient1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPclient1
Client:Hai Server
Server: Hai Client
Client:How are you
Server: Fine
Client:quit
Server: quit
RESULT
Thus the CHAT program was successfully executed.
20
CS8581- Networks Laboratory
AIM
To create a socket (TCP) between two computers and enable file transfer between them.
ALGORITHM
Server
1. Start the program.
2. Create a socket with address family AF_INET, type SOCK_STREAM and default protocol.
3. Initialize the socket and set its attributes assign any port number as desired.
4. Bind the server to the socket using bind() function.
5. Establish the listen queue using the listen function.
6. Wait for client program on request, establish a connection using accept function.
7. Repeat steps 8-10 until the server sends bye.
8. Read the message from the client using read() function. display the message.
9. If the client message is bye go to step 11.
10. Accept the server message and write it to client using write() function.
11. Close the connection.
12. Stop the program.
SERVER PROGRAM
TCPSERVER
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>
21
CS8581- Networks Laboratory
int main()
{
int cont,create_socket,new_socket,addrlen,fd;
int bufsize = 1024;
char *buffer = malloc(bufsize);
char fname[256];
struct sockaddr_in address;
if ((create_socket = socket(AF_INET,SOCK_STREAM,0)) > 0)
printf("The socket was created\n"); address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY; address.sin_port =
htons(8000);
if (bind(create_socket,(struct sockaddr*)&address,sizeof(address)) == 0)
printf("Binding Socket\n");
listen(create_socket,3);
addrlen = sizeof(struct sockaddr_in);
new_socket = accept(create_socket,(struct sockaddr*)&address,&addrlen); if
(new_socket > 0)
printf("The Client %s is Connected...\n",inet_ntoa(address.sin_addr));
recv(new_socket,fname, 255,0);
printf("A request for filename %s Received..\n", fname); if
((fd=open(fname, O_RDONLY))<0) {perror("File Open Failed");
exit(0);}
while((cont=read(fd, buffer, bufsize))>0)
{
send(new_socket,buffer,cont,0);
}
printf("Request Completed\n");
close(new_socket);
return close(create_socket);
}
CLIENT PROGRAM:
TCPCLIENT
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc,char *argv[])
{
int create_socket,cont;
22
CS8581- Networks Laboratory
inet_pton(AF_INET,argv[1],&address.sin_addr);
if (connect(create_socket,(struct sockaddr *) &address,
sizeof(address)) == 0)
printf("The connection was accepted with the server %s...\n",argv[1]);
printf("Enter The Filename to Request : "); scanf("%s",fname);
Output:
Server
[iiiitb031@kings ~]$ cc -o server tcpserver.c
[iiiitb031@kings ~]$ ./server 4235
The socket was created
Binding Socket
The Client 127.0.0.1 is Connected...
A request for filename tcps.c Received.
Request Completed
23
CS8581- Networks Laboratory
Client
[iiiitb031@kings ~]$ cc -o client tcpclient.c
[iiiitb031@kings ~]$ ./client 127.0.0.1 4235
The Socket was created
The connection was accepted with the server 127.0.0.1...
Enter The Filename to Request : hello.c
Request Accepted... Receiving File...
The contents of file are...
#include<stdio.h>
void main()
{printf(“\n hello world”);}
EOF
RESULT:
Thus the File Transfer Protocol using TCP was successfully executed.
24
CS8581- Networks Laboratory
Exp. No: 4
SIMULATION OF DNS USING UDP SOCKETS
Date:
AIM
To create a client server program to Domain Name System using the UDP protocol client server.
ALGORITHM
Server
Step1: Start the program.
Step2: Create the socket for the server.
Step3: Bind the socket to the port.
Step4: Listen for the incoming client connection.
Step5: Receive the IP address from the client to be resolved.
Step6: Get the domain name for the client.
Step7: Check the existence of the domain in the server.
Step8: If domain matches then send the corresponding address to the client.
Step9: Stop the program execution
Client
Step1: Start the Program.
Step2: Create the socket for the client.
Step3: Connect the socket to the Server.
Step4: Send the host name to the server to be resolved.
Step5: If the server corresponds then print the address and terminate the process
PROGRAM
UDPclient
import java .io.*;
import java.net.*;
classUDPclient
{
public static DatagramSocket ds;
public static intclientport=789,serverport=790;
public static void main(String args[])throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“server waiting”);
InetAddressia=InetAddress.getLocalHost();
while(true)
{
System.out.println(“Client:”);
String str=dis.readLine();
if(str.equals(“end”))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
25
CS8581- Networks Laboratory
UDP server
import java.io.*;
import java.net.*;
classUDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static intclientport=789,serverport=790;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(clientport);
System.out.println(“press ctrl+c to quit the program”);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
InetAddressia=InetAddress.getLocalHost();
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println(“Client:” + psx);
InetAddressib=InetAddress.getByName(psx);
System.out.println(“Server output:”+ib);
String str=dis.readLine();
if(str.equals(“end”))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
}
}
}
OUTPUT
UDPclient
D:\Program Files\Java\jdk1.6.0\bin>javac UDPclient.java
D:\Program Files\Java\jdk1.6.0\bin>java UDPclient
Server waiting
Client:www.yahoo.com
UDPserver
D:\Program Files\Java\jdk1.6.0\bin>javac UDPserver.java
D:\Program Files\Java\jdk1.6.0\bin>java UDPserver
Press ctrl+c to quit the program
Client:www.yahoo.com
Server output:www.yahoo.com/106.10.170.115
26
CS8581- Networks Laboratory
RESULT
Thus client server program to Domain Name System using the UDP protocol client server has been
executed and verified successfully.
27
CS8581- Networks Laboratory
Exp. No: 5A
SIMULATING ARP PROTOCOL USING JAVA
Date:
AIM
To stimulate ARP protocol using JAVA language.
ALGORITHM
Step 1: Import the net, input output, language, utility package s
Step 2: Use the method exec with the command “arp -a “ as parameter.
Step 3: Store the result of the ping command in input stream.
Step 4: Process the input stream and display the result.
Step 5: End the process.
PROGRAM
import java.net.*;
import java.io.*;
import java.lang.Object; // O Should be a capital
import java.util.*;
class arp
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("arp -a");
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String str,str1="",st1,st2;
while((str=br.readLine())!=null)
str1+=str+"\n";
StringTokenizer st=new StringTokenizer(str1,"\n");
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the IP ADDRESS");
st2=br1.readLine();
while(st.hasMoreTokens())
{
st1=st.nextToken();
if(st1.indexOf(st2)!=-1)
System.out.println(st1);
}
}
catch(Exception E)
{
E.printStackTrace();
}
}
}
OUTPUT
Enter the IP ADDRESS: 172.15.150.110
00-01-0C-33-1C-5D
RESULT
28
CS8581- Networks Laboratory
AIM
To stimulate RARP protocol using JAVA language.
ALGORITHM
Step 1: Import the net, input output, language, utility packages.
Step 2: Use the method exec with the command “arp -a “as parameter.
Step 3: Store the result of the ping command in input stream.
Step 4: Process the input stream and display the result.
Step 5: End the process.
PROGRAM
import java.net.*;
import java.io.*;
import java.lang.Object; // O Should be a capital
import java.util.*;
class rarp
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("arp -a");
BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
String str,str1="",st1,st2;
while((str=br.readLine())!=null)
str1+=str+"\n";
StringTokenizer st=new StringTokenizer(str1,"\n");
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the physical 48-bit ADDR ENTER THE PHYSICAL 48BIT ADDRESS ");
st2=br1.readLine();
while(st.hasMoreTokens())
{
st1=st.nextToken();
if(st1.indexOf(st2)!=-1)
System.out.println(st1);
}
}
catch(Exception E)
{
E.printStackTrace();
} } }
OUTPUT
ENTER THE PHYSICAL 48BIT ADDRESS: 00-01-0C-33-1C-5D
172.15.150.110
RESULT
Thus the RARP protocols are successfully completed.
29
CS8581- Networks Laboratory
Exp. No: 6
STUDY OF NETWORK SIMULATOR (NS)
Date:
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.
BASIC ARCHITECTURE
Figure 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 define 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
30
CS8581- Networks Laboratory
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 behavior of the network, users can extract a relevant subset of text-based data and transform it to a
more conceivable presentation.
CONCEPT OVERVIEW
NS uses two languages because simulator has two different kinds of things it needs to do. On one hand,
detailed simulations of protocols require 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.
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!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation
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.
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command
set ns [new Simulator]
Which is thus the first line in the tcl script. This line declares a new variable as using the set command, you can
call this variable as you wish, In general people declares it as ns because it is an instance of the Simulator class,
31
CS8581- Networks Laboratory
so an object the code[new Simulator] is indeed the installation of the class Simulator using the reserved word
new.
In order to have output files with data on the simulation (trace files) or files used for visualization (nam files),
we need to create the files using ―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.
Define a “finish‟ procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
}
Definition of a network of links and nodes
The way to define a node is
set n0 [$ns node]
Once we define several nodes, we can define the links that connect them. An example of a definition of a link
is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of propagation delay and
a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace ―duplex-link by ―simplex-link.
In ns, an output queue of a node is implemented as a part of each link whose input is that node. We should also
define the buffer capacity of the queue related to each link. An example would be:
#set Queue Size of link (n0-n2) to 20
$ns queue-limit $n0 $n2 20
FTP over TCP
TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created by the destination to
know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas. The type of agent
appears in the first line:
set tcp [new Agent/TCP]
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
RESULT
Thus the Network Simulator 2 is studied in detail.
33
CS8581- Networks Laboratory
OBJECTIVE
Generate Network Traffic in Simulation Mode and study the Functionality of the TCP and UDP Protocols
Background
This simulation activity is intended to provide a foundation for understanding the TCP and UDPin detail.
Simulation mode provides the ability to view the functionality of the different protocols. As data moves through
the network, it is broken down into smaller pieces and identified in some fashion so that the pieces can be put
back together. Each of these pieces is assigned a specific name (protocol data unit [PDU]) and associated with a
specific layer. Packet Tracer Simulation mode enables the user to view each of the protocols and the associated
PDU. The steps outlined below lead the user through the process of requesting services using various
applications available on a client PC.
This activity provides an opportunity to explore the functionality of the TCP and UDP protocols, multiplexing
and the function of port numbers in determining which local application requested the data or is sending the
data.
Step 1: Generate traffic to populate Address Resolution Protocol (ARP) tables.
Perform the following tasks task to reduce the amount of network traffic viewed in the simulation.
a. ClickMultiServer andclick the Desktop tab>Command Prompt.
b. Enter the ping 192.168.1.255 command. This will take a few seconds as every device on the network
responds to MultiServer.
c. Close the MultiServer window.
Step 2: Generate web (HTTP) traffic.
a. Switch to Simulation mode.
b. Click HTTP Client and click theDesktop tab>Web Browser.
34
CS8581- Networks Laboratory
c. In the URL field, enter 192.168.1.254and click Go. Envelopes (PDUs) will appear in the simulation
window.
d. Minimize, but do not close, the HTTP Client configuration window.
Step 3: Generate FTP traffic.
a. Click FTP Client and click theDesktop tab >Command Prompt.
b. Enter the ftp 192.168.1.254command.PDUs will appear in the simulation window.
c. Minimize, but do not close, the FTP Client configuration window.
Step 4: Generate DNS traffic.
a. Click DNS Client and click theDesktoptab>Command Prompt.
b. Enter the nslookupmultiserver.pt.ptucommand.A PDU will appear in the simulation window.
c. Minimize, but do not close, the DNS Client configuration window.
Step 5: Generate Emailtraffic.
a. Click E-Mail Clientand click theDesktop tab>E Mail tool.
b. ClickComposeand enter the following information:
1) To: [email protected]
2) Subject: Personalize the subject line
3) E-Mail Body: Personalize the Email
c. ClickSend.
d. Minimize, but do not close, the E-Mail Client configuration window.
Step 6: Verify that the traffic is generated and ready for simulation.
Every client computer should have PDUslisted in the Simulation Panel.
b. Click Capture/Forward. Hold your mouse above each PDU until you find one that originates from
HTTP Client. Clickthe PDU envelope to open it.
c. Click the Inbound PDU Details tab and scroll down to the last section. What is the section labeled?
TCP
Are these communications considered to be reliable?
YES.
d. Record the SRC PORT, DEST PORT, SEQUENCE NUM, and ACK NUM values. What is written in
the field to the left of theWINDOWfield?
1025 (could be different), 80,0,0 SYN.
e. Close the PDU and click Capture/Forward until a PDU returns to the HTTP Client with a checkmark.
f. Click the PDU envelope and select Inbound PDU Details. How are the port and sequence numbers
different than before?
SRC PORT and DEST PORT are flipped. SEQUENC NUM is still 0 but ACK num is 1.
SYN+ACK.
g. There is a second PDUof a different color, whichHTTP Client has prepared to send to MultiServer.
This is the beginning of the HTTP communication. Click this second PDU envelope and select
Outbound PDU Details.
h. What information is now listed in the TCP section? How are the port and sequence numbers different
from the previous two PDUs?
1025, 80 ,1 ,1. PSH+ACK The source and destination ports are reversed, and both sequence and
acknowledgement numbers are 1.
i. Click Back until the simulation is reset.
Step 3: Examine FTP traffic as the clients communicate with the server.
a. In the Simulation Panel, change Edit Filters to display onlyFTPand TCP.
b. Click Capture/Forward. Hold your cursor above each PDU until you find one that originates from FTP
Client. Click that PDU envelope to open it.
c. Click the Inbound PDU Details tab and scroll down to the last section. What is the section labeled?
TCP
Are these communications considered to be reliable?
YES
d. Record the SRC PORT, DEST PORT, SEQUENCE NUM, and ACK NUM values. What is written in
the field to the left of theWINDOWfield?
1025, 21, 0 ,0, SYN
e. Close the PDU and click Capture/Forward until a PDU returns to the FTP Client with a checkmark.
f. Click the PDU envelope and select Inbound PDU Details. How are the port and sequence numbers
different than before?
21,1025,0,1 SYN+ACK. The source and destination ports are reversed, and the acknowledgement
number is 1.
g. Click the OutboundPDU Details tab. How are the port and sequence numbers different from the
previous two results?
1025, 21, 1 ,1. ACK. The source and destination ports are reversed, and both sequence numbers
are 1.
h. Close the PDU and click Capture/Forward until a secondPDU returns to the FTP Client.The PDU is a
different color.
36
CS8581- Networks Laboratory
i. Open the PDU and select Inbound PDU Details. Scroll down past the TCP section. What is the
message from the server?
“Welcome to PT FTP server”
j. Click Back until the simulation is reset.
Step 4: Examine DNS traffic as the clients communicate with the server.
a. In the Simulation Panel, change Edit Filters to display onlyDNS and UDP.
b. Click the PDU envelope to open it.
c. Click the Inbound PDU Details tab and scroll down to the last section. What is the section labeled?
UDP
Are these communications considered to be reliable?No
d. Record the SRC PORT andDEST PORTvalues. Why is there no sequence and acknowledgement
number?
1025 and 53. Because UDP does not need to establish a reliable connection.
e. Close the PDU and click Capture/Forward until a PDU returns to the DNS Client with a checkmark.
f. Click the PDU envelope and select Inbound PDU Details. How are the port and sequence numbers
different than before?
53 and 1025. Src and dest ports are reversed.
g. What is the last section of the PDU called?
DNS ANSWER.
h. Click Back until the simulation is reset.
Step 5: Examine email traffic as the clients communicate with the server.
a. In the Simulation Panel, change Edit Filters to display only POP3, SMTPand TCP.
b. Click Capture/Forward. Hold your cursor above each PDU until you find one that originates from E-
mail Client. Clickthat PDUenvelope to open it.
c. Click the Inbound PDU Details tab and scroll down to the last section. What transport layer protocol
does email traffic use?
TCP.
Are these communications considered to be reliable?
Yes.
d. Record the SRC PORT, DEST PORT, SEQUENCE NUM, and ACK NUMvalues. What is written in
the field to the left of theWINDOW field?
1025,25,0,0,SYN
e. Close the PDU and click Capture/Forward until a PDU returns to the E-Mail Client with a
checkmark.
f. Click the PDU envelope and select Inbound PDU Details. How are the port and sequence numbers
different than before?
25,1025,0,1 SYN+ACK
g. Click the OutboundPDU Details tab. How are the port and sequence numbers different from the
previous two results?
1025,25,1,1 ACK.
h. There is a second PDU of a different color that HTTP Client has prepared to send to MultiServer. This
is the beginning of the email communication. Click this second PDU envelope and select Outbound
PDU Details.
i. How are the port and sequence numbers different from the previous two PDUs?
37
CS8581- Networks Laboratory
1025,25,1,1, PSH+ACK
j. What email protocol is associated with TCP port 25?What protocol is associated with TCP port 110?
SMTP,POP3
k. Click Back until the simulation is reset.
Step 6: Examine the use of port numbers from the server.
a. To see TCP active sessions, performthe following steps in quick succession:
1) Switch back to Realtimemode.
2) ClickMultiServerand click theDesktop tab>Command Prompt.
b. Enter the netstatcommand. What protocols are listed in the left column?TCP
What port numbers are being used by the server?
21
c. What states are the sessions in?
ESTABLISHED
d. Repeat the netstat command several times until you see only one session still ESTABLISHED.For
which service is this connection still open?FTP
Why doesn’t this session close like the other three? (Hint: Check the minimized clients)
The server is waiting for a password from the client.
RESULT
This simulation activity has provided a foundation for understanding the TCP and UDP in detail. Simulation
mode provided the ability to view the functionality of the different protocols. As data moves through the
network, it was broken down into smaller pieces and identified in some fashion so that the pieces can be put
back together. Each of these pieces is assigned a specific name (protocol data unit [PDU]) and associated with a
specific layer. Packet Tracer Simulation mode enabled the user to view each of the protocols and the associated
PDU.
38
CS8581- Networks Laboratory
AIM
To simulate and study the Distance Vector Routing algorithm – RIP using NS-2 simulation.
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 table-
either 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
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} {
39
CS8581- Networks Laboratory
RESULT
Thus the Distance vector Routing Algorithm was Simulated and studied.
41
CS8581- Networks Laboratory
Exp. No: 8B
SIMULATION OF LINK STATE ROUTING ALGORITHM
Date:
AIM
To simulate and study the link state routing algorithm using NS-2 simulation.
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.
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 Link state routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.
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
}
42
CS8581- Networks Laboratory
OUTPUT
RESULT
Thus the Link State Routing Algorithm was Simulated and studied.
44
CS8581- Networks Laboratory
AIM
To analyze the Performance evaluation of Routing protocols using Simulation tool.
PROCEDURE
1. Open Packet Tracer simulator
2. Take a HUB and few PCs for demonstration
3. Assign IP address to all the PCs with its subnet mask using the addressing table.
4. Do data transfer which always floods the network unlike switches
ADDRESSING TABLE
PC IP ADDRESS SUBNET PORT
MASK CONNECTED
PC0 10.10.10.1 255.0.0.0 PORT 0
PC1 10.10.10.2 255.0.0.0 PORT 1
PC2 10.10.10.3 255.0.0.0 PORT 2
PC3 10.10.10.4 255.0.0.0 PORT 3
PC4 10.10.10.5 255.0.0.0 PORT 4
RESULT
Performance evaluation of Routing protocols was analyzed using Simulation tool.
46
CS8581- Networks Laboratory
ALGORITHM
1. Open Turbo c++ software and type the program for error detection
2. Get the input in the form of bits.
3. Append 16 zeros as redundancy bits.
4. Divide the appended data using a divisor polynomial.
5. The resulting data should be transmitted to the receiver.
6. At the receiver the received data is entered.
7. The same process is repeated at the receiver.
8. If the remainder is zero there is no error otherwise there is some error in the received bits
9. Run the program.
C PROGRAM
#include<stdio.h>
char m[50],g[50],r[50],q[50],temp[50];
void caltrans(int);
void crc(int);
void calram();
void shiftl();
int main()
{
int n,i=0;
char ch,flag=0;
printf("Enter the frame bits:");
while((ch=getc(stdin))!='\n')
m[i++]=ch;
n=i;
for(i=0;i<16;i++)
m[n++]='0';
m[n]='\0';
printf("Message after appending 16 zeros:%s",m);
for(i=0;i<=16;i++)
g[i]='0';
g[0]=g[4]=g[11]=g[16]='1';g[17]='\0';
printf("\ngenerator:%s\n",g);
crc(n);
printf("\n\nquotient:%s",q);
caltrans(n);
printf("\ntransmitted frame:%s",m);
printf("\nEnter transmitted frame:");
scanf("\n%s",m);
47
CS8581- Networks Laboratory
printf("CRC checking\n");
crc(n);
printf("\n\nlast remainder:%s",r);
for(i=0;i<16;i++)
if(r[i]!='0')
flag=1;
else
continue;
if(flag==1)
printf("Error during transmission");
else
printf("\n\nReceived freme is correct");
}
void crc(int n)
{
int i,j;
for(i=0;i<n;i++)
temp[i]=m[i];
for(i=0;i<16;i++)
r[i]=m[i];
printf("\nintermediate remainder\n");
for(i=0;i<n-16;i++)
{
if(r[0]=='1')
{
q[i]='1';
calram();
}
else
{
q[i]='0';
shiftl();
}
r[16]=m[17+i];
r[17]='\0';
printf("\nremainder %d:%s",i+1,r);
for(j=0;j<=17;j++)
temp[j]=r[j];
}
q[n-16]='\0';
}
void calram()
{
int i,j;
for(i=1;i<=16;i++)
r[i-1]=((int)temp[i]-48)^((int)g[i]-48)+48;
}
48
CS8581- Networks Laboratory
void shiftl()
{
int i;
for(i=1;i<=16;i++)
r[i-1]=r[i];
}
void caltrans(int n)
{
int i,k=0;
for(i=n-16;i<n;i++)
m[i]=((int)m[i]-48)^((int)r[k++]-48)+48;
m[i]='\0';
}
OUTPUT
Enter the Frame Bits:
1011
The msg after appending 16 zeros:
10110000000000000000
The Transmitted frame is:10111011000101101011
Enter the transmitted Frame
10111011000101101011
Received msg:10111011000101101011
The Remainder is:0000000000000000
Received frame is correct.
RESULT
Thus the error detection and error correction is implemented successfully.
49
CS8581- Networks Laboratory
AIM:
ALGORITHM:
Program :
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
public static void main(String a[])throws Exception
{
ServerSocket ser=new ServerSocket(10); Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in); DataInputStream
in1=new DataInputStream(s.getInputStream()); String sbuff[]=new
String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i; String ch;
do
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine()); p.println(nf); if(nf<=sws-1)
{
50
CS8581- Networks Laboratory
RECEIVER PROGRAM
{
rptr=++rptr%8; rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf; System.out.println("\nAcknowledgment sent\n"); p.println(rptr+1); rws+=nf; }
else break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
OUTPUT:
//SENDER OUTPUT
Enter the no. of frames : 4 Enter 4 Messages to be send
hiii how r u
i am fine
how is evryone
Acknowledgment received for 4 frames
//RECEIVER OUTPUT
Result:
Thus, the program for sliding window protocol was implemented and executed successfully.
52
CS8581- Networks Laboratory
ALGORITHM:
PROGRAM
/SENDER PROGRAM
out=new
ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new
ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("reciver .....................> "+str);
System.out.println("Enter the data to send. ");
packet=br.readLine(); n=packet.length();
53
CS8581- Networks Laboratory
do
{
try
{
if(i<n){
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n){
msg="end";out.writeObject(msg);break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0
; out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack. .. \n\n");
if(ack.equals(String.valueOf(sequence)))
{ i++;
System.out.println("receiver > "+" packet recieved\n\n");
}
else{
System.out.println("Time out resending data .. \n\n");
sequence=(sequence==0)?1:0;
}
}catch(Exception e){}
}while(i<n+1);
System.out.println("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
in.close()
;
out.close();
sender.close();
}
catch(Exception e){}
}
}
public static void main(String
args[]){ Sender s=new Sender();
s.run();
}
}
54
CS8581- Networks Laboratory
//RECEIVER PROGRAM
import java.io.*;
import java.net.*;
public class
Reciever{
ServerSocket
reciever;
Socket connection=null; ObjectOutputStream out; ObjectInputStream in;
String packet,ack,data=""; int i=0,sequence=0; Reciever(){}
public void
run(){ try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in)); reciever = new ServerSocket(2004,10);
System.out.println("waiting for
connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new
ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");
do{ try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequen
ce){ data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
}
else
{
System.out.println("\n\nreceiver >"+packet +" duplicate data");
}
if(i<3){
out.writeObject(String.valueOf(sequence));i++;
}
else{ out.writeObject(String.valueOf((sequence+1)%2)); i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));
55
CS8581- Networks Laboratory
System.out.println("Data
recived="+data);
out.writeObject("connection ended
.");
}
catch(Exception
e){} finally{
try{ in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){ Reciever s=new Reciever();
while(true){
s.run();
}
}
}
OUTPUT:
//SENDER OUTPUT
Waiting for Connection....
reciver > connected . Enter the data to send....
myname
data sent>0m waiting for ack.....
receiver > packet recieved
data sent>1y
waiting for ack.....
receiver > packet recieved
data sent>0n
waiting for ack.....
receiver > packet recieved data sent>1a
waiting for ack.....
Time out resending data....
data sent>1a waiting for ack.....
receiver > packet recieved data
sent>0m
waiting for ack.....
receiver > packet recieved
data sent>1e
56
CS8581- Networks Laboratory
//RECEIVER OUTPUT
waiting for connection...
Connection established :
receiver >0m
receiver >1y
receiver >0n
receiver >1a
receiver >1a duplicate data receiver >0m
receiver >1e
Data recived=myname waiting for connection...
Result:
Thus the Stop and Wait protocol program has been executed successfully