Nothing Special   »   [go: up one dir, main page]

CS22511 CN Lab (S)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 114

EX 1: Study of Socket Programming

Aim: To study about Socket programming with client – server model

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.

State diagram for server and client model

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 −

1. The server instantiates a ServerSocket object, denoting which port number


communication is to occur on.
2. The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
3. After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server
and the port number. If communication is established, the client now has a Socket object
capable of communicating with the server.
5. On the server side, the accept() method returns a reference to a new socket on the server
that is connected to the client's socket.

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.

Stages for server:

1. Socket creation:
int sockfd = socket(domain, type, protocol)

sockfd: socket descriptor, an integer (like a file-handle)

domain: integer, communication domain e.g., AF_INET (IPv4 protocol) ,


AF_INET6 (IPv6 protocol)
type: communication type
SOCK_STREAM: TCP(reliable, connection oriented)
SOCK_DGRAM: UDP(unreliable, connectionless)
protocol: Protocol value for Internet Protocol(IP), which is 0. This is the same number
which appears on protocol field in the IP header of a packet.(man protocols
for more details)

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:

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

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:

int listen(int sockfd, int backlog);

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:

int new_socket= accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

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.

Stages for Client

1. Socket connection: Exactly same as that of server’s socket creation


Connect:
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

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.

Client Side Programming(IN JAVA)


1.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. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

2. Communication

To communicate over a socket connection, streams are used to both input and output the
data.

3. Closing the connection

The socket connection is closed explicitly once the message to server is sent.

Server Programming

1.Establish a Socket Connection

To write a server application two sockets are needed.

ServerSocket obj= new ServerSocket(int port);


Creates a server socket, bound to the specified port.
ServerSocket obj= new ServerSocket(int port, int backlog)
Creates a server socket and binds it to the specified local port number, with the specified
backlog.
ServerSocket obj= new ServerSocket(int port, int backlog, InetAddress bindAddr)
Create a server with the specified port, listen backlog, and local IP address to bind to.

 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.

Syntax: DataOutputStream data = new DataOutputStream(Socketobject.getOutpu


tStream());
getOutputStream() method is used to send the output through the socket.

The java.io.DataOuputStream.writeUTF(String str) method writes a string to the


underlying output stream using modified UTF-8 encoding.

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.

Syntax:DataInputStream inst = new DataInputStream(socketobject.getInputStream());

getInputStream() method is used to receive the output through the socket.

3. Close the Connection

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:

A) SENDING MESSAGE FROM CLIENT TO SERVER WITH TCP SOCKET

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{

public static void main(String args[])

{
try

{ ServerSocket ss = new

ServerSocket(1357); Socket s = ss.accept();

DataInputStream dis = new DataInputStream(s.getInputStream());

String str = (String)dis.readUTF();

System.out.println("msg sent by client is "+str);

ss.close();

}catch(Exception e)

System.out.println(e);

} } }
CLIENT:

import java.io.*;

import java.util.Scanner;

import java.net.*;

class client

public static void main(String args[])

{ try

{ Socket s = new Socket("localhost",1357);

Scanner var = new Scanner(System.in);

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

System.out.printf("enter msg : ");

dos.writeUTF(var.nextLine());

dos.flush(); dos.close(); s.close();


}

catch(Exception e)

System.out.println(e); } }}

EXECUTION PROCEDURE:

TERMINAL 1(server):

[login@cs-xServer tcp]$javac server.java

[login@cs-xServer tcp]$ java server

TERMINAL 2(client):

[login @cs-xServer tcp]$javac client.java

[login @cs-xServer tcp]$ java client

OUTPUT:

TERMINAL 1(server):

msg sent by client is hi

TERMINAL 2(client):

Enter msg :hi

RESULT:

Thus, the message was transferred successfully from client to server using TCP socket.
DOC/LP/01/28.02.02

EX 2 B) CHAT USING TCP SOCKET PROGRAMMING

AIM:

To implement a chat between client and server 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. 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:

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

class client3

public static Scanner sc=new Scanner(System.in);

public static void main(String ar[])

try

Socket s=new Socket("localhost",5678);

DataOutputStream dout=new DataOutputStream(s.getOutputStream());


DataInputStream din=new DataInputStream(s.getInputStream());

String str="",str1="";

while(!str.equals("end"))

System.out.println("enter msg to server");

str=sc.nextLine();

dout.writeUTF(str);

dout.flush();

str1=din.readUTF();

System.out.println("msg from server is"+str1);

}}

catch(Exception e){System.out.println(e);}

}}

SERVER:

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

class server3

public static void main(String ar[])

try{

ServerSocket s=new ServerSocket(5678);

Socket ss=s.accept();

DataOutputStream dout=new DataOutputStream(ss.getOutputStream());

DataInputStream din=new DataInputStream(ss.getInputStream());

Scanner sc=new Scanner(System.in);


String str="",str1=""; while(!

str.equals("end"))

str=din.readUTF();

System.out.println("msg from client is"+str);

System.out.println(" enter msg to client");

str1=sc.nextLine();

dout.writeUTF(str1);

dout.flush();

ss.close();

catch(Exception e){ System.out.println(e);}

}}

EXECUTION PROCEDURE:

TERMINAL 1(server):

[login@cs-xServer tcp]$javac serverchat.java

[login @cs-xServer tcp]$ java serverchat

TERMINAL 2(client):

[login @cs-xServer tcp]$javac clientchat.java

[login @cs-xServer tcp]$ java clientchat

OUTPUT:

TERMINAL 1(server):

msg from client is : hi server!

enter msg to client:hi client!


msg from client is : hello

enter msg to client:fine

end

TERMINAL 2(client):

enter msg to server:hi server!

msg from server is: hi client!

enter msg to server:hello

msg from server is: fine

end

RESULT:

Thus, the concept of chatting was successfully done using TCP – Socket Program.

DOC/LP/01/28.02.02

EX 2C) DATE AND TIME OF THE SERVER TO CLIENT

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

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

ServerSocket ss=new ServerSocket(1234);

Socket s=ss.accept();

Date d=new Date();

String str=new String("The current Date and Time is "+d);

DataOutputStream dos=new DataOutputStream(s.getOutputStream());

dos.writeUTF(str);

p.close();

s.close();

ss.close();

}}

CLIENT:

import java.net.*;

import java.io.*;
class dateclient

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

String str;

Socket s=new Socket("localhost",1234);

DataInputStream dis=new DataInputStream(s.getInputStream());

Str=dis.readUTF();

System.out.println("The current Date and time is "+str);

s.close();

}}

EXECUTION PROCEDURE:

TERMINAL 1(server):

[login@cs-xServer tcp]$ javac dateserver.java

[login @cs-xServer tcp]$ java dateserver

TERMINAL 1(client):

[login @cs-xServer tcp]$ javac dateclient.java

[login @cs-xServer tcp]$ java dateclient

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

EX 2D: ECHO SERVER AND CLIENT

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

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

String msg;

ServerSocket ss=new ServerSocket(1333);

Socket s=ss.accept();

DataInputStream dis=new DataInputStream(s.getInputStream());

Str=dis.readUTF();

System.out.println("The msg from client is "+str);

DataOutputStream dos=new DataOutputStream(s.getOutputStream());

dos.writeUTF(str);

p.close();

s.close();

ss.close();

}}

CLIENT:

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

class echoclient

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

Socket s=new Socket("localhost",1333);

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);

DataInputStream dis=new DataInputStream(s.getInputStream());

str=dis.readUTF();

System.out.println(“echoed msg is:”+str);

p.close();

s.close();

}}

EXECUTION PROCEDURE:

TERMINAL 1(server):

[login@cs-xServer tcp]$ javac echoserver.java

[login @cs-xServer tcp]$ java echoserver

TERMINAL 2(client):

[login @cs-xServer tcp]$ javac echoclient.java

[login @cs-xServer tcp]$ java echoclient

OUTPUT:

TERMINAL 1(server):

The msg from client is hi

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

Step1: Import java packages and create class file server.

Step2: Create a new server socket and bind it to the port.

Step3: Accept the client connection

Step4: Get the file name and stored into the BufferedReader.

Step5: Create a new object class file and realine.

Step6: If file is exists then FileReader read the content until EOF is reached.

Step7: Stop the program.

Client

Step1: Import java packages and create class file server.

Step2: Create a new server socket and bind it to the port.

Step3: Now connection is established.

Step4: The object of a BufferReader class is used for storing data content which has been

retrieved from socket object.

Step5 The connection is closed.

Step6: Stop the program.


RESULT:

Thus, the echo server and client were implemented successfully.

DOC/LP/01/28.02.02

Ex 3) Applications using UDP Sockets


A) SENDING MESSAGE FROM CLIENT TO SERVER:
AIM:
To send a simple message from client to server using UDP Socket.

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:

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

class udpserver

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

String msg;

byte buf[]=new byte[1024];

DatagramSocket s=new DatagramSocket(6000);


DatagramPacket dp=new DatagramPacket(buf,buf.length);

s.receive(dp);

msg=new String(dp.getData(),0,dp.getLength());

System.out.println("message from the client "+msg);

s.close();

}}

CLIENT:

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

class udpclient

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

String msg;

byte buf[]=new byte[1024];

DatagramSocket s=new DatagramSocket();

String host=”localhost”;

InetAddress ia=InetAddress.getLocalHost(host);

System.out.println("Enter the message to be sent :");

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

msg=b.readLine();

buf=msg.getBytes();

DatagramPacket dp=new new DatagramPacket(buf,buf.length,ia,6000);

s.send(dp);s.close();}}

EXECUTION PROCEDURE:

TERMINAL 1(server):
[login@cs-xServer udp]$ javac udpserver.java

[login @cs-xServer udp]$ java udpserver

TERMINAL 2(client):

[login @cs-xServer udp]$ javac udpclient.java

[login @cs-xServer udp]$ java udpclient

OUTPUT:

TERMINAL 1(server):

message from the client : hi!

TERMINAL 2(client):

Enter the message to be sent :Hi!

3B)CHAT BETWEEN CIENT AND SERVER


AIM:

To start a chat between client and server using UDP Socket.

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:

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

class udpserverchat

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

String msg;

byte buf[]=new byte[1024];

DatagramSocket s=new DatagramSocket(2000);

DatagramPacket dp=new DatagramPacket(buf,buf.length);

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

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;

System.out.println("message from the client: "+msg);

System.out.println("Enter the message to client: ");

msg=b.readLine();
buf=msg.getBytes();

DatagramPacket dp=new DatagramPacket(buf,buf.length,ia,1000);

s.send(dp);

}while(!(msg.equals("stop")));

s.close();

}}

CLIENT:

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

class udpclientchat

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

String msg;

byte buf[]=new byte[1024];

DatagramSocket s=new DatagramSocket(1000);

DatagramPacket dp=new DatagramPacket(buf,buf.length);

String host=”localhost”;

InetAddress ia=InetAddress.getLocalHost(host);

do

System.out.println("Enter the message to server :");

BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

msg=b.readLine();

buf=msg.getBytes();

DatagramPacket dp=new DatagramPacket(buf,buf.length,ia,2000);


s.send(dp);

if(msg.equals("stop"))

break;

s.receive(dp);

msg=new String(dp.getData(),0,dp.getLength());

System.out.println("message from the server "+msg);

}while(!(msg.equals("stop")));

s.close();

}}

EXECUTION PROCEDURE:

TERMINAL 1(server):

[login@cs-xServer udp]$ javac udpserverchat.java

[login @cs-xServer udp]$ java udpserverchat

TERMINAL 2(client):

[login @cs-xServer udp]$ javac udpclientchat.java

[login @cs-xServer udp]$ java udpclientchat

OUTPUT:

SERVER:

message from the client: hi!

Enter the message to client:

hi client!

message from the client: terminate now.

Enter the message to client

Stop
CLIENT:

Enter the message to server :

hi!

message from the server hi client!

Enter the message to server :

terminate now.

message from the server: stop

3C) DOMAIN NAME SYSTEM

AIM:

To resolve Domain name to IP Address and vice-versa with UDP socket.

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:

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

class dns_server{

public static void main(String args[])

try{

DatagramSocket server=new DatagramSocket(8240);

while(true)

byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

DatagramPacket receiver=newDatagramPacket(receivebyte,receivebyte.length);

server.receive(receiver);

String str=new String(receiver.getData());

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();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);

server.send(sender);

break;

else if(s.equals(name[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 dns_cli{

public static void main(String args[])

try
{

DatagramSocket client=new DatagramSocket();

InetAddress addr=InetAddress.getByName("127.0.0.1");

byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Domain name or IP address:");

String str=in.readLine();

sendbyte=str.getBytes();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,8240);

client.send(sender);

DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);

client.receive(receiver);

String s=new String(receiver.getData());

System.out.println("IP Address or DOMAIN

name:"+s.trim());

client.close();

catch(Exception e)

System.out.println(e);

} } }

EXECUTION PROCEDURE:

TERMINAL 1(server):

[login@cs-xServer udp]$ javac dns_server.java

[login @cs-xServer udp]$ java dns_server


TERMINAL 2(client):

[login @cs-xServer udp]$ javac dns_cli.java

[login @cs-xServer udp]$ java dns_cli

OUTPUT:

SERVER:

165.165.80.80

CLIENT:

Enter the Domain name or IP address:

165.165.80.80

IP Address or DOMAIN name:www.aptitudeguru.com

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:

Write a program to implement CRC and Bit Stuffing.

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:

a) Original Data. b) Stuffed Data. c) Received Data


SOURCE CODE:
import java.util.*;
public class SEFBS
{
public static void main(String[] args)
{
System.out.print("Enter the Binary message: ");
Scanner sn=new Scanner(System.in);
String data =
sn.nextLine(); String res =
new String(); String
out=new String(); int
counter = 0;
for(int i=0;i<data.length();i++)
{

if (data.charAt(i)!='1' && data.charAt(i)!='0')


{
System.out.println("Enter only Binary values!!!");
return;
}
if(data.charAt(i) == '1')
{
counter++;
res = res + data.charAt(i);
}
else
{
res = res + data.charAt(i);
counter = 0;
}
if(counter == 5)
{
res = res + '0';
counter = 0;
}
}
String inc="01111110"+res+"01111110";
System.out.println("The Message to be transfered: "
+inc); System.out.println("Seding Message ");
counter=0;
for(int i=0;i<res.length();i++)
{

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);
}
}

B) CYCLIC REDUNDANCY CHECK:


DESCRIPTION:
Whenever digital data is stored or interfaced, data corruption might occur. Since the beginning of
computer science, developers have been thinking of ways to deal with this type of problem. For serial
data they came up with the solution to attach a parity bit to each sent byte. This simple detection
mechanism works if an odd number of bits in a byte changes, but an even number of false bits in one
byte will not be detected by the parity check. To overcome this problem developers have searched for
mathematical sound mechanisms to detect multiple false bits.

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)

A) STOP AND WAIT PROTOCOL

AIM:

To simulate Stop and Wait protocol using TCP with Java.

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

public static void main(String args[])

try

ServerSocket ss = new ServerSocket(5050);

Socket s = ss.accept();

DataInputStream dis = new DataInputStream(s.getInputStream());

DataInputStream dis2 = new DataInputStream(System.in);


DataOutputStream dos = new DataOutputStream(s.getOutputStream());

String str,a;

do

System.out.println("Enter msg : ");

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
{

public static void main(String args[])

try

Socket s = new Socket("localhost",5050);

DataInputStream dis = new DataInputStream(s.getInputStream());

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

String str;

while(true)

str=(String)dis.readUTF();

System.out.println(str+"\nACK sent for "+str);

dos.writeUTF("ACK received for "+str);

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) :

[login@cs-xServer stop_wait]$ javac sender.java

[login @cs-xServer stop_wait]$ java sender

TERMINAL 2 (Receiver) :

[login @cs-xServer stop_wait]$ javac receiver.java

[login @cs-xServer stop_wait]$ java receiver

OUTPUT:

SENDER:

Enter msg :

hi

ACK received for hi

continue ?:yes

Enter msg :

hello

ACK received for hello

continue ?:end

RECEIVER:

hi

ACK sent for hi

hello

ACK sent for hello

B) SLIDING WINDOW PROTOCOL:

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.*;

public class sender

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

ServerSocket ss=new ServerSocket(5555);

Socket s=ss.accept();

DataInputStream in=new DataInputStream(System.in);

DataInputStream in1=new DataInputStream(s.getInputStream());

String sbuff[]=new String[8];

PrintStream p=new PrintStream(s.getOutputStream());;

int sptr=0,sws=8,nf,ano,i;

String ch;
do{

System.out.print("Enter the no of frames:");

nf=Integer.parseInt(in.readLine());
p.println(nf);

if(nf<sws)

System.out.println("Enter "+nf+" Messages to be send : \n");

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());

System.out.println("for "+ano+" frames");

sws+=nf;

else

System.out.println("no. of frames exceeds the window size");

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

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

Socket s=new Socket("localhost",5555);

DataInputStream in=new DataInputStream(s.getInputStream());

PrintStream p=new PrintStream(s.getOutputStream());

int i=0,rptr=-1,nf,rws=8;

String rbuf[]=new String[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();

System.out.println("The received frame "+rptr+" is : "+rbuf[rptr]);

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):

[login@cs-xServer slid_wind]$ javac sender.java

[login @cs-xServer slid_wind]$ java sender

TERMINAL 2(receiver):

[login @cs-xServer slid_wind]$ javac receiver.java

[login @cs-xServer slid_wind]$ java receiver

OUTPUT:

SENDER:

Enter the no of frames:2

Enter 2 Messages to be send

: hi
hello

Acknowledgement received

continue ? : no

RECEIVER:

The received frame 0 is : hi

The received frame 1 is : hello

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:

To simulate ARP (ADDRESS RESOLUTION PROTOCOL) AND RARP (REVERSE


ADDRESS RESOLUTION PROTOCOL) using UDP Socket.

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

public static void main(String args[])

try{

DatagramSocket server=new DatagramSocket(5050);

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"};

int port; String str,s;

byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

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

public static void main(String args[])

try

DatagramSocket client=new DatagramSocket();

InetAddress addr=InetAddress.getByName("127.0.0.1");

byte[] sendbyte=new byte[1024];

byte[] receivebyte=new byte[1024];

BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the MAC address or IP address:");

String str=in.readLine();
sendbyte=str.getBytes();

DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,5050);

client.send(sender);

DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);

client.receive(receiver);

String s=new String(receiver.getData());

System.out.println("IP Address or MAC address : "+s.trim());

client.close();

catch(Exception e)

System.out.println(e);

} }}

EXECUTION PROCEDURE:

TERMINAL 1 (Sender) :

[login@cs-xServer ex-5_arp_rarp]$ javac server.java

[login @cs-xServer ex-5_arp_rarp]$ java server

TERMINAL 2 (Receiver) :

[login @cs-xServer ex-5_arp_rarp]$ javac client.java

[login @cs-xServer ex-5_arp_rarp]$ java client

OUTPUT:

SERVER:

165.165.80.80

CLIENT:
Enter the MAC address or IP address:

165.165.80.80

IP address or MAC address : 3A-2B-89-11-02-55

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

-D Print a list of network interfaces.

-i Specify an interface on which to capture.

-c Specify the number of packets to receive.

-v, -vv, -vvv Increase the level of detail (verbosity).

-w Write captured data to a file.

-r Read captured data from a file.

Many other options and arguments can be used with tcpdump.

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):

# tcpdump host host1 and host2

2. Display traffic from a source or destination host only

To display traffic from only a source (src) or destination (dst) host:

# tcpdump src host

# tcpdump dst host

3. Display traffic for a specific protocol

Provide the protocol as an argument to display only traffic for a specific protocol, for example

tcp, udp, icmp, arp:

# tcpdump protocol

For example to display traffic only for the tcp traffic :

# tcpdump tcp

4. Filtering based on source or destination port

To filter based on a source or destination port:

# tcpdump src port ftp

# tcpdump dst port http

2.Netstat

Netstat is a common command line TCP/IP networking available in most versions of

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

screen (analogous to a Linux or UNIX for netstat reads as follows:

Displays protocol statistics and current TCP/IP network connections.

NETSTAT -a -b -e -n -o -p proto -r -s -v interval

-a Displays all connections and listening ports.


-b Displays the executable involved in creating each connection or listening port. In

some cases well-known executables host multiple independent components, and in

these cases the sequence of components involved in creating the connection or

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.

-e Displays Ethernet statistics. This may be combined with the -s option.

-n Displays addresses and port numbers in numerical form.

-o Displays the owning process ID associated with each connection.

-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.

-r Displays the routing table.

-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

creating the connection or listening port for all executables.

Interval Redisplays selected statistics, pausing interval seconds between each display. Press

CTRL+C to stop redisplaying statistics. If omitted, netstat will print the current

configuration information once.


Syntax

netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]

Parameters

Used without

parameters displays active TCP connections.

-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

received. This parameter can be combined with -s.

-n Displays active TCP connections, however, addresses and port numbers are

expressed numerically and no attempt is made to determine names.

-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.

The -p parameter can be used to specify a set of 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

information only once.

/? - Displays help at the command prompt.

3. Ifconfig

In Windows, ipconfig is a console application designed to run from the Windows

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]

[/showclassid Adapter] [/setclassid Adapter [ClassID]]

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,

such as installed network adapters, or logical interfaces, such as dial-up

connections.

/renew

[Adapter]

Renews DHCP configuration for all adapters (if an adapter is not specified)

or for a specific adapter if the Adapter parameter is included. This parameter

is available only on computers with adapters that are configured to obtain an

IP address automatically. To specify an adapter name, type the adapter name

that appears when you use ipconfig without parameters.

/release

[Adapter]

Sends a DHCPRELEASE message to the DHCP server to release the current

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

parameter is included. This parameter disables TCP/IP for adapters

configured to obtain an IP address automatically. To specify an adapter name,

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

Client service uses this information to resolve frequently queried names

quickly, before querying its configured DNS servers.

/registerdns

Initiates manual dynamic registration for the DNS names and IP addresses

that are configured at a computer. You can use this parameter to

troubleshoot a failed DNS name registration or resolve a dynamic update

problem between a client and the DNS server without rebooting the client

computer. The DNS settings in the advanced properties of the TCP/IP

protocol determine which names are registered in DNS.

/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

Adapter. This parameter is available only on computers with adapters that

are configured to obtain an IP address automatically.

/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

place of Adapter. This parameter is available only on computers with

adapters that are configured to obtain an IP address automatically. If a DHCP

class ID is not specified, the current class ID is removed.

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

Connection"

To renew a DHCP-assigned IP address configuration for only

the Local Area Connection adapter

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

Connection" TEST

To set the DHCP class ID for the Local Area Connection

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

for domains by querying the Domain Name System.

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

hop the packet makes during its route to the destination.

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]

over a maximum of 30 hops:

1 <1 ms <1 ms <1 ms 10.1.0.1

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

15 76 ms 112 ms 76 ms iy-f104.1e100.net [209.85.225.104]

Trace complete.

tracert -j 10.12.0.1 10.29.3.1 10.1.44.1 www.google.com


B) Capture ping and traceroute PDUs using a network protocol analyzer and examine

You can use Wireshark to capture network packets, but to capture and analyze packets
programmatically in Java, you can use the jNetPcap library.

Example in Java Using jNetPcap

First, include the jNetPcap library in your project.

Maven Dependency:

<dependency>

<groupId>org.jnetpcap</groupId>

<artifactId>jnetpcap</artifactId>

<version>1.4</version>

</dependency>

Java Code to Capture Packets

Here's an example Java code to capture packets:

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;

public class PacketCapture {

public static void main(String[] args) {

List<PcapIf> alldevs = new ArrayList<>(); // List of devices

StringBuilder errbuf = new StringBuilder(); // For any error msgs

int r = Pcap.findAllDevs(alldevs, errbuf);

if (r == Pcap.NOT_OK || alldevs.isEmpty()) {

System.err.printf("Can't read list of devices, error is %s", errbuf.toString());

return;

PcapIf device = alldevs.get(0); // Get the first device

System.out.printf("Choosing '%s' on your behalf:\n",

(device.getDescription() != null) ? device.getDescription()

: device.getName());
int snaplen = 64 * 1024; // Capture all packets, no

truncation int flags = Pcap.MODE_PROMISCUOUS; // capture

all packets int timeout = 10 * 1000; // 10 seconds in millis

Pcap pcap = Pcap.openLive(device.getName(), snaplen, flags, timeout, errbuf);

if (pcap == null) {

System.err.printf("Error while opening device for capture: %s", errbuf.toString());

return;

PcapPacketHandler<String> jpacketHandler = new PcapPacketHandler<>()

{ public void nextPacket(PcapPacket packet, String user) {

System.out.printf("Received packet at %s caplen=%-4d len=%-4d %s\n",

new java.util.Date(packet.getCaptureHeader().timestampInMillis()),

packet.getCaptureHeader().caplen(), // Length actually captured

packet.getCaptureHeader().wirelen(), // Original length

user

);

};

pcap.loop(10, jpacketHandler, "jNetPcap rocks!");


pcap.close();

Capture and Examine Ping and Traceroute PDUs

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:

ping example.com traceroute example.com

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

public static void main(String args[])

try

String str,ip;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

ip=br.readLine();
Runtime H = Runtime.getRuntime();

Process p = H.exec("ping "+ip);

InputStream in = p.getInputStream();

BufferedReader b = new BufferedReader(new InputStreamReader(in));

while((str=b.readLine())!=null)

System.out.println(" "+str);

catch(Exception e)

System.out.println(e);

} }}

EXECUTION:

[login@cs-xServer ping]$ javac pingserver.java

[login @cs-xServer ping]$ java pingserver

OUTPUT:

Enter the IP Address to be ping: 127.0.0.1

Pinging 127.0.0.1 with 32 bytes of data:

Reply from 127.0.0.1: bytes=32 time<1ms

TTL=128 Reply from 127.0.0.1: bytes=32

time<1ms TTL=128 Reply from 127.0.0.1:

bytes=32 time<1ms TTL=128 Reply from

127.0.0.1: bytes=32 time<1ms TTL=128 Ping

statistics for 127.0.0.1:


Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

Minimum = 0ms, Maximum = 0ms, Average = 0ms

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

public static void main(String args[])

try

String str,ip;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

ip=br.readLine();

Runtime H = Runtime.getRuntime();

Process p = H.exec("traceroute

"+ip); InputStream in =

p.getInputStream();

BufferedReader b = new BufferedReader(new InputStreamReader(in));


while((str=b.readLine())!=null)

System.out.println(" "+str);

} }

catch(Exception e)

System.out.println(e);

} }}

EXECUTION:

[login@cs-xServer traceroute]$ javac traceroute.java

[login@cs-xServer traceroute]$ java traceroute

OUTPUT:

Enter the IP Address to be traceroute : 127.0.0.1

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

EX 8) REMOTE METHOD INVOCATION

AIM:

To implement Remote Method Invocation with simple calculator application.

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:

public interface calculator extends java.rmi.Remote

public long add(long a,long b) throws java.rmi.RemoteException ;

public long sub(long a,long b) throws java.rmi.RemoteException ;

public long mul(long a,long b) throws java.rmi.RemoteException ;

public long div(long a,long b) throws java.rmi.RemoteException ;

calc_impl :

public class calc_imp extends java.rmi.server.UnicastRemoteObject implements calculator

public calc_imp() throws java.rmi.RemoteException

{
super();

public long add(long a,long b) throws java.rmi.RemoteException

return a+b;

public long sub(long a,long b) throws java.rmi.RemoteException

return a-b;

public long mul(long a,long b) throws java.rmi.RemoteException

return a*b;

public long div(long a,long b) throws java.rmi.RemoteException

return a/b;

calc_server :

import java.rmi.Naming;

public class calc_server

public calc_server()
{

try

calculator c=new calc_imp();

Naming.rebind("rmi://localhost:1099/CalculatorService",c);
}

catch(Exception e)

System.out.println("Trouble : "+e);

public static void main(String args[])

new calc_server();

calc_client :

import java.rmi.Naming;

import java.rmi.RemoteException;

import java.net.MalformedURLException;

import java.rmi.NotBoundException;

public class calc_client

public static void main(String[] args)

{
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:

[login@cs-xServer ex-8_rmi]$ javac calculator.java

[login @cs-xServer ex-8_rmi]$ javac calc_impl.java

[login @cs-xServer ex-8_rmi]$ javac calc_server.java

[login @cs-xServer ex-8_rmi]$ javac calc_client.java

[login @cs-xServer ex-8_rmi]$ rmic calc_impl

Terminal 2:

[login @cs-xServer ex-8_rmi]$ rmiregistry

Terminal 3 :

[login @cs-xServer ex-8_rmi]$ java calc_server

Terminal 4 :

[login @cs-xServer ex-8_rmi]$ java calc_client

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.*;

public class subnetting

{ public static void main(String[] args) throws IOException

{ System.out.print("Enter IP : ");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String ip=br.readLine();

String[] ipAddrParts=ip.split("\\.");

String checkclass=ipAddrParts[0];

int cc=Integer.parseInt(checkclass);

String mask=null;

if(cc>0 && cc<224)

if(cc<128)

mask="255.0.0.0";

if(cc>127 && cc<192)

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("NETWORK ADDRESS : "+networkAddr);

System.out.println("HOST ID : "+hostid);

}}

EXECUTION :

[login@cs-xServer ex-7_subnetting]$ javac subnetting.java

[login @cs-xServerex-7_subnetting]$ java subnetting

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

EX 10: CISCO PACKET TRACER

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.

A) Packet Tracer – Creating a New Topology

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.

Version: This lab is based on Packet Tracer 5.0.

Step 1: Start Packet Tracer


Step 2: Choosing Devices and Connections

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

Single click on the End Devices.

Single click on the Generic host.

Move the cursor into topology area. You will notice it turns into a plus “+” sign.

Single click in the topology area and it copies the device.

Add three more hosts.


Step 4: Building the Topology – Connecting the Hosts to Hubs and Switches

Adding a Hub

Select a hub, by clicking once on Hubs and once on a Generic hub.

Add the hub by moving the plus sign “+” below PC0 and PC1 and click once.

Connect PC0 to Hub0 by first choosing Connections.


Click once on the Copper Straight-through cable.

Perform the following steps to connect PC0 to Hub0:

1. Click once on PC0


2. Choose FastEthernet
3. Drag the cursor to Hub0
4. Click once on Hub0 and choose Port 0
5. Notice the green link lights on both the PC0 Ethernet NIC and the Hub0 Port 0 showing that the link is
active.

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

Select a switch, by clicking once on Switches and once on a 2950-24 switch.

Add the switch by moving the plus sign “+” below PC2 and PC3 and click once.
Connect PC2 to Hub0 by first choosing Connections.

Click once on the Copper Straight-through cable.

Perform the following steps to connect PC2 to Switch0:

1. Click once on PC2


2. Choose FastEthernet
3. Drag the cursor to Switch0
4. Click once on Switch0 and choose FastEthernet0/1
5. Notice the green link lights on PC2 Ethernet NIC and amber light Switch0 FastEthernet0/1 port. The
switch port is temporarily not forwarding frames, while it goes through the stages for the Spanning Tree
Protocol (STP) process.
6. After a about 30 seconds the amber light will change to green indicating that the port has entered the
forwarding stage. Frames can now forwarded out the switch port.

Note: Spanning Tree Protocol (STP) is discussed later.

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.

Click once on PC0.

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.)

The information is automatically saved when entered. To

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.

Host IP Address Subnet Mask

PC0 172.16.1.10 255.255.0.0

PC1 172.16.1.11 255.255.0.0

PC2 172.16.1.12 255.255.0.0

PC3 172.16.1.13 255.255.0.0

Verify the information

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.

Step 6: Connecting Hub0 to Switch0

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.

Move the Connections cursor over Hub0 and click once.


Select Port 5 (actual port does not matter).

Move the Connections cursor to Switch0.

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.

Step 7: Verifying Connectivity in Realtime Mode

Be sure you are in Realtime mode.


Select the Add Simple PDU tool used to ping devices..

Click once on PC0, then once on PC3.

The PDU Last Status should show as Successful.


Resetting the Network

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:

Click Delete in the PDU area.

Now, Power Cycle Devices and confirm the action.


Waiting for Spanning Tree Protocol (STP)

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.

Step 8: Verifying Connectivity in Simulation Mode

Be sure you are in Simulation mode.

Deselect all filters (All/None) and select only ICMP.


Select the Add Simple PDU tool used to ping devices..

Click once on PC0, then once on PC3.

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.

Step 9: Saving the Topology

Perform the following steps to save the topology (uses .pkt file extension).
Opening Existing Topologies

Opening Existing PT Topologies

B) CONNECT 2 LANS USING MULTI ROUTER TOPOLOGY WITH STATIC ROUTES


The main objective is to extend routing connection by using multiple routers. The concepts include IP addressing
and basic network routing principles. Connect two LANs topology. During router configuration attention is paid to
the types of interfaces as additional issues are involved with set-up. For example, the serial interfaces require
clocking mechanisms to be set correctly. Once the interfaces are working the ping command is used to check for
communication between LANs. The failure of communication illustrates the need for routes to be established inside
the routing infrastructure. Static routes are used to show how packets can be transported through any reasonable
route. It is run trace route on two different configurations to demonstrate the implementation of different routes.

-5) Cables with RJ- P

-
Configure Routers R1 and

configuration. NETWORK

TOPOLOGY:

NETWORK TOPOLOGY:

RESULT:

Thus, the study of CISCO PACKET TRACER was done successfully.


DOC/LP/01/28.02.02

LP – CS22511

LAB MANUAL LP Rev. No : 00

Date : 05/07/2024

Sub Code & Sub Name : CS22511 Computer Networks Laboratory Page: 99 of 118

Branch : CSE / AIDS Semester : V

EX 11: Study of Network simulator (NS).and Simulation of Congestion


Control Algorithms using NS

AIM:

To study about Network Simulation using NS2.

DESCRIPTION :

Network simulation is a technique whereby a software program models the behavior of


a network by calculating the interaction between the different network entities (routers, switches,
nodes, access points, links etc.). Most simulators use discrete event simulation - the modeling of
systems in which state variables change at discrete points in time. The behavior of the network
and the various applications and services it supports can then be observed in a test lab; various
attributes of the environment can also be modified in a controlled manner to assess how the
network / protocols would behave under different conditions.

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 a simulator object


set ns [new Simulator]

#Open the NAM trace file

set nf [open o.nam w]


$ns namtrace-all $nf

# create nodes

set n0 [$ns node]


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

# Setting Colors and Shape

$n0 color red


$n1 color green
$n2 color "#0000FF"
$n0 shape "box"

#Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 15ms DropTail


$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n0 $n1 1.7Mb 20ms DropTail

#Setting Color for Links

$ns duplex-link-op $n0 $n1 color "red"


$ns duplex-link-op $n1 $n2 color "blue"
$ns duplex-link-op $n0 $n2 color "green"

#Set Queue Size of link (n0-n2) with 10


$ns queue-limit $n0 $n2 10

#Define a 'finish' procedure

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
}

#Call the finish procedure

$ns at 1.0 "finish"

#Run the simulation

$ns run

NS-simple.tcl

#Create a simulator object

set ns [new Simulator]

#Define different colors for data flows (for NAM)

$ns color 1 Blue


$ns color 2 Red

#Open the NAM trace file

set nf [open out.nam w]


ns namtrace-all $nf

#Define a 'finish' procedure

proc finish {} {
global ns nf
$ns flush-trace

#Close the NAM trace file


close $nf
#Execute NAM on the trace file

exec nam out.nam &


exit 0
}

#Create four nodes

set n0 [$ns node]


set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 10ms DropTail


$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

#Set Queue Size of link (n2-n3) to 10

$ns queue-limit $n2 $n3 10

#Give node position (for NAM)

$ns duplex-link-op $n0 $n2 orient right-down


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

#Monitor the queue for link (n2-n3). (for NAM)

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

#Setup a TCP connection

set tcp [new Agent/TCP]


$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection

set ftp [new Application/FTP]


$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2

#Setup a CBR over UDP connection

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

#Schedule events for the CBR and FTP agents

$ns at 0.1 "$cbr start"


$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"

#Detach tcp and sink agents (not really necessary)

$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

#Call the finish procedure after 5 seconds of simulation time

$ns at 5.0 "finish"

#Print CBR packet size and interval

puts "CBR packet size = [$cbr set packet_size_]"


puts "CBR interval = [$cbr set interval_]"

#Run the simulation


$ns run

NS program - Simple Example :

#Create a simulator object


set ns [new Simulator]
#Open the NAM trace file
set nf [open o.nam w]
$ns namtrace-all $nf

# create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]

# Setting Colors and Shape


$n0 color red
$n1 color green
$n2 color "#0000FF"
$n0 shape "box"

#Create links between the nodes

$ns duplex-link $n0 $n2 2Mb 15ms DropTail


$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n0 $n1 1.7Mb 20ms DropTail

#Setting Color for Links


$ns duplex-link-op $n0 $n1 color "yellow"
$ns duplex-link-op $n1 $n2 color "blue"

#Set Queue Size of link (n0-n2) with 10


$ns queue-limit $n0 $n2 10

#Define a 'finish' procedure

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
}

#Call the finish procedure

$ns at 1.0 "finish"

#Run the simulation


$ns run

OUTPUT:

//DATA FLOW CODE

#Create a simulator object


set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red

#Open the NAM trace file


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

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace

#Close the NAM trace file


close $nf

#Execute NAM on the trace file


exec nam out.nam &
exit 0
}

#Create four nodes


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

#Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

#Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 10

#Give node position (for NAM)


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

#Monitor the queue for link (n2-n3). (for NAM)


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

#Setup a TCP connection


set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2

#Setup a CBR over UDP connection


set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

#Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"

#Detach tcp and sink agents (not really necessary)


$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"
#Print CBR packet size and interval
puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"
#Run the simulation
$ns run

OUTPUT – Simulation :
RESULT:

Thus, the Network Simulation was studied using NS2 successfully.


DOC/LP/01/28.02.02

LAB MANUAL LP – CS22511

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.

i. Link State routing

Aim: To study about link state routing algoritm

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:

1. Each node acts as both a transmitter and a receiver.

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

1. A packet can be delivered, it will (probably multiple times).

2. Since flooding naturally utilizes every path through the network, it will also use the shortest
path.

3. This algorithm is very simple to implement.


Disadvantages

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

iii. Distance vector :

In computer communication theory relating to packet-switched networks, a distance vector


routing protocol is one of the two major classes of routing protocols, the other major class being
the link-state protocol. Distance-vector routing protocols use the Bellman–Ford algorithm, Ford–
Fulkerson algorithm, or DUAL FSM (in the case of Cisco Systems’ protocols) to calculate paths.

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:

To write a java program for file transfer using TCP Sockets.

Algorithm

Server

Step1: Import java packages and create class file server.

Step2: Create a new server socket and bind it to the

port. Step3: Accept the client connection

Step4: Get the file name and stored into the BufferedReader.

Step5: Create a new object class file and realine.

Step6: If file is exists then FileReader read the content until EOF is reached.

Step7: Stop the program.

Client

Step1: Import java packages and create class file server.

Step2: Create a new server socket and bind it to the

port. Step3: Now connection is established.

Step4: The object of a BufferReader class is used for storing data content which has been

retrieved from socket object.

Step5 The connection is closed.

Step6: Stop the program.


Program

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;

public class FileServer

public static void main(String[] args) throws Exception

//Initialize Sockets

ServerSocket ssock = new ServerSocket(5000);

Socket socket = ssock.accept();

//The InetAddress specification

InetAddress IA = InetAddress.getByName("localhost");

//Specify the file

File file = new File("e:\\Bookmarks.html");

FileInputStream fis = new FileInputStream(file);

BufferedInputStream bis = new BufferedInputStream(fis);

//Get socket's output stream

OutputStream os = socket.getOutputStream();

//Read File Contents into contents array


byte[] contents;

long fileLength = file.length();

long current = 0;

long start = System.nanoTime();

while(current!=fileLength){

int size = 10000;

if(fileLength - current >= size)

current += size;

else{

size = (int)(fileLength - current);

current = fileLength;

contents = new byte[size];

bis.read(contents, 0, size);

os.write(contents);

System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");

os.flush();

//File transfer done. Close the socket connection!

socket.close();

ssock.close();

System.out.println("File sent succesfully!");

}}

File Client

import java.io.BufferedOutputStream;

import java.io.FileOutputStream;
import java.io.InputStream;

import java.net.InetAddress;

import java.net.Socket;

public class FileClient {

public static void main(String[] args) throws Exception{

//Initialize socket

Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);

byte[] contents = new byte[10000];

//Initialize the FileOutputStream to the output file's full path.

FileOutputStream fos = new FileOutputStream("e:\\Bookmarks1.html");

BufferedOutputStream bos = new BufferedOutputStream(fos);

InputStream is = socket.getInputStream();

//No of bytes read in one read() call

int bytesRead = 0;

while((bytesRead=is.read(contents))!=-1)

bos.write(contents, 0, bytesRead);

bos.flush();

socket.close();

System.out.println("File saved successfully!");

Output

server

E:\nwlab>java FileServer

Sending file ... 9% complete!

Sending file ... 19% complete!


Sending file ... 28% complete!

Sending file ... 38% complete!

Sending file ... 47% complete!

Sending file ... 57% complete!

Sending file ... 66% complete!

Sending file ... 76% complete!

Sending file ... 86% complete!

Sending file ... 95% complete!

Sending file ... 100% complete!

File sent successfully!

E:\nwlab>client E:\

nwlab>java FileClient

File saved successfully!

E:\nwlab>

RESULT

Thus,the java program file transfer application using TCP Sockets was executed

You might also like