0% found this document useful (0 votes)
4 views19 pages

Computer Network Practical Manual BCS653

The document contains multiple Java implementations of networking protocols, including Stop and Wait, Sliding Window, ARP/RARP, PING, and TRACEROUTE, as well as client-server socket programming examples for chat applications and DNS queries. Each section provides code snippets demonstrating the functionality of the respective protocols and applications. Additionally, it explains the client-server model and how to run the provided examples.

Uploaded by

lerab95795
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)
4 views19 pages

Computer Network Practical Manual BCS653

The document contains multiple Java implementations of networking protocols, including Stop and Wait, Sliding Window, ARP/RARP, PING, and TRACEROUTE, as well as client-server socket programming examples for chat applications and DNS queries. Each section provides code snippets demonstrating the functionality of the respective protocols and applications. Additionally, it explains the client-server model and how to run the provided examples.

Uploaded by

lerab95795
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/ 19

1. Implementation of Stop and Wait Protocol.

import java.util.Scanner;
import java.util.Random;

public class StopAndWaitProtocol {


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

System.out.print("Enter number of frames to send: ");


int n = sc.nextInt();

for (int i = 0; i < n; i++) {


System.out.println("Sending Frame " + i);

boolean ackReceived = rand.nextBoolean(); // randomly simulate ACK lost or received

if (ackReceived) {
System.out.println("ACK for Frame " + i + " received.\n");
} else {
System.out.println("ACK for Frame " + i + " lost. Resending Frame...\n");
i--; // resend same frame
}
}

System.out.println("All frames sent successfully!");


sc.close();
}
}
OUTPUT :-
2. Implementation of Sliding Window Protocol.
import java.util.Scanner;
import java.util.Random;

public class SlidingWindowProtocol {


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

System.out.print("Enter number of frames to send: ");


int totalFrames = sc.nextInt();

System.out.print("Enter window size: ");


int windowSize = sc.nextInt();

int sent = 0;

while (sent < totalFrames) {


int framesInWindow = Math.min(windowSize, totalFrames - sent);

System.out.println("\nSending frames from " + sent + " to " + (sent + framesInWindow - 1));

boolean allAcked = true;


for (int i = 0; i < framesInWindow; i++) {
boolean ackReceived = rand.nextBoolean();

if (!ackReceived) {
System.out.println("ACK for Frame " + (sent + i) + " lost. Resending window...");
allAcked = false;
break;
} else {
System.out.println("ACK for Frame " + (sent + i) + " received.");
}
}

if (allAcked) {
sent += framesInWindow; // move window forward
}
// else: window remains at same place, resend
}

System.out.println("\nAll frames sent successfully!");


sc.close();
}
}

OUTPUT :-
3. Study of Socket Programming and Client – Server model

What is Socket Programming?


 A socket is like an endpoint between two machines talking over a network.
 Socket Programming is the way we connect, send, and receive data between computers
using sockets.

In short:
Socket = Door.
Socket Programming = Knocking, opening, sending, and receiving through that door.

What is Client–Server Model?

 In Client-Server, one side is called Server, and the other side is called Client.

SERVER CLIENT

Always running / listening Connects when needed

Waits for client connections Sends request to server

Responds with data or service Receives response

Example:

 Google servers wait for your Chrome browser (client) to connect.


 When you search, Chrome sends a request.
 Google's server replies with search results.
Example Code in Java

Server (listens for connections)


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

public class Server {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(5000); // Server listening on port 5000
System.out.println("Server started. Waiting for client...");

Socket socket = serverSocket.accept(); // Accept client connection


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

BufferedReader reader = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

writer.println("Hello Client, I am Server!");

String clientMessage = reader.readLine();


System.out.println("Client says: " + clientMessage);

socket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client (connects to server)
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5000); // Connect to server at localhost on port 5000
System.out.println("Connected to server!");

BufferedReader reader = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

System.out.println("Server says: " + reader.readLine());

writer.println("Hello Server, I am Client!");

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to run?
1. First run the Server.java program:

2. Then run the Client.java program in another terminal


4. Write a code simulating ARP /RARP protocols

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class ARP_RARP_Simulation {

// Simulating a network table


private static final Map<String, String> ipToMac = new HashMap<>();
private static final Map<String, String> macToIp = new HashMap<>();

// Populating some static entries


static {
ipToMac.put("192.168.1.2", "AA:BB:CC:DD:EE:01");
ipToMac.put("192.168.1.3", "AA:BB:CC:DD:EE:02");
ipToMac.put("192.168.1.4", "AA:BB:CC:DD:EE:03");

// Populate reverse mapping


for (Map.Entry<String, String> entry : ipToMac.entrySet()) {
macToIp.put(entry.getValue(), entry.getKey());
}
}

private static void arp(String ipAddress) {


System.out.println("\n[ARP] Resolving IP Address: " + ipAddress);
String macAddress = ipToMac.get(ipAddress);
if (macAddress != null) {
System.out.println("MAC Address found: " + macAddress);
} else {
System.out.println("MAC Address not found for IP: " + ipAddress);
}
}

private static void rarp(String macAddress) {


System.out.println("\n[RARP] Resolving MAC Address: " + macAddress);
String ipAddress = macToIp.get(macAddress);
if (ipAddress != null) {
System.out.println("IP Address found: " + ipAddress);
} else {
System.out.println("IP Address not found for MAC: " + macAddress);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

System.out.println("=== ARP / RARP Simulation ===");


do {
System.out.println("\nChoose an option:");
System.out.println("1. ARP (IP to MAC)");
System.out.println("2. RARP (MAC to IP)");
System.out.println("3. Exit");
System.out.print("Enter choice: ");
choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

switch (choice) {
case 1:
System.out.print("Enter IP Address: ");
String ip = scanner.nextLine();
arp(ip);
break;
case 2:
System.out.print("Enter MAC Address: ");
String mac = scanner.nextLine();
rarp(mac);
break;
case 3:
System.out.println("Exiting Simulation.");
break;
default:
System.out.println("Invalid choice. Try again.");
}
} while (choice != 3);

scanner.close();
}
}

OUTPUT :-
5. Write a code simulating PING commands

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

public class PingSimulation {

public static void main(String[] args) {


String host = "google.com"; // You can change this to any host

try {
// Ping the host
InetAddress inet = InetAddress.getByName(host);

// Try to reach the host


System.out.println("Pinging " + host + "...");
boolean reachable = inet.isReachable(5000); // Timeout is 5 seconds

if (reachable) {
System.out.println(host + " is reachable.");
} else {
System.out.println(host + " is not reachable.");
}

} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
OUTPUT :-
6. Write a code simulating TRACEROUTE commands
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TracerouteSimulation {


public static void main(String[] args) {
String host = "google.com";

try {
System.out.println("Tracing route to " + host + "...\n");

ProcessBuilder pb = new ProcessBuilder("traceroute", host);


Process process = pb.start();

BufferedReader reader = new BufferedReader(new


InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

OUTPUT :-
7. Applications using TCP Sockets like – Chat App

a) Server Code (ChatServer.java)


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

public class ChatServer {


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

Socket socket = serverSocket.accept();


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

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

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

String msgFromClient, msgToClient;


while (true) {
msgFromClient = in.readLine();
if (msgFromClient.equalsIgnoreCase("exit")) {
System.out.println("Client disconnected.");
break;
}
System.out.println("Client: " + msgFromClient);

System.out.print("You: ");
msgToClient = userInput.readLine();
out.println(msgToClient);
}
socket.close();
serverSocket.close();
}
}

b) Client Code (ChatClient.java)


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

public class ChatClient {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234);
System.out.println("Connected to server.");

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

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

String msgFromServer, msgToServer;


while (true) {
System.out.print("You: ");
msgToServer = userInput.readLine();
out.println(msgToServer);

if (msgToServer.equalsIgnoreCase("exit")) {
System.out.println("Disconnected from server.");
break;
}

msgFromServer = in.readLine();
System.out.println("Server: " + msgFromServer);
}

socket.close();
}
}

OUTPUT :-

Server: Client:
8. Applications using TCP and UDP Sockets – DNS(Domain Name System)

import java.net.*;
import java.nio.ByteBuffer;

public class sdns {


public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress dnsServer = InetAddress.getByName("8.8.8.8");
int dnsPort = 53;

String domain = "google.com";

// Build DNS query


byte[] query = buildDnsQuery(domain);

DatagramPacket request = new DatagramPacket(query, query.length, dnsServer, dnsPort);


socket.send(request);
System.out.println("Sent DNS query for: " + domain);

byte[] buffer = new byte[512];


DatagramPacket response = new DatagramPacket(buffer, buffer.length);

socket.setSoTimeout(3000); // 3 seconds timeout


try {
socket.receive(response);
System.out.println("Received DNS response!");

// Optional: Print raw response


for (int i = 0; i < response.getLength(); i++) {
System.out.printf("%02X ", buffer[i]);
}
System.out.println();

} catch (SocketTimeoutException e) {
System.out.println("DNS Server did not respond (Timeout)");
}

socket.close();
}

private static byte[] buildDnsQuery(String domain) {


ByteBuffer buffer = ByteBuffer.allocate(512);

// Transaction ID
buffer.putShort((short) 0x1234);

// Flags: standard query


buffer.putShort((short) 0x0100);

// Questions, Answer RRs, Authority RRs, Additional RRs


buffer.putShort((short) 1); // Questions = 1
buffer.putShort((short) 0); // Answer RRs = 0
buffer.putShort((short) 0); // Authority RRs = 0
buffer.putShort((short) 0); // Additional RRs = 0

// Write domain name in DNS format


String[] labels = domain.split("\\.");
for (String label : labels) {
buffer.put((byte) label.length());
buffer.put(label.getBytes());
}
buffer.put((byte) 0x00); // End of domain name
// Query Type (A record)
buffer.putShort((short) 0x0001);

// Query Class (IN)


buffer.putShort((short) 0x0001);

byte[] query = new byte[buffer.position()];


buffer.flip();
buffer.get(query);
return query;
}
}

OUTPUT :-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy