0% found this document useful (0 votes)
42 views81 pages

Wa0015.

The document outlines the structure and objectives of the Department of Artificial Intelligence and Data Science at an autonomous institution affiliated with Anna University, Chennai. It includes details about the laboratory course 231CS42B-Networks, emphasizing practical skills in network programming and protocols. Additionally, it presents the program's educational objectives, specific outcomes, and various experiments to be conducted by students during their practical sessions.

Uploaded by

aar55721
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)
42 views81 pages

Wa0015.

The document outlines the structure and objectives of the Department of Artificial Intelligence and Data Science at an autonomous institution affiliated with Anna University, Chennai. It includes details about the laboratory course 231CS42B-Networks, emphasizing practical skills in network programming and protocols. Additionally, it presents the program's educational objectives, specific outcomes, and various experiments to be conducted by students during their practical sessions.

Uploaded by

aar55721
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/ 81

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

231CS42B-NETWORKS LABORATORY

NAME :

REGISTER NO :

VM NO : VM - BRANCH :

AI&DS

YEAR : II

SEMESTER : IV

Vision

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

Mission

To impart quality technical skills through practicing, knowledge updating in recent technology and
produce professionals with multidisciplinary and leadership skills.
To promote innovative thinking for design and development of software products of varying
complexity with intelligence to fulfil the global standards and demands.
To inculcate professional ethics among the graduates and to adapt the changing technologies
through lifelong learning.

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.

CERTIFICATE

Name …………………….……………… Year: ……………… Semester: ...................... Branch:

B.TECH – ARTIFICIAL INTELLIGENCE AND DATA SCIENCE University Register

No………………….. College Roll No ........................... Certified that this is the bonafide record of work

done by the above student in the 231CS42B-NETWORKS LABORATORY

during the academic year 2024-2025.

Signature of the Course In-charge Signature of Head of the Department

Submitted for the University Practical Examination held on ............................ at VEL TECH MULTI
TECH
Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, No.42, AVADI – VEL TECH
ROAD, AVADI, CHENNAI-600062.
Signature of Examiners

Internal Examiner:…………… External Examiner:………………


Date:………………

PROGRAMME SPECIFIC OUTCOMES (PSOs)

PEOs PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1 Train the graduates with the potential of strong knowledge in the respective field and to create innovative
multidisciplinary solutions for challenges in the society

PEO2 Groom the engineers to understand, analyse different nature of data and use Machine Learning techniques
to develop software systems with varying complexity for data intensive applications

PEO3 To practice professionalism among the graduates and reflect good leadership skills with ethical standards
and continued professional development through lifelong learning.

PROGRAMME SPECIFIC OUTCOMES (PSOs)

PSO’s PROGRAMME SPECIFIC OUTCOMES (PSOs)

PSO1 To impart theoretical knowledge in the respective field along with recent industrial tools and techniques to
solve societal problems
Apply the core competency obtained in the field of Machine Learning for analysis, design and development
PSO2 of computing systems for multi-disciplinary problems

PSO3 Acquire knowledge in the field of intelligence, deep learning and develop software solutions for security
and analytics of large volume of data.
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

Programme Outcomes (POs)

WA1 PO1: Engineering Knowledge: Apply knowledge of mathematics, natural science, computing, engineering
fundamentals and an engineering specialization as specified in WK1 to WK4 respectively to develop to
the solution of complex engineering problems.

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

WA3 PO3: 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
health and safety, whole-life cost, net zero carbon, culture, society and environment as required. (WK5).

WA4 PO4: Conduct Investigations of Complex Problems: Conduct investigations of complex engineering
problems using research-based knowledge including design of experiments, modelling, analysis &
interpretation of data to provide valid conclusions. (WK8).

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

PO6: The Engineer and The World: Analyze and evaluate societal and environmental aspects while solving
complex engineering problems for its impact on sustainability with reference to economy, health, safety,
WA6 legal framework, culture and environment. (WK1, WK5, and WK7).
WA7 PO7: Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and
inclusion; adhere to national & international laws. (WK9).

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

WA9 PO9: 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,
make effective presentations considering cultural, language, and learning differences.

WA10
PO10: Project Management and Finance: Apply knowledge and understanding of engineering
management 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.

WA11 PO11: 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 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

INDEX
Ex. PAGE
DATE NAME OF THE EXERCISE(s) MARKS SIGN
No. No.
Learn to use commands like tcpdump, netstat,
ifconfig, nslookup and trace route. Capture ping
1
and trace route PDUs using a network protocol
analyzer and examine.
Write a http web client program to download a web
2
page using TCP sockets.
Applications using TCP sockets like:
a) echo client and echo server
3
b) chat
c) file transfer

4 Simulation of DNS using UDP sockets.

Use a tool like Wireshark to capture packets and


5
examine the packets
6 Write a code simulating ARP /RARP protocols.

A) study of network simulator (ns)


7 B) simulation of congestion control algorithms
using ns.
Study of TCP/UDP performance using simulation
8
tool.
Simulation of distance vector/ link state routing
9
algorithm.
10 Simulation of an error correction code (like CRC)
Implementations of stop and wait protocol and
11
sliding window protocol
12 Write a code simulating GO BACK N ARQ.
13 Case study / mini project

SUPPORTING MARKS (75)

Attendance
Pre-Lab Practical Skills and Lab
and Post-Lab Quiz TOTAL
Preparation Experimentation Record(s)
Punctuality

10 15 25 15 10 75
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:

4
INFERENCE:

RESULT:

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

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

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

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

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

OUTPUT:

SERVER:

CLIENT:

8
INFERENCE:

RESULT:

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

AIM:

To write a socket program for implementation of echo.

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.

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

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
{

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

INFERENCE:

RESULT:

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

OUTPUT:

15
TCPSERVER1:

TCPCLIENT1:

INFERENCE:

RESULT:

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

AIM:

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

PROGRAM:

SERVER:

17
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


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

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


while (bytesRead > -1) {

18
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
INFERENCE:

RESULT:

EXP:NO:4 SIMULATION OF DNS USING UDP SOCKET

AIM:

20
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++)

{
if (array[i].equals(str)) return i;
} return -
1; }

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

}
}
}

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

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

OUTPUT:

SERVER:

CLIENT:

23
INFERENCE:

OUTPUT:

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:

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

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.

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

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

27
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
INFERENCE:

RESULT:

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

Aim:

To write a program in java to simulate ARP protocols.

30
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[])
{ try
{
Buff
ered
Rea
der
in=n
ew
Buff
ered
Rea

31
der(
new
Inpu
tStr
eam
Rea
der(
Syst
em.i
n));
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();

32
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++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break; } } obj.close();
}}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:

INFERENCE:

RESULT:

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

35
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

Link failures

36
$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>

Call ‘finish’

$ns at 5.0 "finish"

Run the simulation

$ns run

37
RESULT:

SIMULATION OF CONGESTION CONTROL ALGORITHMS USING NS


EXP:NO:7B

Aim:

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

Algorithm

Step 1: Run NSG 2.1

38
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


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]

39
$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]


$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

40
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

OUTPUT:

41
INFERENCE:

RESULT:

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

42
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

Program

#Create a simulator object


set ns [new Simulator]

43
#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]

44
$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
OUTPUT:

45
46
INFERENCE:

47
RESULT:

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 close $nf

close $nr

exec nam thro.nam &

48
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]

$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

49
$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

OUTPUT:

50
INFERENCE:

RESULT::

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

$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} {

52
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

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

53
$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

OUTPUT:

54
INFERENCE:

RESULT:

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

Aim :

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

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

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

57
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
INFERENCE:

RESULT:

IMPLEMENTATIONS OF STOP AND WAIT PROTOCOL AND SLIDING WINDOW


EXP:NO:11
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.

59
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("-------------------");
}
}
}

Output :

60
INFERENCE:

RESULT:

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

61
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));
base += WINDOW_SIZE;
} else {
System.out.println("ACK lost, resending from Frame " + frames[base]);
}
System.out.println("-------------------");

62
}
}

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 :

INFERENCE:

RESULT:

63
EXNO: Real Time Port Scanner using Python -
DATE: Streamlit

Aim:

To build a real-time port scanner with a web dashboard using Streamlit, that
scans any IP address to detect open ports

Algorithm:
1. Start the application using Streamlit.
2.Take user input for IP address/domain and port range.
3.Resolve domain name to an IP address (if applicable).
4.Initialize a progress bar to track scanning progress.
5.Display a summary of all open ports in a clean, interactive table.
6.Show success message upon completion of scan.
7.End the program.

Program:

app.py

import streamlit as st
import socket
from scanner import scan_ports
import pandas as pd

st.set_page_config(page_title="⚡ Port Scanner", layout="centered")


st.title("🔍 Real-time Port Scanner")
st.markdown("Scan open ports on any IP or domain in real time.")

ip_input = st.text_input("Enter IP Address or Domain:", "scanme.nmap.org")


port_range = st.slider("Select Port Range", 1, 65535, (20, 1024))

if st.button("Start Scan 🚀"):


try:
ip = socket.gethostbyname(ip_input)
st.success(f"Resolved IP: {ip}")
ports = list(range(port_range[0], port_range[1] + 1))

# Progress indicator
st.subheader("📊 Scanning Progress")
progress_bar = st.progress(0)
progress_bar.current = 0
progress_bar.total = len(ports)

# Run scan and show results


results = scan_ports(ip, ports, progress=progress_bar)
df = pd.DataFrame(results)
open_ports = df[df["Status"] == "Open"]

st.success(f"✅ Scan complete! Found {len(open_ports)} open ports.")


st.dataframe(open_ports.reset_index(drop=True))
except Exception as e:
st.error(f"Error: {e}")

scanner.py:

import asyncio
import socket

semaphore = asyncio.Semaphore(100) # Limit concurrent tasks

async def scan_port(ip, port, progress=None):


async with semaphore:
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(ip, port), timeout=1
)
banner = ""
try:
writer.write(b"HEAD / HTTP/1.0\r\n\r\n")
await writer.drain()
banner = await asyncio.wait_for(reader.read(100), timeout=1)
banner = banner.decode(errors="ignore").strip()
except:
banner = "No banner"

writer.close()
await writer.wait_closed()
if progress:
progress.progress(min(progress.current + 1, progress.total))
progress.current += 1
return {"Port": port, "Status": "Open", "Banner": banner}
except:
if progress:
progress.progress(min(progress.current + 1, progress.total))
progress.current += 1
return {"Port": port, "Status": "Closed", "Banner": "-"}

def scan_ports(ip, ports, progress=None):


loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
tasks = [scan_port(ip, port, progress) for port in ports]
return loop.run_until_complete(asyncio.gather(*tasks))
Output:
Inference:
The project successfully implements a real-time port scanner with an interactive web
interface using Streamlit. It efficiently detects open ports and displays service banners for any
given IP address. The asynchronous approach ensures faster scanning with live progress
feedback.

Result:

Thus, the python streamlit application for real time port scanner which scans
port has been successfully implemented.

You might also like