0% found this document useful (0 votes)
20 views68 pages

231CS42B Networks Laboratory

The document is a lab manual for a Networks Laboratory course under the Department of Artificial Intelligence and Data Science at an AICTE approved institution. It outlines the vision and mission of the department, course objectives, experiments, and expected outcomes for students, focusing on network commands, socket programming, and various network protocols. The manual includes detailed procedures for using tools like tcpdump and writing programs for HTTP clients and echo servers.

Uploaded by

geetha.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views68 pages

231CS42B Networks Laboratory

The document is a lab manual for a Networks Laboratory course under the Department of Artificial Intelligence and Data Science at an AICTE approved institution. It outlines the vision and mission of the department, course objectives, experiments, and expected outcomes for students, focusing on network commands, socket programming, and various network protocols. The manual includes detailed procedures for using tools like tcpdump and writing programs for HTTP clients and echo servers.

Uploaded by

geetha.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

An Autonomous Institution

Approved by AICTE, Affiliated to Anna University, Chennai.


ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

LAB MANUAL
COURSE CODE : 231CS42B
COURSE NAME : NETWORKS LABORATORY
YEAR/SEM : II/IV
PREPARED BY,
J.CINDHAMANI, M.Tech(SoftTech).,
J.JAYALAKSHMI, M.E(CSE).,
DEPT OF AI&DS

VISION

To promote centre of excellence through effectual Teaching and Learning, imparting the contemporary
knowledge centric education through innovative research in multidisciplinary fields.

MISSION

M1 - To impart quality technical skills through practicing, knowledge updating in recent technology
and produce professionals with multidisciplinary and leadership skills.
M2 - To promote innovative thinking for design and development of software products of varying
complexity with intelligence to fulfill the global standards and demands
M3 - To inculcate professional ethics among the graduates and to adapt the changing technologies
through lifelong learning
PROGRAMME OUTCOMES (POs)
POs Programme Outcomes (POs)

Engineering Knowledge: Apply knowledge of mathematics, natural science, computing,


PO1 engineering fundamentals and an engineering specialization as specified in WK1 to WK4
respectively to develop to the solution of complex engineering problems.

Problem Analysis: Identify, formulate, review research literature and analyze complex engineering
problems reaching substantiated conclusions with consideration for sustainable development. (WK1
PO2
to WK4)

Design/Development of Solutions: Design creative solutions for complex engineering problems and
design/develop systems/components/processes to meet identified needs with consideration for the public
PO3 health and safety, whole-life cost, net zero carbon, culture, society and environment as required. (WK5)

Conduct Investigations of Complex Problems: Conduct investigations of complex engineering problems


PO4 using research-based knowledge including design of experiments, modelling, analysis & interpretation of
data to provide valid conclusions. (WK8).

Engineering Tool Usage: Create, select and apply appropriate techniques, resources and modern
PO5 engineering & IT tools, including prediction and modelling recognizing their limitations to solve complex
engineering problems. (WK2 and WK6)

The Engineer and The World: Analyze and evaluate societal and environmental aspects while solving
PO6 complex engineering problems for its impact on sustainability with reference to economy, health, safety,
legal framework, culture and environment. (WK1, WK5, and WK7).

Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and inclusion;
PO7 adhere to national & international laws. (WK9)

Individual and Collaborative Team work: Function effectively as an individual, and as a member or leader
PO8
in diverse/multi-disciplinary teams.

Communication: Communicate effectively and inclusively within the engineering community and
society at large, such as being able to comprehend and write effective reports and design documentation,
PO9 make effective presentations considering cultural, language, and learning differences

Project Management and Finance: Apply knowledge and understanding of engineering management
PO10 principles and economic decision-making and apply these to one’s own work, as a member and leader in
a team, and to manage projects and in multidisciplinary environments.

Life-Long Learning: Recognize the need for, and have the preparation and ability for i)
Independent and life-long learning ii) Adaptability to new and emerging technologies
PO11 and iii)Critical thinking in the broadest context of technological change. (WK8)
COURSE OBJECTIVES
The student should be made to:
• Understand the techniques of network commands and Learn socket programming.
• Implement problems using and analyze various network protocols
• Know how to apply simulation tools
LIST OF EXPERIMENTS
Ex.
NAME OF THE EXERCISE(s) CO
No.
LEARN TO USE COMMANDS LIKE TCPDUMP,
NETSTAT, IFCONFIG, NSLOOKUP AND TRACE
1 ROUTE. CAPTURE PING AND TRACE ROUTE CO1
PDUS USING A NETWORK PROTOCOL
ANALYZER AND EXAMINE.
WRITE A HTTP WEB CLIENT PROGRAM TO
2 DOWNLOAD A WEB PAGE USING TCP SOCKETS. CO2

APPLICATIONS USING TCP SOCKETS LIKE:


A) ECHO CLIENT AND ECHO SERVER
3 CO2
B) CHAT
C) FILE TRANSFER

4 SIMULATION OF DNS USING UDP SOCKETS. CO2

USE A TOOL LIKE WIRESHARK TO CAPTURE


5 PACKETS AND EXAMINE THE PACKETS CO1

WRITE A CODE SIMULATING ARP /RARP


6 PROTOCOLS. CO2

A) STUDY OF NETWORK SIMULATOR (NS) B)


SIMULATION OF CONGESTION CONTROL
7 CO3
ALGORITHMS USING NS.

STUDY OF TCP/UDP PERFORMANCE USING


8 SIMULATION TOOL. CO3

SIMULATION OF DISTANCE VECTOR/ LINK


9 STATE ROUTING ALGORITHM. CO3

SIMULATION OF AN ERROR CORRECTION CODE


10 (LIKE CRC) CO2

IMPLEMENTATIONS OF STOP AND WAIT


11 PROTOCOL AND SLIDING WINDOW PROTOCOL CO2

WRITE A CODE SIMULATING GO BACK N ARQ.


12 CO2
CASE STUDY / MINI PROJECT CO3
13
COURSE OUTCOMES

At the end of the course, the student should be able to

Course
CO Statements
Outcome
Identify the basic network tools and packet analyzers to monitor and
CO1
troubleshoot networks.
CO2 Apply the socket programs to simulate network protocols and services.
Simulate and evaluate network protocols using simulation tools.
CO3
CO-PO/PSO MAPPING

Course
Outco
me
CO1 3 3 2 - - - - 1 - - 1 3 2 -
CO2 3 3 2 - - 2 1 - - - 1 3 2 1
CO3 3 3 2 - - 2 1 - - - 1 3 2 1
CO 3 3 2 - - 2 1 1 - - 1 3 2 1

1 – Low 2 – Medium 3 – High

LIST OF EQUIPMENTS / SOFTWARE REQUIRED

Sl. Quantity Quantity Deficiency


Description of Equipment
No required (R) Available (A) (R-A)
Standalone Desktops with Windows or Linux
1 30 30 Nil
OS
C/C++/Java, Network Simulator like NS2 /
2 30 30 Nil
Glomosim / OPNET/ Packet Tracer
EXP:NO:1
LEARN TO USE COMMANDS LIKE TCPDUMP, NETSTAT, IFCONFIG, NSLOOKUP
AND TRACEROUTE. CAPTURE PING AND TRACE ROUTE PDUS USING A
NETWORK PROTOCOL ANALYZER AND EXAMINE.

Aim:
To use commands like tcpdump, netstat, ifconfig, nslookup and trace route. Capture ping and
trace route PDUs using a network protocol analyzer and examine.

1. Tcpdump
Tcpdump is a command line utility that allows you to capture and analyze network traffic going
through your system.
Procedure
Check if tcpdump is installed on your system
$ which tcpdump
/usr/sbin/tcpdump
Iftcpdump is not installed,
$ sudo apt install tcpdump
To get Supervisor Privilege
$ su
(and password 123456)
$ sudo –i to change #
($ is changed to # and the commands can be executed in supervisor)
Capturing packets with tcpdump
Use the command tcpdump -D to see which interfaces are available for capture.
[root@localhost cse]# tcpdump -D
1.nflog (Linux netfilter log (NFLOG) interface)
2.nfqueue (Linux netfilter queue (NFQUEUE) interface)
3.usbmon1 (USB bus number 1)
4. enp2s0
5. usbmon2 (USB bus number 2)
6. any (Pseudo-device that captures on all interfaces)
7.lo [Loopback]
Capture all packets in any interface by running this command:
[root@localhost cse]# tcpdump -i any2
06:03:58.258143 ARP, Request who-has 172.16.51.87 tell 172.16.22.25, length 46
06:03:58.258225 ARP, Request who-has 172.16.51.88 tell 172.16.22.25, length 46
06:03:58.260828 ARP, Request who-has 172.16.51.122 tell 172.16.22.25, length 46
06:03:58.260903 ARP, Request who-has 172.16.51.123 tell 172.16.22.25, length 46
^C
5244 packets captured

1
59636 packets received by filter
54378 packets dropped by kernel
(Press ctrl+C to stop execution)
Filter packets based on the source or destination IP Address
[root@localhost ]#tcpdump -i any -c5 -nn src 172.16.20.138
6:10:30.712414 ARP, Request who-has 172.16.16.16 tell 172.16.20.138, length 28
06:10:31.483765 IP 172.16.20.138.47997 > 51.158.186.98.123: NTPv4, Client, length 48
5 packets captured
5 packets received by filter
0 packets dropped by kernel
[root@localhost ]#tcpdump -i any -c5 -nn dst 172.16.20.139
6:10:30.712414 ARP, Request who-has 172.16.16.16 tell 172.16.20.138, length 28
06:10:31.483765 IP 172.16.20.138.47997 > 51.158.186.98.123: NTPv4, Client, length 48
5 packets captured
5 packets received by filter
0 packets dropped by kernel

Ping command:

2. netstat
netstat (network statistics) is a command line tool for monitoring network connections both
incoming
and outgoing as well as viewing routing tables, interface statistics etc.

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

4. nslookup
nslookup (stands for “Name Server Lookup”) is a useful command for getting information from
DNS server. It is a network administration tool for querying the Domain Name System (DNS) to
obtain undertakes from its source to its destination.

3
5. Traceroute:

RESULT:
Thus the commands like tcpdump, netstat, ifconfig, nslookup and trace route are examined
successfully.

4
EXP:NO:2
WRITE A HTTP WEB CLIENT PROGRAM TO DOWNLOAD A WEB PAGE USING
TCP SOCKET

AIM:
To Write a HTTP web client program to download a web page using TCP sockets.

ALGORITHM:
CLIENT SIDE:
1) Start the program.
2) Create a socket which binds the Ip address of server and the port address to acquire
service.
3) After establishing connection send the url to server.
4) Open a file and store the received data into the file.
5) Close the socket.
6) End the program.

SERVER SIDE:
1) Start the program.
2) Create a server socket to activate the port address.
3) Create a socket for the server socket which accepts the connection.
4) After establishing connection receive url from client.
5) Download the content of the url received and send the data to client.
6) Close the socket.
7) End the program.

PROGRAM:
SERVER:
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {

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


ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
socket=server.accept();

5
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian); JFrame f =
new JFrame("Server"); ImageIcon icon = new
ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true); }}

CLIENT:
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;

public class Client {


public static void main(String[] args) {
Socket soc = null;
BufferedImage img = null;

try {
// Establishing connection to the server
soc = new Socket("localhost", 4000);
System.out.println("Client is running. Connected to server.");

// Reading image from disk


File imageFile = new File("digital_image_processing.jpg");
if (!imageFile.exists()) {
System.out.println("Image file not found.");
return;

6
}
img = ImageIO.read(imageFile);
System.out.println("Reading image from disk.");

// Convert image to byte array


ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();

// Sending image to server


System.out.println("Sending image to server.");
OutputStream out = soc.getOutputStream();

DataOutputStream dos = new DataOutputStream(out);

// Send image length and data


dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server.");

// Close streams
dos.close();
out.close();

} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
// Ensure the socket is closed
try {
if (soc != null && !soc.isClosed()) {
soc.close();
System.out.println("Connection closed.");
}
} catch (IOException e) {
System.out.println("Error closing socket: " + e.getMessage());
}
}
}

7
OUTPUT:

SERVER:

CLIENT:

RESULT:
Thus the program to write a HTTP web client to download a web page using TCP sockets
has been executed and verified successfully

8
EXP:NO:3A
APPLICATIONS USING TCP SOCKETS LIKE: A) ECHO CLIENT AND ECHO
SERVER

AIM:

To write a socket program for implementation of echo client and server.

ALGORITHM:

CLIENT SIDE

1. Start the program.

2. Create a socket which binds the Ip address of server and the port address to acquire

service.

3. After establishing connection send a data to server.

4. Receive and print the same data from server.

5. Close the socket.

6. End the program.

SERVER SIDE

1. Start the program.

2. Create a server socket to activate the port address.

3. Create a socket for the server socket which accepts the connection.

4. After establishing a connection, receive the data from the client.

5. Print and send the same data to the client.

6. Close the socket.

7. End the program.

9
PROGRAM:

ECHO CLIENT:

import java.io.*;
import java.net.*;
public class eclient
{
public static void main(String args[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("localhost",8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
do
{
System.out.println("client");
line=is.readLine();
os.println(line);
if(!line.equals("exit"))
System.out.println("server:"+is1.readLine());
}while(!line.equals("exit"));
}
catch(IOException e)
{
System.out.println("socket closed");
}}}

ECHO SERVER:
import java.io.*;
import java.net.*;
import java.lang.*;
public class eserver

10
{
public static void main(String args[])throws IOException
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
System.out.println("msg received and sent back to client");
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

OUTPUT:

ECHO SERVER:

11
ECHO CLIENT:

RESULT:

Thus the program to write a socket program for implementation of echo client and server has
been executed and verified successfully.

12
EXP:NO:3B
APPLICATIONS USING TCP SOCKETS LIKE: CHAT

AIM:

To write a client-server application for chat using TCP.

ALGORITHM:

CLIENT

1. Start the program

2. Include necessary package in java

3. To create a socket in client to server.

4. The client establishes a connection to the server.

5. The client accept the connection and to send the data from client to server.

6. The client communicates the server to send the end of the message

7. Stop the program.

SERVER

1. Start the program

2. Include necessary package in java

3. To create a socket in server to client

4. The server establishes a connection to the client.

5. The server accept the connection and to send the data from server to client and

6. vice versa

7. The server communicate the client to send the end of the message.

8. Stop the program.

13
PROGRAM:

TCP SERVER1:

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

public class TCPserver1 {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(9999)) {
System.out.println("Server started. Waiting for a client...");

try (Socket clientSocket = serverSocket.accept();


BufferedReader clientInput = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter clientOutput = new PrintWriter(clientSocket.getOutputStream(), true)) {

System.out.println("Client connected!");

String line;
do {
line = clientInput.readLine(); // Read from client
if (line == null) break; // Handle client disconnection

System.out.println("Client: " + line);


System.out.print("Server: ");

String response = userInput.readLine(); // Read from server console


clientOutput.println(response);

} while (!line.equalsIgnoreCase("quit"));

System.out.println("Connection closed.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
TCP CLIENT1:
import java.net.*;
import java.io.*;

public class TCPclient1 {

14
public static void main(String[] args) {
try (Socket socket = new Socket("192.168.23.196", 9999);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader serverInput = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter serverOutput = new PrintWriter(socket.getOutputStream(), true)) {

System.out.println("Connected to the server!");


String line;

do {
System.out.print("Client: ");
line = userInput.readLine(); // Read user input

if (line == null) break; // Exit if input is null

serverOutput.println(line); // Send to server

String serverResponse = serverInput.readLine(); // Read server response

if (serverResponse == null) {
System.out.println("Server disconnected.");
break;
}

System.out.println("Server: " + serverResponse);


} while (!line.equalsIgnoreCase("quit"));

System.out.println("Connection closed.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

15
OUTPUT:

TCPSERVER1:

TCPCLIENT1:

RESULT:

Thus the program to write a client-server application for chat using TCP has been executed and
verified successfully.

16
EXP:NO:3C
APPLICATIONS USING TCP SOCKETS LIKE: FILE TRANSFER

EXP:NO:3C
APPLICATIONS USING TCP SOCKETS LIKE: FILE TRANSFER

AIM:

To Perform File Transfer in Client & Server Using TCP/IP.

ALGORITHM:

CLIENT SIDE

1. Start.

2. Establish a connection between the Client and Server.

3. Socket ss=new Socket(InetAddress.getLocalHost(),1100);

4. Implement a client that can send two requests.

i) To get a file from the server.

ii) To put or send a file to the server.

5. After getting approval from the server ,the client either get file from the server or send

6. file to the server.

SERVER SIDE

1. Start.

2. Implement a server socket that listens to a particular port number.

3. Server reads the filename and sends the data stored in the file for the‘get’ request.

4. It reads the data from the input stream and writes it to a file in theserver for the ‘put’

instruction.

5. Exit upon client’s request.

6. Stop.

17
PROGRAM:

SERVER:

import java.net.*;
import java.io.*;
public class FileServer
{
public static void main (String [] args ) throws IOException {
ServerSocket servsock = new ServerSocket(13267);
while (true)
{
System.out.println("Waiting..."); Socket sock =
servsock.accept(); System.out.println("Accepte connection : " + sock);
File myFile = new File("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}}}

CLIENT:
import java.net.*;
import java.io.*;

public class FileClient {


public static void main(String[] args) throws IOException {
int filesize = 6022386; // File size hardcoded temporarily
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;

// Connect to server on localhost, port 13267


Socket sock = new Socket("192.168.23.196", 13267);
System.out.println("Connecting...");

byte[] mybytearray = new byte[filesize];


InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("Source.pdf");
BufferedOutputStream bos = new BufferedOutputStream(fos);

// Read data in chunks

18
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;

// Use a loop to read until the end of the file


while (bytesRead > -1) {
bytesRead = is.read(mybytearray, current, mybytearray.length - current);
if (bytesRead >= 0) current += bytesRead;
}

// Write the data to the output file


bos.write(mybytearray, 0, current);
bos.flush();

// Calculate time taken for transfer


long end = System.currentTimeMillis();
System.out.println("File transfer time: " + (end - start) + " milliseconds");

// Close all streams and socket


bos.close();
sock.close();
}
}

OUTPUT:

SERVER:

CLIENT:

19
RESULT:

Thus the program to Perform File Transfer in Client & Server Using TCP/IP has been executed
and verified successfully.

20
EXP:NO:4
SIMULATION OF DNS USING UDP SOCKET

AIM:

To write a program to Simulation of DNS using UDP sockets..

ALGORITHM:

1.Start the program.

2.Get the frame size from the user

3.To create the frame based on the user request.

4.To send frames to server from the client side.

5.If your frames reach the server it will send ACK signal to client otherwise it will

send NACK signal to client.

6.Stop the program

PROGRAM:

SERVER:

import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{

21
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true){
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData()); InetAddress ipaddress =
recvpack.getAddress(); int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent = ip[indexOf
(hosts, sen)]; else capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata, senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}

22
}
CLIENT:
import java.io.*; import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata =new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();

23
}
}

OUTPUT:

SERVER:

CLIENT:

RESULT:

Thus the program perform to Simulation of DNS using UDP sockets has been executed and
verified successfully.

24
EXP:NO:5
USE A TOOL LIKE WIRESHARK TO CAPTURE PACKETS AND EXAMINE THE
PACKETS

Aim :

To implement the code to capture packets and examine the packets using wireshark.

Procedure:

1. A network packet analyzer will try to capture network packets and tries to display that packet
data as detailed as possible.

2. Identifying and analyzing protocols.

3. Identifying source & destination of traffic.

Step 1:Go to https://www.wireshark.org/download.html to visit the Wireshark download page.


You must ensure that you use the full URL.
The output will look similar to the following:

Step 2:

Start the Wireshark application. When Wireshark is first run, a default, or blank window is
shown. To list the available network interfaces, select the Capture->Interfaces menu option.

25
Generate some network traffic with a Web Browser, such as Internet Explorer or Chrome. Your
Wireshark window should show the packets, and now look something like.

To stop the capture, select the Capture->Stop menu option, Ctrl+E, or the Stop toolbar button.
What you have created is a Packet Capture or ‘pcap’, which you can now view and analyse using
the Wireshark interface, or save to disk to analyse later.

The capture is split into 3 parts:

1. Packet List Panel – this is a list of packets in the current capture. It colours the packets based
on the protocol type. When a packet is selected, the details are shown in the two panels below.

26
2. Packet Details Panel – this shows the details of the selected packet. It shows the different
protocols making up the layers of data for this packet. Layers include Frame, Ethernet, IP,
TCP/UDP/ICMP, and application protocols such as HTTP.

3. Packet Bytes Panel – shows the packet bytes in Hex and ASCII encodings. To select more
detailed options when starting a capture, select the Capture->Options menu option, or Ctrl+K, or
the Capture Options button on the toolbar (the wrench).

Some of the more interesting options are:


Capture Options > Interface - Again the important thing is to select the correct Network
Interface to capture traffic through.
Capture Options > Capture File – useful to save a file of the packet capture in real time, in
case of a system crash.
Display Options > Update list of packets in real time – A display option, which should be
checked if you want to view the capture as it happens (typically switched off to capture straight
to a file, for later analysis).
Name Resolution > MAC name resolution – resolves the first 3 bytes of the MAC Address,
the Organisation Unique Identifier (OUI), which represents the Manufacturer of the Card.
Name Resolution > Network name resolution – does a DNS lookup for the IP Addresses
captured, to display the network name. Set to off by default, so covert scans do not generate
this DNS traffic, and tip off who’s packets you are sniffing.

27
Make sure the MAC name resolution is selected. Start the capture, and generate some Web
traffic
again, then stop the capture.

Step 3: Wireless Display captures

Wireshark automatically generates a Display Filter, and applies it to the capture. The filter is
shown in the Filter Bar, below the button toolbar. Only packets captured with a Source Port of
the value selected should be displayed. The window should be similar to that shown in Figure 6.
This same process can be performed on most fields within Wireshark, and can be used to include
or exclude traffic.

Step 4:By using this we can capture the http ,So we can find the User name and login

28
29
RESULT:

Thus the implemention of code to capture packets and examine the packets using wireshark has
done successfully.

30
EXP:NO:6
WRITE A CODE SIMULATING ARP/RARP PROTOCOL

Aim:

To write a program in java to simulate ARP protocols.

Algorithm:

Step 1 : Start the program

Step 2 : In Client

a. Start the program

b. Using socket connection is established between client and server.

c. Get the IP address to be converted into MAC address.

d. Send this IP address to server.

e. Server returns the MAC address to client.

Step 3: In Server

a.Start the program

b.Accept the socket which is created by the client.

c.Server maintains the table in which IP and corresponding MAC addresses are stored.

d.Read the IP address which is send by the client.

e.Map the IP address with its MAC address and return the MAC address to client.

Step 4: Stop the program

Program

Client:

import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{

31
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",5604);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Server:

import java.io.*;
import
java.net.*;
import
java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new
ServerSocket(5604);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new
DataOutputStream(obj1.getOutputStream()); String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{

32
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:

RESULT:

Thus the program in java to simulate ARP protocols has been executed and verified successfully.

33
EXP:NO:7A
STUDY OF NETWORK SIMULATOR (NS)

AIM:

To study Network Simulator in detail.

INTRODUCTION :

Network Simulator (Version 2), widely known as NS2, is simply an eventdriven simulation tool
that has proved useful in studying the dynamic nature of communication networks. Simulation of
wired as well as wireless network functions and protocols (e.g., routing algorithms, TCP, UDP)
can be done using NS2. In general, NS2 provides users with a way of specifying such network
protocols and simulating their corresponding behaviors. Due to its flexibility and modular nature,
NS2 has gained constant popularity in the networking research community since its birth in 1989.
Ever since, several revolutions and revisions have marked the growing maturity of the tool, thanks
to substantial contributions from the players in the field. Among these are the University of
California and Cornell University who developed the REAL network simulator, 1 the foundation
which NS is based on. Since 1995 the Defense Advanced Research Projects Agency (DARPA)
supported development of NS through the Virtual InterNetwork Testbed (VINT) project currently
the National Science Foundation (NSF) has joined the ride in development. Last but not the least,
the group of Researchers and developers in the community are constantly working to keep NS2
strong and versatile.

BASIC ARCHITECTURE

Figure shows the basic architecture of NS2. NS2 provides users with executable command ns
which take on input argument, the name of a Tcl simulation scripting file. Users are feeding the

34
name of a Tcl simulation script (which sets up a simulation) as an input argument of an NS2
executable command ns.

In most cases, a simulation trace file is created, and is used to plot graph and/or to create
animation. NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend) of the simulation
objects, the OTcl sets up simulation by assembling and configuring the objects as well as
scheduling discrete events (i.e., a frontend).

The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object, variables in the
OTcl domains are sometimes referred to as handles. Conceptually, a handle (e.g., n as a Node
handle) is just a string (e.g., _o10) in the OTcl domain, and does not contain any functionality.
Instead, the functionality (e.g., receiving a packet) is defined in the mapped C++ object (e.g., of
class Connector). In the OTcl domain, a handle acts as a frontend which interacts with users and
other OTcl objects. It may define its own procedures and variables to facilitate the interaction.
Note that the member procedures and variables in the OTcl domain are called instance procedures
(instprocs) and instance variables (instvars), respectively. Before proceeding further, the readers
are encouraged to learn C++ and OTcl languages. NS2 provides a large number of built-in C++
objects.

It is advisable to use these C++ objects to set up a simulation using a Tcl simulation script.
However, advance users may find these objects insufficient. They need to develop their own C++
objects, and use a OTcl configuration interface to put together these objects. After simulation, NS2
outputs either text-based or animation-based simulation results. To interpret these results
graphically and interactively, tools such as NAM (Network AniMator) and XGraph are used. To
analyze a particular behavior of the network, users can extract a relevant subset of text-based data
and transform it to a more conceivable presentation.

CONCEPT OVERVIEW :
ns uses two languages because simulator has two different kinds of things it needs to do. On one
hand, detailed simulations of protocols require a systems programming language which can
efficiently manipulate bytes, packet headers and implement algorithms that run over large data
sets. For these tasks run-time speed is important and turn-around time (run simulation, find bug,

35
fix bug, recompile, re-run) is less important. On the other hand, a large part of network research
involves slightly varying parameters or configurations, or quickly exploring number of scenarios.
In these cases, iteration time (change the model and re-run) is more important. Since
configuration runs once (at the beginning of the simulation), run-time of this part of the task is
less important. ns meets both of these needs with two languages, C++ and OTcl.

BASIC COMMANDS IN NS2

Create event scheduler

set ns [new Simulator]

Trace packets on all links

set nf [open out.nam w]

$ns trace-all $nf

$ns namtrace-all $nf

Nodes

set n0 [$ns node]

set n1 [$ns node]

Links and queuing

$ns duplex-link $n0 $n1 <bandwidth> <delay> <queue_type>

<queue_type>: DropTail, RED, etc.

$ns duplex-link $n0 $n1 1Mb 10ms RED

Creating a larger topology

for {set i 0} {$i < 7} {incr i} {

set n($i) [$ns node]

for {set i 0} {$i < 7} {incr i} {

$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms RED

36
}

Link failures

$ns rtmodel-at <time> up|down $n0 $n1

Creating UDP connection

set udp [new Agent/UDP]

set null [new Agent/Null]

$ns attach-agent $n0 $udp

$ns attach-agent $n1 $null

$ns connect $udp $null

Creating Traffic (On Top of UDP)

set cbr [new Application/Traffic/CBR]

$cbr set packetSize_ 500

$cbr set interval_ 0.005

$cbr attach-agent $udp

Post-Processing Procedures

proc finish {}

global ns nf

$ns flush-trace

close $nf

exec nam out.nam &

exit 0

Schedule Events

$ns at <time> <event>

37
Call ‘finish’

$ns at 5.0 "finish"

Run the simulation

$ns run

RESULT:

Thus the study Network Simulator in detail has done successfully.

38
EXP:NO:7B
SIMULATION OF CONGESTION CONTROL ALGORITHMS USING NS

Aim:

To perform simulation of Congestion Control Algorithms (sliding window) using NS.

Algorithm

Step 1: Run NSG 2.1

Step 2: Create two nodes n0 and n1.

Step 3. Create a duplex-link and set the following parameters

a. Queuetype : Droptail

b. Capacity 0.2 Mbps

c. Propagation delay: 200 ms

d. Queue size: 10

Step 4: Create link from n0 to n1.

Step 5: In Agent tab do the following

a. Packet size: 500 bytes

b. Agent type: TCP and draw a line from n0.

c. Agent type: TCP Sink and draw a line from n1.

d. Draw a line from tcp to sink.

Step 6: In Application tab do the following.

a. Application Type: ftp

b. Start time: 0.1

c. Stop time: 3.5

d. Draw line from tcp.

Step 7: In parameters tab do the following

a. Simulation time: 5.0

b. Trace file: sliding.tr

39
c. Nam file: sliding.nam

d. Click done

Program:

# Create a simulator object


set ns [new Simulator]

# Create NAM and trace output files


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

set tr [open out.tr w]


$ns trace-all $tr

# Define the finish procedure


proc finish {} {
global ns nf tr
$ns flush-trace
close $tr
close $nf
exec nam out.nam &
exit 0
}

# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

# Create links
$ns duplex-link $n0 $n1 10Mb 10ms DropTail
$ns duplex-link $n1 $n3 10Mb 10ms DropTail
$ns duplex-link $n2 $n1 10Mb 10ms DropTail

# Set link orientations for NAM visualization


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

# TCP connection from n0 to n3


set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp

set ftp [new Application/FTP]

40
$ftp attach-agent $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink

$ns connect $tcp $sink

# UDP connection from n2 to n3


set udp [new Agent/UDP]
$ns attach-agent $n2 $udp

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp

set null [new Agent/Null]


$ns attach-agent $n3 $null

$ns connect $udp $null

# Simulate a link failure and recovery


$ns rtmodel-at 1.0 down $n1 $n3
$ns rtmodel-at 2.0 up $n1 $n3

# Use Link State routing protocol


$ns rtproto LS

# Start applications
$ns at 0.0 "$ftp start"
$ns at 0.0 "$cbr start"

# End simulation
$ns at 5.0 "finish"

# Run simulation
$ns run

41
OUTPUT:

RESULT:

Thus the program to perform simulation of Congestion Control Algorithms (sliding window) using
NS has been done successfully.

42
EXP:NO:8
STUDY OF TCP/UDP PERFORMANCE USING SIMULATION TOOL

Aim :

To study the performance of TCP/UDP using Simulation Tool (NS2)

Algorithm :

1. Create 4 nodes (n0, n1, n2, n3).

2. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10

ms of delay.

3. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay.

4. Each node uses a DropTail queue, of which the maximum size is 10.

5. A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent

attached to n3.

6. As default, the maximum size of a packet that a "tcp" agent can generate is 1KByte.

7. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and

frees the received packets.

8. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3.

9. A "null" agent just frees the packets received.

10. A "ftp" and a "cbr" traffic generator are attached to "tcp" and "udp" agents

respectively, and the "cbr" is configured to generate 1 KByte packets at the rate of 1

Mbps.

11. The "cbr" is set to start at 0.1 sec and stop at 4.5 sec, and "ftp" is set to start at 1.0 sec

and stop at 4.0 sec

43
Program

#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

44
#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

45
OUTPUT:

46
RESULT:

Thus study of the performance of TCP/UDP using Simulation Tool (NS2) has been executed
and verified successfully.

47
EXP:NO:9A
SIMULATION OF DISTANCE VECTOR ROUTING ALGORITHM

Aim:

To perform Simulation of Distance Vector Routing algorithm.

ALGORITHM:

1. Create a simulator object

2. Define different colors for different data flows

3. Open a nam trace file and define finish procedure then close the trace file, and execute

nam on trace file.

4. Create n number of nodes using for loop

5. Create duplex links between the nodes

6. Setup UDP Connection between n(0) and n(5)

7. Setup another UDP connection between n(1) and n(5)

8. Apply CBR Traffic over both UDP connections

9. Choose distance vector routing protocol to transmit data from sender to receiver.

10. Schedule events and run the program.

Program (Distance Vector Protocol)

set ns [new Simulator]

set nr [open thro.tr w]

$ns trace-all $nr

set nf [open thro.nam w]

$ns namtrace-all $nf

proc finish { } {

global ns nr nf

$ns flush-trace

48
close $nf

close $nr

exec nam thro.nam &

exit 0

for { set i 0 } { $i < 12} { incr i 1 } {

set n($i) [$ns node]}

for {set i 0} {$i < 8} {incr i} {

$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }

$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail

$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail

$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail

$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail

$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail

$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail

set udp0 [new Agent/UDP]

$ns attach-agent $n(0) $udp0

set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.005

$cbr0 attach-agent $udp0

set null0 [new Agent/Null]

$ns attach-agent $n(5) $null0

$ns connect $udp0 $null0

set udp1 [new Agent/UDP]

49
$ns attach-agent $n(1) $udp1

set cbr1 [new Application/Traffic/CBR]

$cbr1 set packetSize_ 500

$cbr1 set interval_ 0.005

$cbr1 attach-agent $udp1

set null0 [new Agent/Null]

$ns attach-agent $n(5) $null0

$ns connect $udp1 $null0

$ns rtproto DV

$ns rtmodel-at 10.0 down $n(11) $n(5)

$ns rtmodel-at 15.0 down $n(7) $n(6)

$ns rtmodel-at 30.0 up $n(11) $n(5)

$ns rtmodel-at 20.0 up $n(7) $n(6)

$udp0 set fid_ 1

$udp1 set fid_ 2

$ns color 1 Red

$ns color 2 Green

$ns at 1.0 "$cbr0 start"

$ns at 2.0 "$cbr1 start"

$ns at 45 "finish"

$ns run

50
OUTPUT:

RESULT:

Thus the program to perform Simulation of Distance Vector Routing algorithmhas been executed
and verified successfulluy.

51
EXP:NO:9B
SIMULATION OF LINK STATE ROUTING ALGORITHM

Aim:

To perform Simulation of Link State Routing algorithm.

Algorithm:

1. Create a simulator object

2. Define different colors for different data flows

3. Open a nam trace file and define finish procedure then close the trace file, and execute

nam

on trace file.

4. Create n number of nodes using for loop

5. Create duplex links between the nodes

6. Setup UDP Connection between n(0) and n(5)

7. Setup another UDP connection between n(1) and n(5)

8. Apply CBR Traffic over both UDP connections

9. Choose Link state routing protocol to transmit data from sender to receiver.

10. Schedule events and run the program.

Program (Link State Protocol)

set ns [new Simulator]

set nr [open link.tr w]

$ns trace-all $nr

set nf [open link.nam w]

$ns namtrace-all $nf

proc finish { } {

global ns nr nf

52
$ns flush-trace

close $nf

close $nr

exec nam link.nam &

exit 0

for { set i 0 } { $i < 12} { incr i 1 } {

set n($i) [$ns node]}

for {set i 0} {$i < 8} {incr i} {

4931_Grace College of Engineering,Thoothukudi

$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }

$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail

$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail

$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail

$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail

$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail

$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail

set udp0 [new Agent/UDP]

$ns attach-agent $n(0) $udp0

set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.005

$cbr0 attach-agent $udp0

set null0 [new Agent/Null]

$ns attach-agent $n(5) $null0

53
$ns connect $udp0 $null0

set udp1 [new Agent/UDP]

$ns attach-agent $n(1) $udp1

set cbr1 [new Application/Traffic/CBR]

$cbr1 set packetSize_ 500

$cbr1 set interval_ 0.005

$cbr1 attach-agent $udp1

set null0 [new Agent/Null]

$ns attach-agent $n(5) $null0

$ns connect $udp1 $null0

$ns rtproto LS

$ns rtmodel-at 10.0 down $n(11) $n(5)

$ns rtmodel-at 15.0 down $n(7) $n(6)

$ns rtmodel-at 30.0 up $n(11) $n(5)

$ns rtmodel-at 20.0 up $n(7) $n(6)

$udp0 set fid_ 1

$udp1 set fid_ 2

$ns color 1 Red

$ns color 2 Green

$ns at 1.0 "$cbr0 start"

$ns at 2.0 "$cbr1 start"

$ns at 45 "finish"

$ns run

54
OUTPUT:

RESULT:

Thus the program to perform Simulation of Link State Routing algorithm has been executed and
verified successfully.

55
EXP:NO:10
SIMULATION OF AN ERROR CORRECTION CODE (LIKE CRC)

Aim :

To write a program in Java to implement the Simulation of Error Correction Code

Algorithm :

At sender side

1. Start the program

2. Read the number of bits to be sent. Let n be the Number of bits in data to be sent from

sender side.

3. Read the number of bits in the divisor. Let k be the Number of bits in the divisor (key

obtained from generator polynomial).

4. The binary data is first increased by adding k-1 zeros in the end of the data

5. Use modulo-2 binary division to divide binary data by the divisor and store remainder

of division.

6. Append the remainder at the end of the data to form the encoded data and send the

same

At receiver side

1. Perform modulo-2 division again and if remainder is 0, then there are no errors.

Modulo 2 division

In each step, a copy of the divisor (or data) is XORed with the k bits of the dividend.

The result of the XOR operation (remainder) is (n-1) bits, which is used for the next

step after 1 extra bit is pulled down to make it n bits long.

When there are no bits left to pull down, we have a result. The (n-1)-bit remainder

which is appended at the sender side.

56
Program

import java.util.Scanner;

public class HCS {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter 7-bit binary data: ");


String data = scanner.next();

String encoded = encodeHamming(data);


System.out.println("Code word: " + encoded);

System.out.println("Enter received Hamming code: ");


String received = scanner.next();

int errorPos = checkError(received);


if (errorPos == 0) {
System.out.println("No error in received code word.");
} else {
System.out.println("Error at position: " + errorPos);
received = correctError(received, errorPos);
System.out.println("Corrected code word: " + received);
}

scanner.close();
}

private static String encodeHamming(String data) {


int[] hamming = new int[11];
int[] dataBits = new int[7];
for (int i = 0; i < 7; i++) dataBits[i] = Character.getNumericValue(data.charAt(i));

hamming[2] = dataBits[0]; hamming[4] = dataBits[1]; hamming[5] = dataBits[2];


hamming[6] = dataBits[3]; hamming[8] = dataBits[4]; hamming[9] = dataBits[5];
hamming[10] = dataBits[6];

hamming[0] = hamming[2] ^ hamming[4] ^ hamming[6] ^ hamming[8] ^ hamming[10];


hamming[1] = hamming[2] ^ hamming[5] ^ hamming[6] ^ hamming[9] ^ hamming[10];
hamming[3] = hamming[4] ^ hamming[5] ^ hamming[6];
hamming[7] = hamming[8] ^ hamming[9] ^ hamming[10];

StringBuilder code = new StringBuilder();


for (int bit : hamming) code.append(bit);
return code.toString();
}

57
private static int checkError(String received) {
int[] r = new int[11];
for (int i = 0; i < 11; i++) r[i] = Character.getNumericValue(received.charAt(i));

int p1 = r[0] ^ r[2] ^ r[4] ^ r[6] ^ r[8] ^ r[10];


int p2 = r[1] ^ r[2] ^ r[5] ^ r[6] ^ r[9] ^ r[10];
int p4 = r[3] ^ r[4] ^ r[5] ^ r[6];
int p8 = r[7] ^ r[8] ^ r[9] ^ r[10];

return p1 * 1 + p2 * 2 + p4 * 4 + p8 * 8;
}

private static String correctError(String received, int pos) {


char[] bits = received.toCharArray();
bits[pos - 1] = (bits[pos - 1] == '0') ? '1' : '0';
return new String(bits);
}
}

OUTPUT:

58
RESULT:

Thus the program in Java to implement the Simulation of Error Correction Code has been
executed and verified successfully.

59
EXP:NO:11
IMPLEMENTATIONS OF STOP AND WAIT PROTOCOL AND SLIDING WINDOW
PROTOCOL

Aim :
To write a program in Java to Implementations of Stop and Wait Protocol and Sliding Window
Protocol

Algorithm :

1. Start the program.


2. Create the socket by specifying the address and establishes the connection
3. Send and receive information.
4. The sender sends one frame, stops until it receives confirmation from the receiver
and then sends the next frame.
5.Stop the program

Program:

import java.util.Random;

class SAP {
public static void main(String[] args) {
int[] frames = {1, 2, 3, 4, 5}; // Example frames
Random rand = new Random();

for (int frame : frames) {


System.out.println("Sending Frame: " + frame);

// Simulate acknowledgment (sometimes lost)


if (rand.nextInt(10) < 8) { // 80% chance of successful ACK
System.out.println("Acknowledgment received for Frame: " + frame);
} else {
System.out.println("ACK lost, resending Frame: " + frame);
System.out.println("Frame " + frame + " resent and acknowledged.");
}
System.out.println("-------------------");
}
}
}

60
Output :

RESULT:

Thus the program in Java to Implementations of Stop and Wait Protocol and Sliding Window
Protocol has been executed and verified successfully.

61
EXP:NO:12
WRITE A CODE SIMULATING GO BACK N ARQ.

Aim :
To write a program in Java to Write a code simulating Go Back N ARQ.

ALGORITHM:

Step 1: Start the program.


Step 2: Initialize WINDOW_SIZE to 3.
Step 3: Initialize the array frames = [1, 2, 3, 4, 5, 6].
Step 4: Set base = 0.
Step 5: Repeat the following steps while base < length of frames:
Step 5.1: Set end = min(base + WINDOW_SIZE, length of frames).
Step 5.2: Display the frames from base to end - 1 as "Sending frames".
Step 5.3: Generate a random number to simulate acknowledgment (80% chance).
Step 5.4: If acknowledgment is received:
Step 5.4.1: Display acknowledgment received message.
Step 5.4.2: Update base = base + WINDOW_SIZE.
Step 5.5: Else (acknowledgment is lost):
Step 5.5.1: Display "ACK lost, resending from Frame X".
Step 5.6: Print a separator line for clarity.
Step 6: End the program.

PROGRAM:

import java.util.Random;

class SWP {
static int WINDOW_SIZE = 3;

public static void main(String[] args) {


int[] frames = {1, 2, 3, 4, 5, 6};
Random rand = new Random();
int base = 0;

while (base < frames.length) {


int end = Math.min(base + WINDOW_SIZE, frames.length);
System.out.println("Sending frames: " + printFrames(frames, base, end));

boolean ackReceived = rand.nextInt(10) < 8; // 80% chance of ACK

if (ackReceived) {
System.out.println("Acknowledgment received for frames: " + printFrames(frames,
base, end));

62
base += WINDOW_SIZE;
} else {
System.out.println("ACK lost, resending from Frame " + frames[base]);
}
System.out.println("-------------------");
}
}

private static String printFrames(int[] frames, int start, int end) {


StringBuilder sb = new StringBuilder();
for (int i = start; i < end; i++) {
sb.append(frames[i]).append(" ");
}
return sb.toString();
}
}

Output :

RESULT:

Thus the program in Java for code simulating Go Back N ARQ has been executed and verified
successfully

63

You might also like