Wireshark and Error Detection Techniques
Wireshark and Error Detection Techniques
Submitted by:
B. Thishithasai (AP23110010728)
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING
Aim: To use Wireshark for sniffing network traffic in real-time and analyzing the packet
contents for traffic analysis.
When you open Wireshark, you see a screen that shows you a list of all of the network
connections you can monitor. Choose your active interface (WI-FI in my case)
Click the first button on the toolbar, titled “Start Capturing Packets.”
You can select the menu item Capture -> Start.
During the capture, Wireshark will show you the packets that it captures in real-time.
Once you have captured all the packets you need, you use the same buttons or menu options
to stop the capture.
Step 3: Analyzing Data Packets on Wireshark
Wireshark shows you three different panes for inspecting packet data.
The Packet List, the top pane, is a list of all the packets in the capture. When you click on a
packet, the other two panes change to show you the details about the selected packet.
the middle pane, shows you as much readable information about the packet as possible,
depending on what kind of packet it is. You can right-click and create filters based on the
highlighted text in this field.
The bottom pane, Packet Bytes, displays the packet exactly as it got captured in hexadecimal.
Step 4: Wireshark Capture Filters
Capture filters limit the captured packets by the filter. Meaning if the packets don’t match the
filter, Wireshark won’t save them.
Experiment - 2
Aim: The goal is to create a C program that will simulate an Error Detection Technique
employing the Cyclic Redundancy Check algorithm in order to detect transmission errors in
data.
Program (C Code):
#include <stdio.h>
#include <string.h>
#define N strlen(gen_poly)
char data[28];
char check_value[28];
char gen_poly[10];
int data_length;
int i, j;
void XOR();
void CRC();
void receiver();
void XOR() {
for (j = 1; j < N; j++)
check_value[j] = (check_value[j] == gen_poly[j]) ? '0' : '1';
} void CRC() {
for (i = 0; i < N; i++)
check_value[i] = data[i];
do {
if (check_value[0] == '1')
XOR();
for (j = 0; j < N - 1; j++)
check_value[j] = check_value[j + 1];
check_value[j] = data[i++];
} while (i <= data_length + N - 1);
}void receiver() {
printf("\nEnter the received data: ");
scanf("%s", data);
printf("Data received: %s\n", data);
CRC();
for (i = 0; (i < N - 1) && (check_value[i] != '1'); i++);
if (i < N - 1)
printf("\nError detected in received data!\n");
else
printf("\nNo error detected in received data.\n");
} int main() {
printf("Enter data to be transmitted: ");
scanf("%s", data);
printf("Enter the generating polynomial: ");
scanf("%s", gen_poly);
data_length = strlen(data);
for (i = data_length; i < data_length + N - 1; i++)
data[i] = '0';
data[i] = '\0';
printf("\nData padded with n-1 zeros: %s\n", data);
CRC();
printf("\nCRC or Check value: %s\n", check_value);
for (i = data_length; i < data_length + N - 1; i++)
data[i] = check_value[i - data_length];
data[i] = '\0';
printf("\nFinal data to be sent: %s\n", data);
receiver();
return 0;
}
OUTPUT:
TEST CASE 1 — No Error Case:
Aim: To write a program that generates a Hamming code for a given set of data bits, detects
single-bit errors, and corrects them using the concept of Hamming distance.
Program (C Code):
#include <stdio.h>
#include <math.h>
int getRedundantCount(int m) {
int r = 0;
while ((1 << r) < (m + r + 1))
r++;
return r;
}
void generateHammingCode(int dataBits[], int m, int hammingCode[]) {
int r = getRedundantCount(m);
int n = m + r;
int i, j, k = 0;
for (i = 1; i <= n; i++) {
if ((i & (i - 1)) == 0)
hammingCode[i] = 0; // parity bits
else
hammingCode[i] = dataBits[k++];
}
for (i = 0; i < r; i++) {
int pos = 1 << i;
int parity = 0;
for (j = 1; j <= n; j++) {
if (j & pos)
parity ^= hammingCode[j];
} hammingCode[pos] = parity;
}
printf("\nGenerated Hamming Codeword: ");
for (i = n; i >= 1; i--)
printf("%d", hammingCode[i]);
printf("\n");
}void detectAndCorrect(int hammingCode[], int n) {
int r = log2(n) + 1;
int i, j;
int errorPos = 0;
for (i = 0; i < r; i++) {
int pos = 1 << i;
int parity = 0;
for (j = 1; j <= n; j++) {
if (j & pos)
parity ^= hammingCode[j];
}
if (parity != 0)
errorPos += pos;
} if (errorPos == 0) {
printf("\nNo error detected.\n");
} else {
printf("\nError detected at position: %d\n", errorPos);
hammingCode[errorPos] ^= 1;
printf("Corrected Hamming Codeword: ");
for (i = n; i >= 1; i--)
printf("%d", hammingCode[i]);
printf("\n");
}}
int main() {
int m, i, n, pos;
int dataBits[20], hammingCode[50];
printf("Enter number of data bits: ");
scanf("%d", &m);
printf("Enter data bits (LSB first): ");
for (i = 0; i < m; i++)
scanf("%d", &dataBits[i]);
generateHammingCode(dataBits, m, hammingCode);
int r = getRedundantCount(m);
n = m + r;
printf("\nEnter error position (0 for no error): ");
scanf("%d", &pos);
if (pos != 0 && pos <= n) {
hammingCode[pos] ^= 1;
printf("Erroneous Hamming Codeword: ");
for (i = n; i >= 1; i--)
printf("%d", hammingCode[i]);
printf("\n");
} detectAndCorrect(hammingCode, n);
return 0;
}
OUTPUT:
TEST CASE – 1 (Error Case)
Aim: To write a program to implement the 1-bit Stop and Wait protocol at the data link layer.
import [Link].*;
import [Link].*;
import [Link];
public class SlidingWindowClient {
private static final String SERVER_IP = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_IP, PORT);
[Link]("Connected to server.");
DataOutputStream out = new DataOutputStream([Link]());
DataInputStream in = new DataInputStream([Link]());
Scanner sc = new Scanner([Link]);
[Link]("Enter window size (N): ");
int N = [Link]();
int expectedFrame = 0;
while (true) {
try {
int frame = [Link]();
[Link]("Received frame " + frame);
if (frame == expectedFrame) {
[Link]("Frame " + frame + " is correct.");
expectedFrame++;
} else {
[Link]("Frame " + frame + " is out of order.");
}
[Link](expectedFrame - 1);
[Link]();
} catch (EOFException e) {
[Link]("All frames received.");
break;
}
}
[Link]();
[Link]();
[Link]();
}
}
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
public class SlidingWindowServer {
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
[Link]("Server is running... Waiting for client.");
Socket clientSocket = [Link]();
[Link]("Client connected.");
DataOutputStream out = new DataOutputStream([Link]());
DataInputStream in = new DataInputStream([Link]());
Scanner sc = new Scanner([Link]);
[Link]("Enter window size (N): ");
int N = [Link]();
[Link]("Enter total number of frames to send: ");
int totalFrames = [Link]();
int base = 0;
int nextSeqNum = 0;
while (base < totalFrames) {
while (nextSeqNum < base + N && nextSeqNum < totalFrames) {
[Link]("Sending frame " + nextSeqNum);
[Link](nextSeqNum);
[Link]();
nextSeqNum++;
}
int ack = [Link]();
[Link]("Received ACK for frame " + ack);
if (ack >= base) {
base = ack + 1;
}
}
[Link]("All frames sent and acknowledged.");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
TEST CASE 1 — Normal Case (No Lost Frames)
Aim: Write a Java program to implement the N-bit Sliding Window protocol at the data link
layer. using sockets to achieve reliable data transfer with retransmission of lost frames. Go-
Back-N ARQ, Selective Repeat ARQ protocol, in which the frames are retransmitted only
when lost or erroneous, to ensure efficiency and reliability in the transfer of data.
import [Link].*;
import [Link].*;
import [Link].*;
public class GoSlidingWindowServer {
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
[Link]("Server is running... Waiting for client connection...");
Socket clientSocket = [Link]();
[Link]("Client connected.");
DataOutputStream out = new DataOutputStream([Link]());
DataInputStream in = new DataInputStream([Link]());
Scanner sc = new Scanner([Link]);
[Link]("Enter window size (N): ");
int N = [Link]();
[Link]("Enter total number of frames to send: ");
int totalFrames = [Link]();
int base = 0;
int nextSeqNum = 0;
int ack = -1;
while (base < totalFrames) {
while (nextSeqNum < base + N && nextSeqNum < totalFrames) {
[Link]("Sending frame " + nextSeqNum);
[Link](nextSeqNum);
[Link]();
nextSeqNum++;
}
try {
ack = [Link]();
[Link]("Received ACK for frame " + ack);
if (ack >= base) {
base = ack + 1; // Move window forward
} else {
[Link]("Duplicate or old ACK received. No movement of window.");
}
}
catch (SocketTimeoutException e) {
[Link]("Timeout! Resending frames from " + base + " to " +
(nextSeqNum - 1));
nextSeqNum = base; // Go back and resend
}
catch (EOFException e) {
[Link]("Connection closed by client.");
break;
}
}
[Link]("All frames sent and acknowledged successfully.");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
public class GoSlidingWindowClient {
private static final String SERVER_IP = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(SERVER_IP, PORT);
[Link]("Connected to server.");
DataInputStream in = new DataInputStream([Link]());
DataOutputStream out = new DataOutputStream([Link]());
Scanner sc = new Scanner([Link]);
[Link]("Enter window size (N): ");
int N = [Link]();
int expectedFrame = 0;
int lastAckSent = -1;
while (true) {
try {
int frame = [Link]();
[Link]("\nReceived frame " + frame);
if ([Link]() < 0.2) { // 20% chance of loss
[Link]("Frame " + frame + " lost/corrupted!");
continue;
}
if (frame == expectedFrame) {
[Link]("Frame " + frame + " accepted.");
expectedFrame++;
lastAckSent = frame;
} else {
[Link]("Frame " + frame + " out of order. Expected: " +
expectedFrame);
}
[Link](lastAckSent);
[Link]();
[Link]("ACK sent for frame " + lastAckSent);
} catch (EOFException e) {
[Link]("All frames received successfully.");
break;
}
}
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
TEST CASE 1 – Frame Loss
import [Link].*;
import [Link].*;
import [Link].*;
public class SelectiveRepeatServer {
private static final int PORT = 8080;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
[Link]("Server is running... Waiting for client connection...");
try (Socket clientSocket = [Link]();
DataOutputStream out = new DataOutputStream([Link]());
DataInputStream in = new DataInputStream([Link]());
Scanner sc = new Scanner([Link])) {
[Link]("Client connected.");
[Link]("Enter window size (N): ");
int N = [Link]();
[Link]("Enter total number of frames to send: ");
int totalFrames = [Link]();
boolean[] ackReceived = new boolean[totalFrames];
int base = 0;
while (base < totalFrames) {
for (int i = base; i < base + N && i < totalFrames; i++) {
if (!ackReceived[i]) {
[Link]("Sending frame " + i);
[Link](i);
[Link]();
}
}
try {
int ack = [Link]();
[Link]("Received ACK for frame " + ack);
if (ack >= 0 && ack < totalFrames) {
ackReceived[ack] = true;
}
while (base < totalFrames && ackReceived[base]) {
base++;
}
} catch (EOFException e) {
[Link]("Client disconnected early.");
break;
} catch (SocketException e) {
[Link]("Client forcibly closed the connection.");
break;
}
}
[Link]("All frames sent and acknowledged successfully.");
}
} catch (IOException e) {
[Link]("Server Error: " + [Link]());
}
}
}
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
public class SelectiveRepeatClient {
private static final String SERVER_IP = "localhost";
private static final int PORT = 8080;
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_IP, PORT);
DataInputStream in = new DataInputStream([Link]());
DataOutputStream out = new DataOutputStream([Link]());
Scanner sc = new Scanner([Link])) {
[Link]("Connected to server.");
[Link]("Enter window size (N): ");
int N = [Link]();
int expectedBase = 0;
int windowEnd = expectedBase + N - 1;
boolean[] received = new boolean[100];
while (true) {
try {
int frame = [Link](); // <-- line where your crash happened
[Link]("\nReceived frame " + frame);
if ([Link]() < 0.2) { // simulate loss
[Link]("Frame " + frame + " lost/corrupted!");
continue;
}
if (frame >= expectedBase && frame <= windowEnd) {
received[frame] = true;
[Link]("Frame " + frame + " accepted and buffered.");
[Link](frame);
[Link]();
[Link]("ACK sent for frame " + frame);
while (received[expectedBase]) {
expectedBase++;
windowEnd = expectedBase + N - 1;
}
} else if (frame < expectedBase) {
[Link]("Duplicate frame " + frame + " received. Re-ACKing...");
[Link](frame);
[Link]();
} else {
[Link]("Frame " + frame + " outside window. Ignored.");
}
} catch (EOFException e) {
[Link]("\nServer finished sending all frames.");
break;
} catch (SocketException e) {
[Link]("\nConnection closed by server. Ending client.");
break;
}
}
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
}
OUTPUT:
TEST CASE 1 – Frame Loss + Selective Retransmission
Aim: Write a Java program to implement Dijkstra's Shortest Path Algorithm for finding the
shortest path and minimum cost from a given source node to all other nodes in a network.
import [Link].*;
public class DijkstraShortestPath {
static final int INF = 9999;
static int minDistance(int[] dist, boolean[] visited, int V) {
int min = INF, minIndex = -1;
for (int v = 0; v < V; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
static void printSolution(int[] dist, int[] parent, int src, int V) {
[Link]("\nRouter " + (src + 1) + " as Source:\n");
[Link]("Destination\tDistance\tPath");
for (int i = 0; i < V; i++) {
if (i != src) {
[Link]((i + 1) + "\t\t" + dist[i] + "\t\t");
printPath(i, parent);
[Link]();
}
}
}
static void printPath(int j, int[] parent) {
if (parent[j] == -1) {
[Link]((j + 1));
return;
}
printPath(parent[j], parent);
[Link](" -> " + (j + 1));
}
static void dijkstra(int[][] graph, int src, int V) {
int[] dist = new int[V];
boolean[] visited = new boolean[V];
int[] parent = new int[V];
// Initialize
for (int i = 0; i < V; i++) {
dist[i] = INF;
visited[i] = false;
parent[i] = -1;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, visited, V);
visited[u] = true;
for (int v = 0; v < V; v++) {
if (!visited[v] && graph[u][v] != 0 &&
dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u;
}
}}
printSolution(dist, parent, src, V);
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of vertices (routers): ");
int V = [Link]();
int[][] graph = new int[V][V];
[Link]("Enter the cost adjacency matrix (0 for no direct link):");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
graph[i][j] = [Link]();
if (i != j && graph[i][j] == 0)
graph[i][j] = INF;
}
}
[Link]("Enter the source router (1 to " + V + "): ");
int src = [Link]() - 1;
dijkstra(graph, src, V);
}
}
OUTPUT:
CASE 1 – Simple 5-Router Network
Aim: Write a Java program to implement the Distance Vector Routing Algorithm for
computing routing tables for each node, dynamically updating the tables when the link costs
change.
import [Link].*;
public class DVR {
static final int INF = 9999;
static int v, e;
static int[][] graph, via, rt;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter number of Vertices: ");
v = [Link]([Link]());
[Link]("Enter number of Edges: ");
e = [Link]([Link]());
graph = new int[v][v];
via = new int[v][v];
rt = new int[v][v];
for (int i = 0; i < v; i++)
for (int j = 0; j < v; j++)
graph[i][j] = (i == j) ? 0 : INF;
for (int i = 0; i < e; i++) {
[Link]("Edge " + (i + 1));
[Link]("Source: ");
int s = [Link]([Link]()) - 1;
[Link]("Destination: ");
int d = [Link]([Link]()) - 1;
[Link]("Cost: ");
int c = [Link]([Link]());
graph[s][d] = c;
graph[d][s] = c;
}
dvr_calc_disp("Initial Routing Tables:");
[Link]("Enter updated edge Source: ");
int s = [Link]([Link]()) - 1;
[Link]("Enter updated edge Destination: ");
int d = [Link]([Link]()) - 1;
[Link]("Enter new cost: ");
int newCost = [Link]([Link]());
graph[s][d] = newCost;
graph[d][s] = newCost;
dvr_calc_disp("Updated Routing Tables:");
}
static void dvr_calc_disp(String msg) {
init_tables();
update_tables();
[Link]("\n" + msg);
print_tables();
}
static void init_tables() {
for (int i = 0; i < v; i++)
for (int j = 0; j < v; j++) {
rt[i][j] = (i == j) ? 0 : INF;
via[i][j] = (i == j) ? i : -1;
}
}
static void update_tables() {
for (int k = 0; k < 4 * v; k++)
update_table(k % v);
}
static void update_table(int src) {
for (int i = 0; i < v; i++) {
if (graph[src][i] == INF)
continue;
int dist = graph[src][i];
for (int j = 0; j < v; j++) {
int inter = rt[i][j];
if (via[i][j] == src)
inter = INF;
if (dist + inter < rt[src][j]) {
rt[src][j] = dist + inter;
via[src][j] = i;
}
}
}
}
static void print_tables() {
[Link]("\nRouting Table:");
for (int i = 0; i < v; i++) {
[Link]("Router " + (i + 1) + ": ");
for (int j = 0; j < v; j++)
[Link](rt[i][j] + "\t");
[Link]();
}
}
}
OUTPUT:
CASE 1 – 4-Node Network
CASE 2 – Small 3-Node Network CASE 3 – Small 2-Node Network
Experiment – 8
import [Link].*;
import [Link].*;
public class EchoServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("Echo Server is running on port " + port);
while (true) {
Socket clientSocket = [Link]();
[Link]("Client connected: " + [Link]());
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String line;
while ((line = [Link]()) != null) {
[Link]("Received from client: " + line);
[Link](line); // Echo the message back to the client
}
[Link]("Client disconnected.");
[Link]();
}
} catch (IOException e) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}
[Link]:
import [Link].*;
import [Link].*;
public class EchoClient {
public static void main(String[] args) {
String hostname = "localhost";
int port = 12345;
try (Socket socket = new Socket(hostname, port)) {
[Link]("Connected to server");
BufferedReader userInput = new BufferedReader(new
InputStreamReader([Link]));
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String message;
[Link]("Type a message (type 'exit' to quit):");
while (true) {
[Link]("> ");
message = [Link]();
if ([Link]("exit")) {
break;
}
[Link](message);
String response = [Link]();
[Link]("Echo from server: " + response);
}
[Link]("Disconnected from server.");
} catch (IOException e) {
[Link]("Client exception: " + [Link]());
[Link]();
}
}
}
OUTPUT:
CASE 1 — Single Message
CASE 3 - no Message
Experiment - 9
import [Link].*;
public class UDPServer {
public static void main(String[] args) {
int port = 9876;
try (DatagramSocket serverSocket = new DatagramSocket(port)) {
byte[] receiveData = new byte[1024];
byte[] sendData;
[Link]("[SERVER] UDP Server started on port " + port);
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
[Link](receivePacket);
String clientMessage = new String([Link](), 0,
[Link]());
[Link]("[SERVER] Received: " + clientMessage);
if ([Link]("exit")) {
[Link]("[SERVER] Client requested termination. Closing server...");
break;
}
String response = "Echo from server: " + clientMessage;
sendData = [Link]();
InetAddress clientIP = [Link]();
int clientPort = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
clientIP, clientPort);
[Link](sendPacket);
}
} catch (Exception e) {
[Link]("[SERVER] Error: " + [Link]());
}
}
}
[Link]:
import [Link].*;
import [Link].*;
public class UDPClient {
public static void main(String[] args) {
String serverHost = "[Link]";
int serverPort = 9876;
try (DatagramSocket clientSocket = new DatagramSocket();
BufferedReader userInput = new BufferedReader(new
InputStreamReader([Link]))) {
InetAddress IPAddress = [Link](serverHost);
byte[] sendData;
byte[] receiveData = new byte[1024];
[Link]("[CLIENT] Connected to UDP server at " + serverHost + ":" +
serverPort);
[Link]("[CLIENT] Type your message (type 'exit' to quit):");
while (true) {
[Link]("You: ");
String sentence = [Link]();
sendData = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
IPAddress, serverPort);
[Link](sendPacket);
if ([Link]("exit")) {
[Link]("[CLIENT] Exiting...");
break;
}
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
[Link](receivePacket);
String modifiedSentence = new String([Link](), 0,
[Link]());
[Link]("[SERVER]: " + modifiedSentence);
}
} catch (Exception e) {
[Link]("[CLIENT] Error: " + [Link]());
}
}
}
OUTPUT:
CASE 1 — Normal Message Exchange
CASE 3 — no Message
Experiment – 10
Aim: Writing a Java program to implement an Echo Server and Client using TCP sockets,
where the server echoes the same message received from the client back to it.
import [Link].*;
import [Link].*;
public class EchoServer {
public static void main(String[] args) {
int port = 12345; // You can choose any available port number
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("Echo Server is running on port " + port);
while (true) {
Socket clientSocket = [Link](); // Accept a connection
[Link]("Client connected: " + [Link]());
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String line;
while ((line = [Link]()) != null) {
[Link]("Received from client: " + line);
[Link](line); // Echo the message back to the client
}
[Link]("Client disconnected.");
[Link]();
}
} catch (IOException e) {
[Link]("Server exception: " + [Link]());
[Link]();
}
}
}
[Link]:
import [Link].*;
import [Link].*;
public class EchoClient {
public static void main(String[] args) {
String hostname = "localhost"; // or the server's IP address
int port = 12345;
try (Socket socket = new Socket(hostname, port)) {
[Link]("Connected to server");
BufferedReader userInput = new BufferedReader(new
InputStreamReader([Link]));
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
String message;
[Link]("Type a message (type 'exit' to quit):");
while (true) {
[Link]("> ");
message = [Link]();
if ([Link]("exit")) {
break;
}
[Link](message); // Send message to server
String response = [Link](); // Read echoed message
[Link]("Echo from server: " + response);
}
[Link]("Disconnected from server.");
} catch (IOException e) {
[Link]("Client exception: " + [Link]());
[Link]();
}
}}
OUTPUT:
CASE 1 — Normal Message Exchange
Aim: To write a Java program to simulate the Trace Route (Traceroute) protocol, which
determines the path and hop delays from the source host to the destination host using socket
programming.
import [Link];
import [Link].*;
public class TraceRoute {
public static void main(String[] args) {
if ([Link] != 1) {
[Link]("Usage: java TraceRoute <hostname>");
return;
}
String targetHost = args[0];
int maxHops = 30;
int port = 33434; // Commonly used port for traceroute simulations
int timeout = 3000; // 3 seconds timeout
[Link]("Tracing route to " + targetHost + " over a maximum of " + maxHops
+ " hops:");
try {
InetAddress target = [Link](targetHost);
for (int ttl = 1; ttl <= maxHops; ttl++) {
try {
long startTime = [Link]();
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(target, port);
[Link](timeout);
[Link](true);
try {
[Link](address, timeout);
} catch (SocketTimeoutException ste) {
}
long endTime = [Link]();
long rtt = endTime - startTime;
String hopAddress = "Unknown";
if ([Link](timeout)) {
hopAddress = [Link]();
}
[Link]("%2d %s %d ms\n", ttl, hopAddress, rtt);
if ([Link]().equals(hopAddress)) {
[Link]("Trace complete.");
break;
}
[Link]();
} catch (IOException e) {
[Link]("%2d Request timed out.\n", ttl);
}
}
} catch (UnknownHostException e) {
[Link]("Unknown host: " + targetHost);
} catch (IOException e) {
[Link]("I/O error: " + [Link]());
}
}
}
OUTPUT:
CASE 1 - Trace [Link]
Aim: In this lab, we will be writing a Java program to simulate Ping (ICMP Echo
Request/Reply) to check host reachability and measure per packet RTT.
import [Link];
import [Link];
public class PingSimulator {
public static void main(String[] args) {
if ([Link] != 1) {
[Link]("Usage: java PingSimulator <hostname>");
return;
}
String host = args[0];
int pingCount = 4;
int timeout = 1000; // milliseconds
try {
InetAddress inet = [Link](host);
[Link]("Pinging " + host + " with " + timeout + "ms timeout:");
for (int i = 1; i <= pingCount; i++) {
long startTime = [Link]();
boolean reachable = [Link](timeout);
long endTime = [Link]();
long rtt = endTime - startTime;
if (reachable) {
[Link]("Reply from " + [Link]() + ": time=" + rtt +
"ms");
} else {
[Link]("Request timed out.");
}
[Link](1000); // Wait 1 second between pings
}
[Link]("Ping simulation complete.")
} catch (IOException e) {
[Link]("I/O error: " + [Link]());
} catch (InterruptedException e) {
[Link]("Ping interrupted.");
}
}
}
OUTPUT:
Case 1 – Ping [Link]
Aim: The task is to write a Java program to implement an IP Subnet Calculator that
determines the IP address class, the default subnet mask, custom subnet mask, and subnet
address based on a given IP address.
import [Link];
public class IPSubnetCalculator {
private static String getIPAddressClass(String ip) {
int firstOctet = [Link]([Link]("\\.")[0]);
if (firstOctet >= 1 && firstOctet <= 126) {
return "A";
} else if (firstOctet >= 128 && firstOctet <= 191) {
return "B";
} else if (firstOctet >= 192 && firstOctet <= 223) {
return "C";
} else if (firstOctet >= 224 && firstOctet <= 239) {
return "D (Multicast)";
} else if (firstOctet >= 240 && firstOctet <= 255) {
return "E (Experimental)";
} else {
return "Invalid";
}
}
private static String getDefaultSubnetMask(String ipClass) {
switch (ipClass) {
case "A":
return "[Link]";
case "B":
return "[Link]";
case "C":
return "[Link]";
default:
return "Not applicable";
}
}
private static String convertMaskToBinary(int maskBits) {
StringBuilder mask = new StringBuilder();
for (int i = 0; i < 32; i++) {
if (i < maskBits) {
[Link]("1");
} else {
[Link]("0");
}
if ((i + 1) % 8 == 0 && i != 31) {
[Link](".");
}
}
return [Link]();
}
private static String generateSubnetMask(int subnetBits) {
String binaryMask = convertMaskToBinary(subnetBits);
String[] octets = [Link]("\\.");
StringBuilder mask = new StringBuilder();
for (int i = 0; i < 4; i++) {
int value = [Link](octets[i], 2);
[Link](value);
if (i < 3) {
[Link](".");
}
}
return [Link]();
}
private static String calculateSubnetAddress(String ip, String subnetMask) {
String[] ipOctets = [Link]("\\.");
String[] maskOctets = [Link]("\\.");
StringBuilder subnetAddress = new StringBuilder();
for (int i = 0; i < 4; i++) {
int ipPart = [Link](ipOctets[i]);
int maskPart = [Link](maskOctets[i]);
int subnetPart = ipPart & maskPart;
[Link](subnetPart);
if (i < 3) {
[Link](".");
}}
return [Link]();
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter IP Address (e.g., [Link]): ");
String ip = [Link]();
String ipClass = getIPAddressClass(ip);
[Link]("IP Address Class: " + ipClass);
String defaultMask = getDefaultSubnetMask(ipClass);
[Link]("Default Network Mask: " + defaultMask);
[Link]("Enter subnet bits (e.g., 24): ");
int subnetBits = [Link]();
if (subnetBits < 0 || subnetBits > 32) {
[Link]("Invalid subnet bits.");
return;
}
String subnetMask = generateSubnetMask(subnetBits);
[Link]("Subnet Mask: " + subnetMask)
String subnetAddress = calculateSubnetAddress(ip, subnetMask);
[Link]("Subnet Address: " + subnetAddress);
[Link]();
}}
OUTPUT:
CASE 1 — Class C IP (Most Common)
Aim: To write a code to implement the Sliding Window protocol at the transport layer.
import [Link].*;
public class SlidingWindow {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("=== Sliding Window Protocol Simulation ===");
[Link]("Enter total number of frames: ");
int totalFrames = [Link]();
[Link]("Enter window size: ");
int windowSize = [Link]();
int sent = 0;
while (sent < totalFrames) {
[Link]("\nWindow:");
for (int i = 0; i < windowSize && (sent + i) < totalFrames; i++) {
[Link]("Sending frame: " + (sent + i));
}
[Link]("\nEnter the ACK for the last received frame:");
int ack = [Link]();
if (ack == sent) {
[Link]("No ACK received... retransmitting window...");
} else {
[Link]("ACK received for frame: " + (ack - 1));
sent = ack;
}
}
[Link]("\nAll frames sent successfully!");
}
}
OUTPUT:
CASE 1 — Normal flow
CASE 2 — With retransmission
import [Link].*;
import [Link].*;
public class TCPFileServer {
public static void main(String[] args) {
int port = 5000;
try (ServerSocket serverSocket = new ServerSocket(port)) {
[Link]("[SERVER] Waiting for client...");
Socket socket = [Link]();
[Link]("[SERVER] Client connected!");
DataInputStream dis = new DataInputStream([Link]());
FileOutputStream fos = new FileOutputStream("received_file.txt");
long fileSize = [Link]();
byte[] buffer = new byte[4096];
int read;
long remaining = fileSize;
while ((read = [Link](buffer, 0, (int) [Link]([Link], remaining))) > 0) {
[Link](buffer, 0, read);
remaining -= read;
}
[Link]();
[Link]();
[Link]("[SERVER] File received successfully!");
} catch (Exception e) {
[Link]("Server Error: " + [Link]());
}
}
}
[Link]:
import [Link].*;
import [Link].*;
public class TCPFileClient {
public static void main(String[] args) {
String host = "[Link]";
int port = 5000;
try (Socket socket = new Socket(host, port)) {
File file = new File("send_file.txt");
FileInputStream fis = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream([Link]());
long fileSize = [Link]();
[Link](fileSize);
byte[] buffer = new byte[4096];
int read;
while ((read = [Link](buffer)) > 0) {
[Link](buffer, 0, read);
}
[Link]();
[Link]("[CLIENT] File sent successfully!");
} catch (Exception e) {
[Link]("Client Error: " + [Link]());
}
}
}
OUTPUT:
CASE 1 — Small Text File