CS22511 CN Lab (S)
CS22511 CN Lab (S)
CS22511 CN Lab (S)
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network. Two common
network protocols are
1. TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
2. UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.
Socket Programming − This is the most widely used concept in Networking. Socket
programming is a way of connecting two nodes on a network to communicate with each
other. One socket (node) listens on a particular port at an IP, while other socket reaches
out to the other to form a connection. Server forms the listener socket while client reaches
out to the server.
URL Processing − This would be covered separately. Click here to learn about URL
Processing.
Socket Programming
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.When the connection is made, the server creates a socket object on its end of the
communication. The client and the server can now communicate by writing to and reading from
the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using
sockets −
After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the
same time. Following are the useful classes providing complete set of methods to implement
sockets.
1. Socket creation:
int sockfd = socket(domain, type, protocol)
Setsockopt:
int setsockopt(int sockfd, int level, int optname,
const void *optval, socklen_t optlen);
This helps in manipulating options for the socket referred by the file descriptor sockfd.
This is completely optional, but it helps in reuse of address and port. Prevents error such
as: “address already in use”.
2. Bind:
After creation of the socket, bind function binds the socket to the address and port
number specified in addr(custom data structure). In the example code, we bind the server
to the localhost, hence we use INADDR_ANY to specify the IP address.
3. Listen:
It puts the server socket in a passive mode, where it waits for the client to approach the
server to make a connection. The backlog, defines the maximum length to which the
queue of pending connections for sockfd may grow. If a connection request arrives when
the queue is full, the client may receive an error with an indication of
ECONNREFUSED.
4. Accept:
It extracts the first connection request on the queue of pending connections for the
listening socket, sockfd, creates a new connected socket, and returns a new file descriptor
referring to that socket. At this point, connection is established between client and server,
and they are ready to transfer data.
The connect() system call connects the socket referred to by the file descriptor sockfd to
the address specified by addr. Server’s address and port is specified in addr.
2. Communication
To communicate over a socket connection, streams are used to both input and output the
data.
The socket connection is closed explicitly once the message to server is sent.
Server Programming
A ServerSocket which waits for the client requests (when a client makes a new Socket())
A plain old Socket socket to use for communication with the client.
2. Communication
Java DataOutputStream class allows an application to write primitive Java data types to
the output stream in a machine-independent way.Java application generally uses the data output
stream to write data that can later be read by a data input stream.
Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.Java application generally uses the data output stream to
write data that can later be read by a data input stream.
After finishing, it is important to close the connection by closing the socket as well as
input/output streams.
Important Points
Server application makes a ServerSocket on a specific port which is 5000. This starts our
Server listening for client requests coming in for port 5000.
Then Server makes a new Socket to communicate with the client.
socket = server.accept()
The accept() method blocks(just sits there) until a client connects to the server.
Then we take input from the socket using getInputStream() method. Our Server keeps
receiving messages until the Client sends “Over”.
After we’re done we close the connection by closing the socket and the input stream.
To run the Client and Server application on your machine, compile both of them. Then
first run the server application and then run the Client application.
Result:
Thus, the study of Socket Programming was done on client server model.
EX 2: Applications using TCP Sockets:
AIM:
Write a program to send a message to server from client using TCP Socket.
ALGORITHM:
SERVER:
1. Start.
2. Create a Server socket defined with port number and a socket to accept the connection
from client.
3. Create a Data input stream and initialize it with object input stream.
4. Read the message from the socket.
5. Print the message.
6. Close the socket and input stream,followed by closing the server socket.
7. Stop.
CLIENT:
1. Start.
2. Create a socket with IP address and port number to establish a connection.
3. Create a Data output stream and initialize it with object output stream.
4. Write a message and send it through the socket.
5. Close the socket followed by closing the input stream.
6. Stop.
SOURCE CODE:
SERVER:
import java.io.*;
import java.net.*;
class server{
{
try
{ ServerSocket ss = new
ss.close();
}catch(Exception e)
System.out.println(e);
} } }
CLIENT:
import java.io.*;
import java.util.Scanner;
import java.net.*;
class client
{ try
dos.writeUTF(var.nextLine());
catch(Exception e)
System.out.println(e); } }}
EXECUTION PROCEDURE:
TERMINAL 1(server):
TERMINAL 2(client):
OUTPUT:
TERMINAL 1(server):
TERMINAL 2(client):
RESULT:
Thus, the message was transferred successfully from client to server using TCP socket.
DOC/LP/01/28.02.02
AIM:
ALGORITHM:
SERVER :
1. Start.
2. Create a Server socket defined with port number and a socket to accept the connection
from client.
3. Create a Data input stream and initialize it with object input stream.
4. Read the message from the socket.
5. Print the message.
6. If the message is “terminate” then go to step 8 else to step 7.
7. Write a message to client through the socket and go to step 4.
8. Close the socket and input stream followed by closing the server socket.
9. Stop.
CLIENT:
1. Start.
2. Create a socket with IP address and port number to establish a connection.
3. Create a Data output stream and initialize it with object output stream.
4. Write a message to the socket.
5. If the message is “terminate” then go to step 8 else to step 6.
6. Read the message from server.
7. Print the message and go to step 4.
8. Close the socket followed by closing the input stream.
9. Stop.
SOURCE CODE:
CLIENT:
class client3
try
String str="",str1="";
while(!str.equals("end"))
str=sc.nextLine();
dout.writeUTF(str);
dout.flush();
str1=din.readUTF();
}}
catch(Exception e){System.out.println(e);}
}}
SERVER:
class server3
try{
Socket ss=s.accept();
str.equals("end"))
str=din.readUTF();
str1=sc.nextLine();
dout.writeUTF(str1);
dout.flush();
ss.close();
}}
EXECUTION PROCEDURE:
TERMINAL 1(server):
TERMINAL 2(client):
OUTPUT:
TERMINAL 1(server):
end
TERMINAL 2(client):
end
RESULT:
Thus, the concept of chatting was successfully done using TCP – Socket Program.
DOC/LP/01/28.02.02
AIM:
To get the current date and time of a server using TCP – socket.
ALGORITHM:
SERVER :
1. Start.
2. Create a Server Socket and a socket which is going to give a handshake to client socket.
3. Create a print writer object and write the date and time of server to client through output
stream.
4. Close the socket and server socket.
5. Stop
CLIENT:
1. Start
2. Create a socket with a IP address and a port number.
3. Create a buffered reader object and get the date & time through input stream.
4. Print the date and time.
5. Close the socket.
6. Stop.
SOURCE CODE:
SERVER:
import java.net.*;
import java.io.*;
import java.util.*;
class dateserver
Socket s=ss.accept();
dos.writeUTF(str);
p.close();
s.close();
ss.close();
}}
CLIENT:
import java.net.*;
import java.io.*;
class dateclient
String str;
Str=dis.readUTF();
s.close();
}}
EXECUTION PROCEDURE:
TERMINAL 1(server):
TERMINAL 1(client):
OUTPUT:
TERMINAL 1(server):
connected
TERMINAL 2(client):
The current Date and time is Sat Feb 03 06:38:06 PST 2018
RESULT:
Thus the program has compiled and executed successfully to get the current date
and time of the server.
DOC/LP/01/28.02.02
AIM:
To create a echo server and echo client using TCP – socket program.
ALGORITHM:
SERVER :
1. Start.
2. Create a server socket with it port number and wait for connection.
3. Get the message from client and print it .
4. Send the message back to client.
5. Stop.
CLIENT :
1. Start.
2. Create a socket with the IP of the server and its port number.
3. Send a message to the server.
4. Receive the same message echoed back from the server and print it .
5. Stop.
SOURCE CODE:
SERVER:
import java.net.*;import java.io.*;import java.util.*;
class echoserver
String msg;
Socket s=ss.accept();
Str=dis.readUTF();
dos.writeUTF(str);
p.close();
s.close();
ss.close();
}}
CLIENT:
class echoclient
String str;
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
Sytem.out.println(“Enter mg to server”);
Scanner c=new
Scanner(Sytem.in);
str=c.nextLine();
dos.writeUTF(str);
str=dis.readUTF();
p.close();
s.close();
}}
EXECUTION PROCEDURE:
TERMINAL 1(server):
TERMINAL 2(client):
OUTPUT:
TERMINAL 1(server):
TERMINAL 2(client):
Enter mg to server hi
echoed msg is : hi
Ex 2E File Transfer
AIM: To write a java program for file transfer using TCP Sockets.
Algorithm
Server
Step4: Get the file name and stored into the BufferedReader.
Step6: If file is exists then FileReader read the content until EOF is reached.
Client
Step4: The object of a BufferReader class is used for storing data content which has been
DOC/LP/01/28.02.02
ALGORITHM:
SERVER :
1. Start.
2. Create a datagram socket with it port number.
3. Wait for message and receive the message.
4. Print the received message.
5. Stop.
CLIENT:
1. Start.
2. Create a datagram socket with its port number and also get the address of the localhost.
3. Create a datagram packet with the buffer size and also read the message to be sent.
4. Send the message to server using the server port number.
5. Close the sockets.
6. Stop.
SOURCE CODE:
SERVER:
class udpserver
String msg;
s.receive(dp);
msg=new String(dp.getData(),0,dp.getLength());
s.close();
}}
CLIENT:
class udpclient
String msg;
String host=”localhost”;
InetAddress ia=InetAddress.getLocalHost(host);
msg=b.readLine();
buf=msg.getBytes();
s.send(dp);s.close();}}
EXECUTION PROCEDURE:
TERMINAL 1(server):
[login@cs-xServer udp]$ javac udpserver.java
TERMINAL 2(client):
OUTPUT:
TERMINAL 1(server):
TERMINAL 2(client):
ALGORITHM:
SERVER :
1. Start.
2. Create a datagram socket with it a port number ,also create a datagram packet.
3. Wait for message and receive the message.
4. Print the received message.
5. If the message is stop then go to step 8
6. Get the message to be sent to client and send it.
7. If the message is “stop” then go to step 8 else go to step 3
8. Close the socket.
9. Stop.
CLIENT:
1. Start.
2. Create a datagram packet ,datagram socket with its port number and also get
the address of the local host.
3. Read the message to be sent.
4. Send the message to server using the server port number.
5. If the message is “stop” then go to step else continue.
6. Wait for the message from the server
7. If the message is “stop” then go to step 8 else go to step 3
8. Close the sockets.
9. Stop.
SOURCE CODE:
SERVER:
class udpserverchat
String msg;
String host=”localhost”;
InetAddress ia=InetAddress.getLocalHost(host);
do
s.receive(dp);
msg=new String(dp.getData(),0,dp.getLength());
if(msg.equals("stop"))
break;
msg=b.readLine();
buf=msg.getBytes();
s.send(dp);
}while(!(msg.equals("stop")));
s.close();
}}
CLIENT:
class udpclientchat
String msg;
String host=”localhost”;
InetAddress ia=InetAddress.getLocalHost(host);
do
msg=b.readLine();
buf=msg.getBytes();
if(msg.equals("stop"))
break;
s.receive(dp);
msg=new String(dp.getData(),0,dp.getLength());
}while(!(msg.equals("stop")));
s.close();
}}
EXECUTION PROCEDURE:
TERMINAL 1(server):
TERMINAL 2(client):
OUTPUT:
SERVER:
hi client!
Stop
CLIENT:
hi!
terminate now.
AIM:
ALGORITHM:
SERVER:
1. Start.
2. Create a datagram socket with it a port number and also create a datagram packet.
3. Wait for message and receive the message.
4. Print the received message.
5. Initialise String IPs with its corresponding Domain names.
6. If the received message is an IP Address,then check with the String IPs and
send the corresponding Domain name.
7. If the received message is a Domain name,then check with the String Domain
name and send the corresponding IP.
8. Close the socket.
9. Stop.
CLIENT:
1. Start
2. Create a datagram packet and a datagram socket with its port number and
also address of the local host.
3. Read the Domain Name or IP Address from the user.
4. Send the message to server using the server port number.
5. Wait for the message from the server
6. Display the received message from the server.
7. Close the sockets.
8. Stop.
SOURCE CODE:
SERVER:
class dns_server{
try{
while(true)
DatagramPacket receiver=newDatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String s=str.trim();
System.out.println(s);
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1","172.16.2.79"};
Stringname[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.com","www.softped
ia.com"};
for(int i=0;i<ip.length;i++)
if(s.equals(ip[i]))
{
sendbyte=name[i].getBytes();
server.send(sender);
break;
else if(s.equals(name[i]))
sendbyte=ip[i].getBytes();
server.send(sender);
break;
} }
break;
} }
catch(Exception e)
System.out.println(e);
}}}
CLIENT:
class dns_cli{
try
{
InetAddress addr=InetAddress.getByName("127.0.0.1");
String str=in.readLine();
sendbyte=str.getBytes();
client.send(sender);
client.receive(receiver);
name:"+s.trim());
client.close();
catch(Exception e)
System.out.println(e);
} } }
EXECUTION PROCEDURE:
TERMINAL 1(server):
OUTPUT:
SERVER:
165.165.80.80
CLIENT:
165.165.80.80
RESULT:
Thus, the program for message transfer, chat and domain name system with udp socket was
successfully implemented.
DOC/LP/01/28.02.02
EX 4) BIT STUFFING AND CRC
AIM:
A) BIT STUFFING:
DESCRIPTION:
Bit Stuffing is one of the framing technique used in Data-Link Layer (layer 2) of OSI Reference Model.
In Bit-Stuffing technique, stuffing is done at the bit level. It was developed for the once very popular
HDLC(High-Level Data Link Layer) protocol. Each frame begins and ends with a special bit pattern
01111110 or 0x7E in hexadecimal. This pattern is a flag byte.
"Whenever the sender's data link layer encounters five consecutive 1s in the data, it
automatically stuffs a 0 bit into the outgoing bit stream"
"Whenever the receiver sees five consecutive incoming 1 bits, followed by a 0 bit, it
automatically destuffs (i.e, deletes) the 0 bit."
ForExample:
If the user data contain the flag pattern, 01111110, this flag is transmitted as 011111010 but
stored in the receiver's memory as 01111110, as shown in fig below:
if(res.charAt(i) == '1')
{
counter++;
out = out + res.charAt(i);
}
else
{
out = out + res.charAt(i);
counter = 0;
}
if(counter == 5)
{
if((i+2)!=res.length())
out = out + res.charAt(i+2);
else
out=out + '1';
i=i+2;
counter = 1;
}
}
System.out.println("Message Recevied...Successfully!!!");
System.out.println("The Destuffed Message is: "+out);
}
}
The CRC calculation or cyclic redundancy check was the result of this. Nowadays CRC calculations are
used in all types of communications. All packets sent over a network connection are checked with a CRC.
Also each data block on your hard disk has a CRC value attached to it. Modern computer world cannot
do without these CRC calculations. So let's see why they are so widely used. The answer is simple; they
are powerful, detect many types of errors and are extremely fast to calculate especially when dedicated
hardware chips are used.
The idea behind CRC calculation is to look at the data as one large binary number. This number is divided
by a certain value and the remainder of the calculation is called the CRC. Dividing in the CRC calculation
at first looks to cost a lot of computing power, but it can be performed very quickly if we use a method
similar to the one learned at school. We will as an example calculate the remainder for the character
'm'—which is 1101101 in binary notation—by dividing it by 19 or 10011. Please note that 19 is an odd
number.
This is necessary as we will see further on. Please refer to your schoolbooks as the binary calculation
method here is not very different from the decimal method you learned when you were
young. It might only look a little bit strange. Also notations differ between countries, but the method is
similar. With decimal calculations you can quickly check that 109 divided by 19 gives a quotient of 5 with
14 as the remainder. But what we also see in the scheme is that every bit extra to check only costs one
binary comparison and in 50% of the cases one binary subtraction.
You can easily increase the number of bits of the test data string—for example to 56 bits if we use our
example value "Lammert"—and the result can be calculated with 56 binary comparisons and an average
of 28 binary subtractions. This can be implemented in hardware directly with only very few transistors
involved. Also software algorithms can be very efficient. All of the CRC formulas you will encounter are
simply checksum algorithms based on modulo-2 binary division where we ignore carry bits and in effect
the subtraction will be equal to an exclusive or operation. Though some differences exist in the specifics
across different CRC formulas, the basic mathematical process is always the same:
The message bits are appended with c zero bits; this augmented message is the dividend .
A predetermined c+1-bit binary sequence, called the generator polynomial, is the divisor .
The checksum is the c-bit remainder that results from the division operation Table 1 lists some of the
most commonly used generator polynomials for 16- and 32-bit CRCs. Remember that the width of the
divisor is always one bit wider than the remainder. So, for example, you’d use a 17-bit generator
polynomial whenever a 16-bit checksum is required.
Table 1: International Standard CRC Polynomials CRC-CCITT CRC-16 CRC-32 Checksum Width 16 bits 16
bits 32 bits Generator Polynomial 10001000000100001 11000000000000101
100000100110000010001110110110111 Error detection with CRC
Consider a message represented by the polynomial M(x)
Consider a generating polynomial G(x)
This is used to generate a CRC = C(x) to be appended to M(x). Note this G(x) is prime.
Steps:
1. Multiply M(x) by highest power in G(x). i.e. Add So much zeros to M(x).
2. Divide the result by G(x). The remainder = C(x). Special case: This won't work if bitstring =all zeros.
We don't allow such an M(x).But M(x) bitstring = 1 will work, for example. Can divide 1101 into 1000.
3. If: x div y gives remainder c that means: x = n y + c Hence (x-c) = n y (x-c) div y gives remainder 0
Here (x-c) = (x+c) Hence (x+c) div y gives remainder 0
4. Transmit: T(x) = M(x) + C(x)
5. Receiver end: Receive T(x). Divide by G(x), should have remainder 0.
Note if G(x) has order n - highest power is xn, then G(x) will cover (n+1) bits and the remainder will
cover n bits. i.e. Add n bits (Zeros) to message.
SOURCE CODE:
import java.util.*;
class crc
{
void div(int a[],int k)
{
int gp[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1};
int count=0;
for(int i=0;i<k;i++)
{
if(a[i]==gp[0])
{
for(int j=i;j<17+i;j++)
{
a[j]=a[j]^gp[count++];
}
count=0;
} } }
public static void main(String args[])
{
int a[]=new int[100];
int b[]=new int[100];
int len,k;
crc ob=new crc();
System.out.println("Enter the length of Data Frame:");
Scanner sc=new Scanner(System.in);
len=sc.nextInt();
int flag=0;
System.out.println("Enter the Message:");
for(int i=0;i<len;i++)
{
a[i]=sc.nextInt();
}
for(int i=0;i<16;i++)
{
a[len++]=0;
}
k=len-16;
for(int i=0;i<len;i++)
{
b[i]=a[i];
}
ob.div(a,k);
for(int i=0;i<len;i++)
a[i]=a[i]^b[i];
System.out.println("Data to be transmitted: ");
for(int i=0;i<len;i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
System.out.println("Enter the Reveived Data: ");
for(int i=0;i<len;i++)
{
a[i]=sc.nextInt();
}
ob.div(a, k);
for(int i=0;i<len;i++)
{
if(a[i]!=0)
{
System.out.println("ERROR in Received data");
return;
}
System.out.println("no error");
} } }
OUTPUT:
Enter the length of Data Frame: 4
Enter the Message: 1 0 1 1
Data to be transmitted: 1 0 1 1 1 0 1 1 0 0 0 1 0 1 1 0 1 0 1 1
Enter the Received Data: 1 0 1 1 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 1
ERROR in Received Data
RESULT:
Thus ,the program for Bit stuffing and CRC was successfully implemented.
DOC/LP/01/28.02.02
EX 5: IMPLEMENTATION OF FLOW CONTROL (Stop and Wait Protocol and Sliding
Window Protocol)
AIM:
ALGORITHM:
SENDER:
1. Start.
2. Create a server socket with its port number and wait for connection.
3. Enter the message to be sent to the receiver and wait for the acknowledgement from
the receiver.
4. If the acknowledgement is received, ask the user whether to continue this process.
5. If “Yes”,go to step 3.
6. If “end”,Close the Socket.
7. Stop.
RECEIVER:
1. Start.
2. Create a server socket with its port number and localhost.
3. Wait for the message and read the message from the sender.
4. If the message is received successfully, send the acknowledgement to the sender.
5. Continue this process if the user wants to send another message.
6. If not, close the socket.
7. Stop.
SOURCE CODE:
SENDER:
import java.io.*;
import java.net.*;
class sender
try
Socket s = ss.accept();
String str,a;
do
str=dis2.readLine();
dos.writeUTF(str);
str=(String)dis.readUTF();
System.out.println(str);
System.out.print("continue ? :");
a=dis2.readLine();
dos.writeUTF(a);
}while(a.equals("yes"));
dos.flush();
dos.close();
s.close();
ss.close();
catch(Exception e)
{ System.out.println(e);
} }}
RECEIVER:
import java.io.*;
import java.net.*;
class receiver
{
try
String str;
while(true)
str=(String)dis.readUTF();
str=(String)dis.readUTF(); if(!str.equals("yes"))
{ break;}
dos.flush();
dos.close();
s.close();
catch(Exception e)
{ System.out.println(e);
} }}
EXECUTION :
TERMINAL 1 (Sender) :
TERMINAL 2 (Receiver) :
OUTPUT:
SENDER:
Enter msg :
hi
continue ?:yes
Enter msg :
hello
continue ?:end
RECEIVER:
hi
hello
ALGORITHM:
SENDER:
1. Start.
2. Create a server socket with port number and wait for connection.
3. Read the number of frames, nf.
4. Read the nf messages to be sent to the receiver and wait for the acknowledgement from
the receiver through the TCP connection.
5. If the acknowledgement is received, ask the user whether to continue this process.
6. If “Yes”,go to step 3.
7. If “No”,Close the Socket.
8. Stop.
RECEIVER:
1. Start.
2. Connect to server with its port number and localhost.
3. Wait for the message and read the message from the sender.
4. If the message is received successfully, send the acknowledgement to the sender.
5. Continue this process if the user wants to send another set of frames.
6. If not, close the socket.
7. Stop.
SOURCE CODE:
SENDER:
import java.net.*;
import java.io.*;
Socket s=ss.accept();
int sptr=0,sws=8,nf,ano,i;
String ch;
do{
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<sws)
for(i=1;i<=nf;i++)
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
sws-=nf;
System.out.print("Acknowledgement received");
ano=Integer.parseInt(in1.readLine());
sws+=nf;
else
break;
System.out.print("continue ? : ");
ch=in.readLine();
p.println(ch);
}while(ch.equals("yes"));
s.close();
}}
RECEIVER:
import java.io.*;
import java.net.*;
class receiver
int i=0,rptr=-1,nf,rws=8;
String ch;
System.out.println();
do{
nf=Integer.parseInt(in.readLine());
if(nf<rws)
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
rws-=nf; System.out.println("\
nAcknowledgement sent\n");
p.println(rptr+1);
rws+=nf;
else break;
ch=in.readLine();
}while(ch.equals("yes"));
}}
EXECUTION PROCEDURE:
TERMINAL 1(sender):
TERMINAL 2(receiver):
OUTPUT:
SENDER:
: hi
hello
Acknowledgement received
continue ? : no
RECEIVER:
Acknowledgement sent
RESULT:
Thus, the program for Stop and Wait & Sliding Window protocol was successfully
executed with TCP Socket.
DOC/LP/01/28.02.02
EX 6) SIMULATION OF ARP AND RARP
A) Address Resolution Protocol & Reverse Address Resolution Protocol:
AIM:
ALGORITHM:
SERVER:
1. Start.
2. Create a datagram socket with it a port number and also create a datagram packet.
3. Initialise Strings IP and mac with its corresponding IP address and MAC address.
4. Wait for message and receive the message.
5. Print the received message.
6. If the received message is an IP Address,then check with the String IPs and send
the Corresponding MAC address.If the received message is a MAC address,then
check with the String mac and send the corresponding IP.
7. Close the socket.
8. Stop.
CLIENT:
1. Start
2. Create a datagram packet and a datagram socket with its port number and also get
the address of the local host.
3. Read the MAC address IP Address from the user.
4. Send the message to server using the server port number.
5. Wait for the message from the server
6. Display the received message from the server.
7. Close the sockets.
8. Stop.
SOURCE CODE:
SERVER:
import java.io.*;
import java.net.*;
import java.util.*;
class server
try{
String ip[]={"165.165.80.80","165.165.79.1","172.16.2.79","211.202.59.55",};
String mac[]={"3A-2B-89-11-02-55","31-11-69-5A-01-23","55-E5-23-58-55-
09","44-8A-5B-BA-BD-D4"};
while(true)
{
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
str=new String(receiver.getData());
System.out.println(s=str.trim());
InetAddress addr=receiver.getAddress();
port=receiver.getPort();
for(int i=0;i<ip.length;i++)
if(s.equals(ip[i]))
sendbyte=mac[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
else if(s.equals(mac[i]))
sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
} }
break;
} }
catch(Exception e)
System.out.println(e);
} }
CLIENT:
import java.io.*;
import java.net.*;
import java.util.*;
class client
try
InetAddress addr=InetAddress.getByName("127.0.0.1");
String str=in.readLine();
sendbyte=str.getBytes();
client.send(sender);
client.receive(receiver);
client.close();
catch(Exception e)
System.out.println(e);
} }}
EXECUTION PROCEDURE:
TERMINAL 1 (Sender) :
TERMINAL 2 (Receiver) :
OUTPUT:
SERVER:
165.165.80.80
CLIENT:
Enter the MAC address or IP address:
165.165.80.80
RESULT:
Thus the program for ARP and RARP were executed successfully with UDP socket.
DOC/LP/01/28.02.02
EX 7: Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute.
Capture ping and traceroute PDUs using a network protocol analyzer and examine
A) Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute
AIM:
To Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute
Tcpdump
The tcpdump utility allows you to capture packets that flow within your network to assist in network
troubleshooting. The following are several examples of using tcpdump with different options. Traffic is
captured based on a specified filter.
Options Description
The following are some specific examples of the power of the tcpdump utility.
1. Display traffic between 2 hosts
To display all traffic between two hosts (represented by variables host1 and host2):
Provide the protocol as an argument to display only traffic for a specific protocol, for example
# tcpdump protocol
# tcpdump tcp
2.Netstat
Windows, Linux, UNIX and other operating systems. Netstat provides information and
statistics about protocols in use and current TCP/IP network connections. The Windows help
listening port is displayed. In this case the executable name is in [] at the bottom, on
top is the component it called, and so forth until TCP/IP was reached. Note that this
option can be time-consuming and will fail unless you have sufficient permissions.
-p proto 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 per-protocol statistics,
proto may be any of: IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
-s Displays per-protocol statistics. By default, statistics are shown for IP, IPv6, ICMP,
ICMPv6, TCP, TCPv6, UDP, and UDPv6; the -p option may be used to specify a subset
of the default.
-v When used in conjunction with -b, will display sequence of components involved in
Interval Redisplays selected statistics, pausing interval seconds between each display. Press
CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current
netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]
Parameters
Used without
-a Displays all active TCP connections and the TCP and UDP ports on which the
computer is listening.
-e Displays Ethernet statistics, such as the number of bytes and packets sent and
-n Displays active TCP connections, however, addresses and port numbers are
-o
Displays active TCP connections and includes the process ID (PID) for each
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.
-p
Shows connections for the protocol specified by Protocol. In this case, the
Protocol can 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.
-s 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 shown for the TCP over IPv6, UDP over IPv6, ICMPv6, and IPv6
protocols.
-r Displays the contents of the IP routing table. This is equivalent to the route
print command.
Interval Redisplays the selected information every Interval seconds. Press CTRL+C to
stop the redisplay. If this parameter is omitted, netstat prints the selected
3. Ifconfig
command prompt. This utility allows you to get the IP address information of a Windows
computer. It also allows some control over active TCP/IP connections. Ipconfig replaced the
older winipcfg utility.
Using ipconfig
From the command prompt, type ipconfig to run the utility with default options. The output
of the default command contains the IP address, network mask, and gateway for all physical and
virtual network adapter
Syntax
ipconfig [/all] [/renew [Adapter]] [/release [Adapter]] [/flushdns] [/displaydns] [/registerdns]
Parameters
Used without
parameters displays the IP address, subnet mask, and default gateway for all adapters.
/all Displays the full TCP/IP configuration for all adapters. Without this
parameter, ipconfig displays only the IP address, subnet mask, and default
gateway values for each adapter. Adapters can represent physical interfaces,
connections.
/renew
[Adapter]
Renews DHCP configuration for all adapters (if an adapter is not specified)
/release
[Adapter]
DHCP configuration and discard the IP address configuration for either all
adapters (if an adapter is not specified) or for a specific adapter if the Adapter
type the adapter name that appears when you use ipconfig without
parameters.
/flushdns
Flushes and resets the contents of the DNS client resolver cache. During DNS
troubleshooting, you can use this procedure to discard negative cache entries
from the cache, as well as any other entries that have been added
dynamically.
/displaydns
Displays the contents of the DNS client resolver cache, which includes both
entries preloaded from the local Hosts file and any recently obtained
resource records for name queries resolved by the computer. The DNS
/registerdns
Initiates manual dynamic registration for the DNS names and IP addresses
problem between a client and the DNS server without rebooting the client
/showclassid
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
/setclassid
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
Examples:
ipconfig /all To display the full TCP/IP configuration for all adapters
Connection"
ipconfig /flushdns To flush the DNS resolver cache when troubleshooting DNS
ipconfig /showclassid Local To display the DHCP class ID for all adapters with names
Connection" TEST
adapter to TEST
4. Nslookup
The nslookup (which stands for name server lookup) command is a network utility
program used to obtain information about internet servers. It finds name server information
5. traceroute
Traceroute is a network diagnostic tool used to track the pathway taken by a packet
on an IP network from source to destination. Traceroute also records the time taken for each
Traceroute uses Internet Control Message Protocol (ICMP) echo packets with variable time to
live (TTL) values. The response time of each hop is calculated. To guarantee accuracy, each
hop is queried multiple times (usually three times) to better measure the response of that
particular hop.
tracert www.google.com
With the tracert command shown above, we're asking tracert to show us the path from the
local computer all the way to the network device with the hostname www.google.com. Tracing
route to www.l.google.com [209.85.225.104]
2 35 ms 19 ms 29 ms 98.245.140.1
3 11 ms 27 ms 9 ms te-0-3.dnv.comcast.net [68.85.105.201]
... 13 81 ms 76 ms 75 ms 209.85.241.37
14 84 ms 91 ms 87 ms 209.85.248.102
Trace complete.
You can use Wireshark to capture network packets, but to capture and analyze packets
programmatically in Java, you can use the jNetPcap library.
Maven Dependency:
<dependency>
<groupId>org.jnetpcap</groupId>
<artifactId>jnetpcap</artifactId>
<version>1.4</version>
</dependency>
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import java.util.ArrayList;
import java.util.List;
if (r == Pcap.NOT_OK || alldevs.isEmpty()) {
return;
: device.getName());
int snaplen = 64 * 1024; // Capture all packets, no
if (pcap == null) {
return;
new java.util.Date(packet.getCaptureHeader().timestampInMillis()),
user
);
};
To capture ping and traceroute packets, ensure that these commands are running while the packet
capture is active. You can initiate ping or traceroute from the command line:
Analysis
Use the captured packets for further analysis. You can dissect the packet details and analyze
headers and payloads for networking insights.
SOURCE CODE:
import java.io.*;
import java.net.*;
class pingserver
try
String str,ip;
ip=br.readLine();
Runtime H = Runtime.getRuntime();
InputStream in = p.getInputStream();
while((str=b.readLine())!=null)
System.out.println(" "+str);
catch(Exception e)
System.out.println(e);
} }}
EXECUTION:
OUTPUT:
TRACE ROUTE:
ALGORITHM:
1. Start.
2. Read the IP address to which the server needs to be trace the route as a string.
3. Using the process class, the IP is traced to the server with the help of runtime
class.
4. Display the traceroute status.
5. Stop.
SOURCE CODE:
import java.io.*;
import java.net.*;
class traceroute
try
String str,ip;
ip=br.readLine();
Runtime H = Runtime.getRuntime();
Process p = H.exec("traceroute
"+ip); InputStream in =
p.getInputStream();
System.out.println(" "+str);
} }
catch(Exception e)
System.out.println(e);
} }}
EXECUTION:
OUTPUT:
Tracing route t
over a maximum
1 <1 ms
Trace complete.
RESULT:
Thus, the program for ping and trace route was simulated successfully.
DOC/LP/01/28.02.02
AIM:
ALGORITHM:
1. Start.
2. Create a remote interface.
3. Provide the implementation of remote interface.
4. Compile the implementation class and create the stub and skeleton object using RMIC
tool.
5. Start the registry service by RMI registry tool.
6. Create and start remote application(server).
7. Create and start client application.
8. Stop.
SOURCE CODE:
calculator:
calc_impl :
{
super();
return a+b;
return a-b;
return a*b;
return a/b;
calc_server :
import java.rmi.Naming;
public calc_server()
{
try
Naming.rebind("rmi://localhost:1099/CalculatorService",c);
}
catch(Exception e)
System.out.println("Trouble : "+e);
new calc_server();
calc_client :
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
{
try
calculator c=(calculator)Naming.lookup("rmi://localhost/CalculatorService");
System.out.println(c.sub(4,3));
System.out.println(c.add(4,5));
System.out.println(c.mul(3,6));
System.out.println(c.div(9,3));
}
catch(Exception e){
System.out.println(e);
} }}
EXECUTION :
Terminal 1:
Terminal 2:
Terminal 3 :
Terminal 4 :
OUTPUT:
1
18
RESULT:
Thus, the program for implementing Remote Method Invocation with calculator
application was executed successfully.
DOC/LP/01/28.02.02
EX 09) SUBNETTING
AIM:
To find the subnet mask, host ID and net ID for a given IP address using the concept of
Subnetting.
ALGORITHM:
1. Start.
2. Read an IP address.
3. Split the IP address into parts for each occurrence of a ‘.’.
4. Typecast the split IP address into integer.
5. Compare the type-casted integer with all the ranges of IP address to find the subnet mask.
6. Display the Subnet mask.
7. Similarly split the mask and ‘and’ it with the split parts of IP and subnet mask to provide
the Network address.
8. Subtract the split parts of IP and Net ID to provide the corresponding host ID.
9. Display the network address and host id.
10. Stop.
SOURCE CODE:
import java.io.*;
import java.net.*;
{ System.out.print("Enter IP : ");
String ip=br.readLine();
String[] ipAddrParts=ip.split("\\.");
String checkclass=ipAddrParts[0];
int cc=Integer.parseInt(checkclass);
String mask=null;
if(cc<128)
mask="255.0.0.0";
mask="255.255.0.0.";
if(cc>191)
mask="255.255.255.0";
System.out.println("\nMASK : "+mask);
String networkAddr="";
String hostid="";
String[] maskParts=mask.split("\\.");
for(int i=0;i<4;i++)
{ int x=Integer.parseInt(ipAddrParts[i]);
int y=Integer.parseInt(maskParts[i]);
int z=x&y;
networkAddr+=z+".";
z=x-z;
hostid+=z+".";
System.out.println("HOST ID : "+hostid);
}}
EXECUTION :
OUTPUT:
Enter IP:127.0.0.1
MASK:
255.0.0.0
NETWORK ADDRESS:
127.0.0.0.
HOST ID:
0.0.0.1
RESULT:
Thus, the subnet mask, host ID and Net ID for a given IP address was found successfully.
DOC/LP/01/28.02.02
Do the following a) Establish a Local Area Network (LAN) with 4 hosts and a switch/Hub b) Connect two
LANs using multi-router topology with static routes
DECRIPTION:
Cisco Packet Tracer 7.2.2 is a powerful network simulator for CCNA TM and CCNPTM
certification exam training allowing students to create networks with an almost unlimited number
of devices and to experience troubleshooting without having to buy real Cisco TM routers or
switches.
Cisco Packet Tracer features an array of simulated routing & switching protocols with STP,
HSRP, RIP, OSPF, EIGRP, and BGP to the extent required by the current Cisco CCNA
curriculum as well as application layer protocols (HTTP, DNS,) to simulate network traffic.
Network simulators are one of the key ingredients of training for the CCNA. There are few
network simulators as widely used as Cisco Packet Tracer. Packet Tracer has been a staple tool
of CCNA students ever since it was released. With Packet Tracer, you can imitative a live
networking environment.
For instance, the user can design and interact with network topologies comprised of Cisco
devices. Through building networks and “troubleshooting” on Packet Tracer users can start to
build their knowledge of networking before working on a live network. There are also a range of
tutorials, tips and help topics to help users learn the basics of the OSI model.
If you’re preparing to take the CCNA, then Packet Tracer will help you to take that first step
towards “hands on” experience. Configuring routers and switches will be just some of the skills
that you learn when using the program. In this article we’re going to look at what Packet Tracer
is and how you can use it to configure a router.
What is Packet Tracer? Packet Tracer is a protocol simulator developed by Dennis Frezzo and his team at Cisco
Systems. Packet Tracer (PT) is a powerful and dynamic tool that displays the various protocols used in networking,
in either Real Time or Simulation mode. This includes layer 2 protocols such as Ethernet and PPP, layer 3 protocols
such as IP, ICMP, and ARP, and layer 4 protocols such as TCP and UDP. Routing protocols can also be traced.
Purpose: The purpose of this lab is to become familiar with building topologies in Packet Tracer.
Requisite knowledge: This lab assumes some understanding of the Ethernet protocol. At this point we have not
discussed other protocols, but will use Packet Tracer in later labs to discuss those as well.
We will begin building our network topology by selecting devices and the media in which to connect them. Several
types of devices and network connections can be used. For this lab we will keep it simple by using End Devices,
Switches, Hubs, and Connections.
Single click on each group of devices and connections to display the various choices. The devices you see may
differ slightly.
Step 3: Building the Topology – Adding Hosts
Move the cursor into topology area. You will notice it turns into a plus “+” sign.
Adding a Hub
Add the hub by moving the plus sign “+” below PC0 and PC1 and click once.
1 2 3 4 5
Repeat the steps above for PC1 connecting it to Port 1 on Hub0. (The actual hub port you choose does not
matter.)
Adding a Switch
Add the switch by moving the plus sign “+” below PC2 and PC3 and click once.
Connect PC2 to Hub0 by first choosing Connections.
1 2 3 4 5 6
Repeat the steps above for PC3 connecting it to Port 3 on Switch0 on port FastEtherent0/2. (The actual
switch port you choose does not matter.)
Move the cursor over the link light to view the port number. Fa means FastEthernet, 100 Mbps Ethernet.
Step 5: Configuring IP Addresses and Subnet Masks on the Hosts
Before we can communicate between the hosts we need to configure IP Addresses and Subnet Masks on the devices.
Choose the Config tab and click on Settings. It is here that you can change the name of PC0. It is also here
where you would enter a Gateway IP Address, also known as the default gateway and the DNS Server IP
Address. We will discuss this later, but this would be the IP address of the local router. If you want, you can enter
the Gateway IP Address 172.16.1.1 and DNS Server IP Address 172.16.1.100, although it will not be used in this
lab.
Click on Interface and then FastEthernet. Although we have not yet discussed IP Addresses, add the IP Address
to 172.16.1.10. Click once in the Subnet Mask field to enter the default Subnet Mask. You can leave this at
255.255.0.0. We will discuss this later.
Also, notice this is where you can change the Bandwidth (speed) and Duplex of the Ethernet NIC (Network
Interface Card). The default is Auto (autonegotiation), which means the NIC will negotiate with the hub or switch.
The bandwidth and/or duplex can be manually set by removing the check from the Auto box and choosing the
specific option.
Bandwidth - Auto
If the host is connected to a hub or switch port which can do 100 Mbps, then the Ethernet NIC on the host will
choose 100 Mbps (Fast Ethernet). Otherwise, if the hub or switch port can only do 10 Mbps, then the Ethernet NIC
on the host will choose 10 Mbps (Ethernet).
Duplex - Auto
Hub: If the host is connected to a hub, then the Ethernet NIC on the host will choose Half Duplex.
Switch: If the host is connected to a switch, and the switch port is configured as Full Duplex (or Autonegotiation),
then the Ethernet NIC on the host will choose Full Duplex. If the switch port is configured as Half Duplex, then the
Ethernet NIC on the host will choose Half Duplex. (Full Duplex is a much more efficient option.)
close this dialog box, click the “X” in the upper right.
Repeat these steps for the other hosts. Use the information below for IP Addresses and Subnet Masks.
To verify the information that you entered, move the Select tool (arrow) over each host.
Deleting a Device or Link
To delete a device or link, choose the Delete tool and click on the item you wish to delete.
To connect like-devices, like a Hub and a Switch, we will use a Cross-over cable. Click once the Cross- over
Cable from the Connections options.
Click once on Switch0 and choose FastEthernet0/4 (actual port does not matter).
The link light for switch port FastEthernet0/4 will begin as amber and eventually change to green as the Spanning Tree
Protocol transitions the port to forwarding.
At this point we will want to reset the network, Whenever you want to reset the network and begin the simulation
again, perform the following tasks:
Note: Because Packet Tracer also simulates the Spanning Tree Protocol (later), at times the switch may show
amber lights on its interfaces. You will need to wait for the lights to turn green on the switches before they will
forward any Ethernet frames.
2
Continue clicking Capture/Forward button until the ICMP ping is completed. You should see the ICMP
messages move between the hosts, hub and switch. The PDU Last Status should show as Successful. Click on
Clear Event List if you do not want to look at the events or click Preview Previous Events if you do. For this
exercise it does not matter.
Perform the following steps to save the topology (uses .pkt file extension).
Opening Existing Topologies
-
Configure Routers R1 and
configuration. NETWORK
TOPOLOGY:
NETWORK TOPOLOGY:
RESULT:
LP – CS22511
Date : 05/07/2024
Sub Code & Sub Name : CS22511 Computer Networks Laboratory Page: 99 of 118
AIM:
DESCRIPTION :
A network simulator is software that predicts the behavior of a computer network. Since
communication Networks have become too complex for traditional analytical methods to provide
an accurate understanding of system behavior, network simulators are used. In simulators, the
computer network is modeled with devices, links, applications etc. and the performance is
analyzed.
For this, we are using NS2 (Network Simulator –version 2). It 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, the foundation which NS is based on. Since 1995 the Defense Advanced
Research Projects Agency (DARPA) supported development of NS through the Virtual
Internetwork Test bed (VINT) project. Currently the National Science Foundation (NSF) has
joined the ride in development. The group of researchers and developers in the community are
constantly working to keep NS2 strong and versatile.
SOURCE CODE :
Node.tcl
# create nodes
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam o.nam &
exit 0
}
$ns run
NS-simple.tcl
proc finish {} {
global ns nf
$ns flush-trace
$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"
# create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
proc finish {} {
global ns nf
$ns flush-trace
OUTPUT:
OUTPUT – Simulation :
RESULT:
LP Rev. No : 00
Date : 05/07/2024
Sub Code & Sub Name : CS22511 Computer Networks Laboratory
Page: 110 of 118
Branch : CSE / AIDS Semester : V
EX 12: Perform a case study about the different routing algorithms to select the
network path with its optimum and economical during data transfer.
Link State routing Routing is the process of selecting best paths in a network. In the past, the
term routing was also used to mean forwarding network traffic among networks. However this
latter function is much better described as simply forwarding. Routing is performed for many
kinds of networks, including the telephone network (circuit switching), electronic data networks
(such as the Internet), and transportation networks. This article is concerned primarily with
routing in electronic data networks using packet switching technology.
In packet switching networks, routing directs packet forwarding (the transit of logically
addressed network packets from their source toward their ultimate destination) through
intermediate nodes. Intermediate nodes are typically network hardware devices such as routers,
bridges, gateways, firewalls, or switches. General-purpose computers can also forward packets
and perform routing, though they are not specialized hardware and may suffer from limited
performance. The routing process usually directs forwarding on the basis of routing tables which
maintain a record of the routes to various network destinations. Thus, constructing routing tables,
which are held in the router's memory, is very important for efficient routing. Most routing
algorithms use only one network path at a time. Multipath routing techniques enable the use of
multiple alternative paths.
In case of overlapping/equal routes, the following elements are considered in order to decide
which routes get installed into the routing table (sorted by priority):
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it is within a
routing protocol or over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the same routing
protocol)
3. Administrative distance: where a lower distance is preferred (only valid between different
routing protocols)
Routing, in a more narrow sense of the term, is often contrasted with bridging in its assumption
that network addresses are structured and that similar addresses imply proximity within the
network. Structured addresses allow a single routing table entry to represent the route to a group
of devices. In large networks, structured addressing (routing, in the narrow sense) outperforms
unstructured addressing (bridging). Routing has become the dominant form of addressing on the
Internet. Bridging is still widely used within localized environments.
ii. Flooding :
Flooding s a simple routing algorithm in which every incoming packet is sent through every
outgoing link except the one it arrived on. Flooding is used in bridging and in systems such as
Usenet and peer-to-peer file sharing and as part of some routing protocols, including OSPF,
DVMRP, and those used in ad-hoc wireless networks. There are generally two types of flooding
available, Uncontrolled Flooding and Controlled Flooding. Uncontrolled Flooding is the fatal
law of flooding. All nodes have neighbors and route packets indefinitely. More than two
neighbors create a broadcast storm.
Controlled Flooding has its own two algorithms to make it reliable, SNCF (Sequence Number
Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches its own
address and sequence number to the packet, since every node has a memory of addresses and
sequence numbers. If it receives a packet in memory, it drops it immediately while in RPF, the
node will only send the packet forward. If it is received from the next node, it sends it back to the
sender.
Algorithm
There are several variants of flooding algorithm. Most work roughly as follows:
2. Each node tries to forward every message to every one of its neighbours except the source
node.
This results in every message eventually being delivered to all reachable parts of the network.
Algorithms may need to be more complex than this, since, in some case, precautions have to be
taken to avoid wasted duplicate deliveries and infinite loops, and to allow messages to eventually
expire from the system. A variant of flooding called selective flooding partially addresses these
issues by only sending packets to routers in the same direction. In selective flooding the routers
don't send every incoming packet on every line but only on those lines which are going
approximately in the right direction.
Advantages
2. Since flooding naturally utilizes every path through the network, it will also use the shortest
path.
1. Flooding can be costly in terms of wasted bandwidth. While a message may only have one
destination it has to be sent to every host. In the case of a ping flood or a denial of service attack,
it can be harmful to the reliability of a computer network.
2. Messages can become duplicated in the network further increasing the load on the networks
bandwidth as well as requiring an increase in processing complexity to disregard duplicate
messages.
3. Duplicate packets may circulate forever, unless certain precautions are taken:
4. Use a hop count or a time to live count and include it with each packet. This value should
take into account the number of nodes that a packet may have to pass through on the way to its
destination.
5. Have each node keep track of every packet seen and only forward each packet once .
6. Enforce a network topology without loops
A distance-vector routing protocol requires that a router informs its neighbors of topology
changes periodically. Compared to link-state protocols, which require a router to inform all the
nodes in a network of topology changes, distance-vector routing protocols have less
computational complexity and message overhead. The term distance vector refers to the fact that
the protocol manipulates vectors (arrays) of distances to other nodes in the network. The vector
distance algorithm was the original ARPANET routing algorithm and was also used in the
internet under the name of RIP (Routing Information Protocol).
Examples of distance-vector routing protocols include RIPv1 and RIPv2 and IGRP. Method
Routers using distance-vector protocol do not have knowledge of the entire path to a destination.
Instead they use two methods:
1. Direction in which router or exit interface a packet should be forwarded.
2. Distance from its destination .
Distance-vector protocols are based on calculating the direction and distance to any link in a
network. "Direction" usually means the next hop address and the exit interface. "Distance" is a
measure of the cost to reach a certain node. The least cost route between any two nodes is the
route with minimum distance. Each node maintains a vector (table) of minimum distance to
every node. The cost of reaching a destination is calculated using various route metrics. RIP uses
the hop count of the destination whereas IGRP takes into account other information such as node
delay and available bandwidth.
Updates are performed periodically in a distance-vector protocol where all or part of a router's
routing table is sent to all its neighbors that are configured to use the same distance-vector
routing protocol. RIP supports cross-platform distance vector routing whereas IGRP is a Cisco
Systems proprietary distance vector routing protocol. Once a router has this information it is able
to amend its own routing table to reflect the changes and then inform its neighbors of the
changes. This process has been described as ‗routing by rumor‘ because routers are relying on
the information they receive from other routers and cannot determine if the information is
actually valid and true. There are a number of features which can be used to help with instability
and inaccurate routing information.
EGP and BGP are not pure distance-vector routing protocols because a distance-vector protocol
calculates routes based only on link costs whereas in BGP, for example, the local route
preference value takes priority over the link cost. Count-to-infinity problem The Bellman–Ford
algorithm does not prevent routing loops from happening and suffers from the count-to-infinity
problem. The core of the count-to-infinity problem is that if A tells B that it has a path
somewhere, there is no way for B to know if the path has B as a part of it. To see the problem
clearly, imagine a subnet connected like A–B–C–D–E–F, and let the metric between the routers
be "number of jumps". Now suppose that A is taken offline. In the vector-update-process B
notices that the route to A, which was distance 1, is down – B does not receive the vector update
from A. The problem is, B also gets an update from C, and C is still not aware of the fact that A
is down – so it tells B that A is only two jumps from C (C to B to A), which is false. This slowly
propagates through the network until it reaches infinity (in which case the algorithm corrects
itself, due to the relaxation property of Bellman–Ford).
RESULT:
Thus the case study about the different routing algorithms to select the network path with
its optimum and economical during data transfer was studied.
LAB MANUAL LP – CS22511
LP Rev. No : 00
Date : 05/07/2024
Sub Code & Sub Name : CS22511 Computer Networks Laboratory
Page: 114 of 118
Branch : CSE / AIDS Semester : V
13) File Transfer
AIM:
Algorithm
Server
Step4: Get the file name and stored into the BufferedReader.
Step6: If file is exists then FileReader read the content until EOF is reached.
Client
Step4: The object of a BufferReader class is used for storing data content which has been
File Server :
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
//Initialize Sockets
InetAddress IA = InetAddress.getByName("localhost");
OutputStream os = socket.getOutputStream();
long current = 0;
while(current!=fileLength){
current += size;
else{
current = fileLength;
bis.read(contents, 0, size);
os.write(contents);
os.flush();
socket.close();
ssock.close();
}}
File Client
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
//Initialize socket
InputStream is = socket.getInputStream();
int bytesRead = 0;
while((bytesRead=is.read(contents))!=-1)
bos.write(contents, 0, bytesRead);
bos.flush();
socket.close();
Output
server
E:\nwlab>java FileServer
E:\nwlab>client E:\
nwlab>java FileClient
E:\nwlab>
RESULT
Thus,the java program file transfer application using TCP Sockets was executed