0% found this document useful (0 votes)
305 views49 pages

Computer Networks Lab KCS 653

Computer Networks Lab Manual download, free lab manual download, AKTU lab manual download

Uploaded by

coderevisemail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
305 views49 pages

Computer Networks Lab KCS 653

Computer Networks Lab Manual download, free lab manual download, AKTU lab manual download

Uploaded by

coderevisemail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

Computer Networks Lab

Manual

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Computer Networks Lab (KCS-653)

1. Implementation of Stop and Wait Protocol and Sliding Window Protocol.


2. Study of Socket Programming and Client – Server model
3. Write a code simulating ARP /RARP protocols.
4. Write a code simulating PING and TRACEROUTE commands
5. Create a socket for HTTP for web page upload and download.
6. Write a program to implement RPC (Remote Procedure Call)
7. Implementation of Subnetting .
8. Applications using TCP Sockets like
a. Echo client and echo server b. Chat c. File Transfer
9. Applications using TCP and UDP Sockets like d. DNS e. SNMP f. File Transfer
10. Study of Network simulator (NS).and Simulation of Congestion Control Algorithms using NS
11. Perform a case study about the different routing algorithms to select the network path with its
optimum and economical during data transfer. i. Link State routing ii. Flooding iii. Distance vector
12. To learn handling and configuration of networking hardware like RJ-45 connector, CAT-6 cable,
crimping tool, etc.
13. Configuration of router, hub, switch etc. (using real devices or simulators)
14. Running and using services/commands like ping, traceroute, nslookup, arp, telnet, ftp, etc.
15.Network packet analysis using tools like Wireshark, tcpdump, etc.
16. Network simulation using tools like Cisco Packet Tracer, NetSim, OMNeT++, NS2, NS3, etc.
17.Socket programming using UDP and TCP (e.g., simple DNS, data & time client/server, echo
client/server, iterative & concurrent servers)

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 1

Objective: Implementation of Stop and Wait Protocol and Sliding Window Protocol.
Program: C programs to simulate data transfer operations using the Stop and Wait Protocol and the Sliding
Window Protocol.

Stop and Wait Protocol in C

Here, sender sends one frame and waits for an acknowledgment before sending the next frame. When the
receiver successfully receives the frame, sends an acknowledgment.

Program Code

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <time.h>

#define FRAME_COUNT 5

void sender(int frame);

int receiver(int frame);

int main() {

srand(time(0)); // Seed for random number generation

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

sender(i);

sleep(1); // Simulate delay

return 0;

void sender(int frame) {

printf("Sender: Sending frame %d\n", frame);

int ack = receiver(frame);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


if (ack == frame) {

printf("Sender: Received ACK for frame %d\n", frame);

} else {

printf("Sender: ACK not received, resending frame %d\n", frame);

sender(frame); // Resend the frame

int receiver(int frame) {

if (rand() % 10 < 9) { // 90% chance of successful receipt

printf("Receiver: Received frame %d, sending ACK\n", frame);

return frame;

} else {

printf("Receiver: Frame %d lost, no ACK sent\n", frame);

return -1; // Indicate frame loss

Output

Sliding Window Protocol in C

The sender send the multiple frames before getting any acknowledgments for the first frames. The window
size is set to 4.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Program Code

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <time.h>

#define WINDOW_SIZE 4

#define FRAME_COUNT 10

void sender();

void receiver(int frame);

void process_ack(int ack);

int sender_base = 0;

int next_seq_num = 0;

int acknowledged[FRAME_COUNT] = {0};

int main() {

srand(time(0)); // for random number generation

sender();

return 0;

void sender() {

while (sender_base < FRAME_COUNT) {

if (next_seq_num < sender_base + WINDOW_SIZE && next_seq_num < FRAME_COUNT) {

printf("Sender: Sending frame %d\n", next_seq_num);

receiver(next_seq_num);

next_seq_num++;

} else {

sleep(1); // for delay

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


}

void receiver(int frame) {

if (rand() % 10 < 9) { // 90% chance of successful receipt

printf("Receiver: Received frame %d, sending ACK\n", frame);

process_ack(frame);

} else {

printf("Receiver: Frame %d lost, no ACK sent\n", frame);

void process_ack(int ack) {

printf("Sender: Received ACK for frame %d\n", ack);

acknowledged[ack] = 1;

while (acknowledged[sender_base]) {

sender_base++;

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/
Experiment No. - 2

Objective: Study of Socket Programming and Client – Server model

Socket Programming
The process of creating software that can communicate over a network using sockets is known as
socket programming. A socket is used to sending or receiving data across the computer network.
Sockets can be used for communication on the same machine or on different machines.

Client-Server Model
The client-server model is a design pattern used in network applications where the server provides
resources or services, and the client accesses them.

Server: A program that waits for client requests and provides services. It usually runs on a specific
port number.
Client: A program that sends requests to the server and processes the server's responses.

Example of Socket Programming in Java

Server.java
import java.net.*;
import java.io.*;
public class ChatServer
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
ServerSocket ss=new ServerSocket(2345);
Socket skt=ss.accept( );
BufferedReader skt_in=new BufferedReader(new
InputStreamReader(skt.getInputStream( )));
PrintStream skt_out=new PrintStream(skt.getOutputStream( ));
while(true)
{
System.out.println(skt_in.readLine( ));
skt_out.println(“What is your name”);
yourname=skt_in.readLine( );

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


System.out.println(yourname);
String s=skt_in.readLine( );
System.out.println(s);
String myname=br.readLine( );
skt_out.println(myname);
break;
}
while(true)
{
String recv=skt_in.readLine( );
System.out.println(yourname+”:”+recv);
String send=br.readLine( );
skt_out.println(send);
}
}
catch(Exception e)
{
System.out.println(“Exception :”+e);
}}}

Client.java

import java.net.*;
import java.io.*;
public class ChatClient
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Socket skt=new Socket(“rungtaibm”,2345);
BufferedReader skt_in=new BufferedReader(new
InputStreamReader(skt.getInputStream( )));
PrintStream skt_out=new PrintStream(skt.getOutputStream( ));
while(true)
{
skt_out.println(“hello can I connect”);
skt_out.println(skt_in.readLine( ));
String myname=br.readLine( );
skt_out.println(myname);
skt_out.println(“What is yours”);
String yourname=skt_in.readLine( );
System.out.println(yourname);
break;
}
while(true)
{
String send=br.readLine( );
skt_out.println(send);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


String recv=skt_in.readLine( );
System.out.println(yourname +”:”+recv);
}
}
catch(Exception e)
{
System.out.println(“Exception :”+e);
}
}
}

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 3

Objective: Write a code simulating ARP /RARP protocols.


Devices communicate in a network simulation to resolve IP addresses to MAC addresses (ARP) or MAC
addresses to IP addresses (RARP) using the address resolution protocol (ARP) and the reverse address
resolution protocol (RARP).

Here we are performing implementations of ARP and RARP protocols in C programming.

ARP Simulation (Address Resolution Protocol):- ARP is used to resolve IP addresses to MAC addresses on a
local network.

Program Code

#include <stdio.h>

#include <string.h>

// Define a structure for ARP table entry

struct ARPEntry {

char ip_address[16]; // IPv4 address in string format (xxx.xxx.xxx.xxx)

char mac_address[18]; // MAC address in string format (xx:xx:xx:xx:xx:xx)

};

// Sample ARP table (can be expanded with more entries)

struct ARPEntry arp_table[] = {

{"192.168.1.1", "00:11:22:33:44:55"},

{"192.168.1.2", "11:22:33:44:55:66"},

{"192.168.1.3", "22:33:44:55:66:77"},

// Add more entries as needed

};

// Function to perform ARP resolution

void arp_resolve(const char* ip_address) {

int i;

int num_entry = sizeof(arp_table) / sizeof(struct ARPEntry);

int found = 0;

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


// Search the ARP table for the given IP address

for (i = 0; i < num_entry; i++) {

if (strcmp(arp_table[i].ip_address, ip_address) == 0) {

printf("ARP=> IP Address %s -> MAC Address %s\n", ip_address, arp_table[i].mac_address);

found = 1;

break;

if (!found) {

printf("ARP=> IP Address %s is not found in ARP table\n", ip_address);

int main() {

// Simulating ARP requests

arp_resolve("192.168.1.1");

arp_resolve("192.168.1.2");

arp_resolve("192.168.1.5"); // IP address not in ARP table

return 0;

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


RARP Simulation (Reverse Address Resolution Protocol): RARP is used to resolve MAC addresses
to IP addresses.

Program Code
#include <stdio.h>

#include <string.h>

// Structure of RARP table entry

struct RARPEntry {

char mac_address[18]; // MAC address

char ip_address[16]; // IPv4 address

};

// RARP table

struct RARPEntry rarp_table[] = {

{"00:11:22:33:44:55", "192.168.1.1"},

{"11:22:33:44:55:66", "192.168.1.2"},

{"22:33:44:55:66:77", "192.168.1.3"},

};

// Function to perform RARP resolution

void rarp_resolve(const char* mac_address) {

int i;

int num_entry = sizeof(rarp_table) / sizeof(struct RARPEntry);

int found = 0;

// Search the RARP table for the given MAC address

for (i = 0; i < num_entry; i++) {

if (strcmp(rarp_table[i].mac_address, mac_address) == 0) {

printf("RARP=> MAC Address %s -> IP Address %s\n", mac_address, rarp_table[i].ip_address);

found = 1;

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


break;

if (!found) {

printf("RARP=> MAC Address %s is not exist in RARP table\n", mac_address);

int main() {

// RARP requests

rarp_resolve("00:11:22:33:44:55");

rarp_resolve("11:22:33:44:55:66");

rarp_resolve("00:00:00:00:00:00"); // MAC address not in RARP table

return 0;

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 4

Objective: Write a code simulating PING and TRACEROUTE commands

Program: Java program for simulating PING command

import java.io.*;

import java.net.*;

class pinger

public static void main(String args[])

try

String str;

System.out.print(" Enter the IP Address to be Ping : ");

BufferedReader br1=new BufferedReader(new

InputStreamReader(System.in));

String ip=br1.readLine();

Runtime H=Runtime.getRuntime();

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

InputStream ins=p.getInputStream();

BufferedReader br2=new BufferedReader(new

InputStreamReader(ins));

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

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

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


catch(Exception e)

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

Output

Java program for simulating TRACEROUTE command

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class traceroute

public static void runSystemCommand(String command)

try

Process p = Runtime.getRuntime().exec(command);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));

String st = "";

while ((st = inputStream.readLine()) != null)

System.out.println(st);

catch (Exception e)

public static void main(String[] args)

String ip = "www.google.co.in";

runSystemCommand("tracert " + ip);

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 5

Objective: Create a socket for HTTP for web page upload and download

//HttpClient.java
import javax.swing.*;

import java.net.*;

import java.awt.image.*;

import javax.imageio.*;

import java.io.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

public class HttpClient{

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

BufferedImage img = null;

soc=new Socket("localhost",4000);

System.out.println("Client is running.... ");

try {

System.out.println("Reading image from disk. ");

img = ImageIO.read(new File("Java_logo.png")); ByteArrayOutputStream baos = new


ByteArrayOutputStream();

ImageIO.write(img, "jpg", baos);

baos.flush();

byte[] bytes = baos.toByteArray();

baos.close();

System.out.println("Sending image to server.... ");

OutputStream out = soc.getOutputStream();

DataOutputStream dos = new DataOutputStream(out);

dos.writeInt(bytes.length);

dos.write(bytes, 0, bytes.length);

System.out.println("Image sent to server. ");

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


dos.close();

out.close();

catch (Exception e)

System.out.println("Exception: " + e.getMessage());

soc.close();

soc.close();

HttpServer.java
import java.net.*;

import java.io.*;

import java.awt.image.*;

import javax.imageio.*;

import javax.swing.*;

class HttpServer {

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

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


dis.close();

in.close();

InputStream ian = new ByteArrayInputStream(data);

BufferedImage bImage = ImageIO.read(ian);

JFrame f = new JFrame("Server");

ImageIcon icon = new ImageIcon(bImage);

JLabel l = new JLabel();

l.setIcon(icon);

f.add(l);

f.pack();

f.setVisible(true);

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 6

Objective: Write a program to implement RPC (Remote Procedure Call)


RPC, or Remote Procedure Call, is a powerful technique for constructing distributed, client-server based
applications. RPC uses the client-server architecture where the client requests a service, and the server
provides it.

Advantages of RPC
Transparency: Makes remote procedure calls look like local ones, simplifying distributed application
development.

Abstraction: Abstracts the communication layer, allowing developers to focus on application logic.

Reusability: Encourages code reuse by separating client and server functionalities.

//serverPC.java
import java.io.*;

import java.net.*;

import java.util.*;

class serverPC

public static void main(String ar[])

try

ServerSocket obj1 = new ServerSocket(818);

while(true)

Socket obj2=obj1.accept();

DataInputStream dins= new DataInputStream(obj2.getInputStream());

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

String str=dins.readLine();

Process p=Runtime.getRuntime().exec(str);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


catch(Exception e)

System.out.println(e);

clientPC.java
import java.io.*;

import java.net.*;

import java.util.*;

class clientPC

public static void main(String ar[])

try

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

Socket soc=new Socket("127.0.0.1",818);

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

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

System.out.println("Enter a string : ");

String st = brin.readLine();

dout.writeBytes(st+'\n');

soc.close();

catch (Exception e1)

System.out.println(e1);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 7

Objective: Implementation of Subnetting.


Program: Write a java program to implement sub netting and find the subnet masks.

//Subnetting.java

import java.util.Scanner;

public class Subnetting

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

// input IP address and prefix length

System.out.print("Enter IP address (for exam., 192.168.1.1): ");

String ipAddress = scanner.nextLine();

System.out.print("Enter prefix length (for exam., 24): ");

int prefixLength = scanner.nextInt();

// Calculate subnet mask

String subnetMask = calculateSubnetMask(prefixLength);

System.out.println("Subnet Mask: " + subnetMask);

// Calculate network address

String networkAddress = calculateNetworkAddress(ipAddress, subnetMask);

System.out.println("Network Address: " + networkAddress);

// Calculate broadcast address

String broadcastAddress = calculateBroadcastAddress(networkAddress, subnetMask);

System.out.println("Broadcast Address: " + broadcastAddress);

// Calculate range of valid host addresses

String[] hostRange = calculateHostRange(networkAddress, broadcastAddress);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


System.out.println("Host Range: " + hostRange[0] + " - " + hostRange[1]);

scanner.close();

private static String calculateSubnetMask(int prefixLength)

int mask = 0xffffffff << (32 - prefixLength);

return String.format("%d.%d.%d.%d",(mask >>> 24) & 0xff,(mask >>> 16) & 0xff,(mask >>> 8) & 0xff,mask &
0xff);

private static String calculateNetworkAddress(String ipAddress, String subnetMask)

String[] ipParts = ipAddress.split("\\.");

String[] maskParts = subnetMask.split("\\.");

int[] networkParts = new int[4];

for (int i = 0; i < 4; i++)

networkParts[i] = Integer.parseInt(ipParts[i]) & Integer.parseInt(maskParts[i]);

return String.format("%d.%d.%d.%d", networkParts[0], networkParts[1], networkParts[2],


networkParts[3]);

private static String calculateBroadcastAddress(String networkAddress, String subnetMask) {

String[] networkParts = networkAddress.split("\\.");

String[] maskParts = subnetMask.split("\\.");

int[] broadcastParts = new int[4];

for (int i = 0; i < 4; i++)

broadcastParts[i] = Integer.parseInt(networkParts[i]) | (~Integer.parseInt(maskParts[i]) & 0xff);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


}

return String.format("%d.%d.%d.%d", broadcastParts[0], broadcastParts[1], broadcastParts[2],


broadcastParts[3]);

private static String[] calculateHostRange(String networkAddress, String broadcastAddress) {

String[] networkParts = networkAddress.split("\\.");

String[] broadcastParts = broadcastAddress.split("\\.");

int[] startParts = new int[4];

int[] endParts = new int[4];

for (int i = 0; i < 4; i++)

startParts[i] = Integer.parseInt(networkParts[i]);

endParts[i] = Integer.parseInt(broadcastParts[i]);

startParts[3] += 1; // Start host range (network address + 1)

endParts[3] -= 1; // End host range (broadcast address - 1)

String startIp = String.format("%d.%d.%d.%d", startParts[0], startParts[1], startParts[2], startParts[3]);

String endIp = String.format("%d.%d.%d.%d", endParts[0], endParts[1], endParts[2], endParts[3]);

return new String[]{startIp, endIp};

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 8 (a)

Objective: Applications using TCP Sockets like (Echo client and echo server)
Program: Write a java program for echo client and echo server using TCP sockets.

// EchoServer.java

import java.io.*;

import java.net.*;

public class EchoServer {

public static void main(String[] args) {

int port = 12345; // Port number to listen on

try (ServerSocket serverSocket = new ServerSocket(port)) {

System.out.println("Echo Server started on port " + port);

while (true) {

try (Socket clientSocket = serverSocket.accept();

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

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()))) {

System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

String inputLine;

while ((inputLine = in.readLine()) != null) {

System.out.println("Received: " + inputLine);

out.println(inputLine); // Echo the input back to client

} catch (IOException e) {

System.out.println("Exception caught when trying to listen on port "

+ port + " or listening for a connection");

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

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


}

} catch (IOException e) {

System.out.println("Could not listen on port " + port);

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

// EchoClient.java

import java.io.*;

import java.net.*;

public class EchoClient {

public static void main(String[] args) {

String hostname = "localhost"; // Server hostname

int port = 12345; // Server port number

try (Socket echoSocket = new Socket(hostname, port);

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

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

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

System.out.println("Connected to Echo Server");

String userInput;

System.out.println("Type a message to send to the server (type 'bye' to quit):");

while ((userInput = stdIn.readLine()) != null) {

out.println(userInput);

if ("bye".equalsIgnoreCase(userInput)) {

break;

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


}

System.out.println("Echo from server: " + in.readLine());

} catch (UnknownHostException e) {

System.err.println("Don't know about host " + hostname);

System.exit(1);

} catch (IOException e) {

System.err.println("Couldn't get I/O for the connection to " + hostname);

System.exit(1);

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 8 (b)

Objective: Applications using TCP Sockets (like chat)


Program: Write a java program for chat using TCP sockets.

ChatServer.java
import java.io.*;

import java.net.*;

public class ChatServer {

private static final int PORT = 1248;

public static void main(String[] args) {

System.out.println("Chat Server started...");

try (ServerSocket serverSocket = new ServerSocket(PORT)) {

Socket clientSocket = serverSocket.accept();

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

// Input and output streams for communicating with the client

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

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

// Thread for getting incoming messages from client

new Thread(() -> {

String message;

try {

while ((message = in.readLine()) != null) {

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

} catch (IOException e) {

System.out.println("Connection closed.");

}).start();

// Read messages and forward them to client

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


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

String message;

while ((message = consoleInput.readLine()) != null) {

out.println(message);

} catch (IOException e) {

e.printStackTrace();

//ChatClient.java
import java.io.*;

import java.net.*;

public class ChatClient {

private static final String SERVER_ADDRESS = "localhost";

private static final int PORT = 1248;

public static void main(String[] args) {

System.out.println("Chat Client started...");

try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {

// Input and output streams for communicating with the server

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

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

// Thread to get incoming messages from server

new Thread(() -> {

String message;

try {

while ((message = in.readLine()) != null) {

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

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


}

} catch (IOException e) {

System.out.println("Connection closed.");

}).start();

// Read messages and send them to the server

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

String message;

while ((message = consoleInput.readLine()) != null) {

out.println(message);

} catch (IOException e) {

e.printStackTrace();

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 8 (c)

Objective: Applications using TCP Sockets (like file transfer)


Program: Write a java program for file transfer using TCP sockets.

//FileServer.java
import java.io.*;

import java.net.*;

public class FileServer {

private static final int PORT = 1248;

private static final String FILE_TO_SEND = "tmp/sendfile.txt";

public static void main(String[] args) {

System.out.println("File Server started...");

try (ServerSocket serverSocket = new ServerSocket(PORT)) {

Socket clientSocket = serverSocket.accept();

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

File file = new File(FILE_TO_SEND);

byte[] fileBytes = new byte[(int) file.length()];

// Read the file into the byte array

try (FileInputStream fileInputStream = new FileInputStream(file)) {

fileInputStream.read(fileBytes);

// Send the file size to the client

DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

out.writeLong(fileBytes.length);

// Send the file bytes to the client

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


out.write(fileBytes);

out.flush();

System.out.println("File sent successfully.");

} catch (IOException e) {

e.printStackTrace();

//FileClient.java
import java.io.*;

import java.net.*;

public class FileClient {

private static final String SERVER_ADDRESS = "localhost";

private static final int PORT = 1248;

private static final String FILE_TO_RECEIVE = "tmp/recievefile.txt";

public static void main(String[] args) {

System.out.println("File Client started...");

try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {

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

// Receive the file size from the server

long fileSize = in.readLong();

byte[] fileBytes = new byte[(int) fileSize];

// Receive the file in bytes from server

in.readFully(fileBytes);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


// Save the received file

try (FileOutputStream fileOutputStream = new FileOutputStream(FILE_TO_RECEIVE)) {

fileOutputStream.write(fileBytes);

System.out.println("File received successfully.");

} catch (IOException e) {

e.printStackTrace();

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 9 (a)

Objective: Applications using TCP and UDP Sockets (like DNS)


Program: Write a java program for DNS application.

//DNSServer.java

import java.io.*;

import java.net.*;

import java.util.*;

public class DNSServer {

private static final int PORT = 1248;

public static void main(String[] args) {

System.out.println("DNS Server started...");

try (ServerSocket serverSocket = new ServerSocket(PORT)) {

while (true) {

try (Socket clientSocket = serverSocket.accept()) {

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

// Input and output streams for communicating with the client

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));

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

// Read domain name from client

String domainName = in.readLine();

System.out.println("Received domain name: " + domainName);

// Resolve the domain name to an IP address

String ipAddress = resolveDomainName(domainName);

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


// Send the IP address back to the client

out.println(ipAddress);

System.out.println("Sent IP address: " + ipAddress);

} catch (IOException e) {

System.out.println("Connection error: " + e.getMessage());

} catch (IOException e) {

e.printStackTrace();

private static String resolveDomainName(String domainName) {

try {

InetAddress inetAddress = InetAddress.getByName(domainName);

return inetAddress.getHostAddress();

} catch (UnknownHostException e) {

return "Unknown host";

//DNSClient.java
import java.io.*;
import java.net.*;
public class DNSClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int PORT = 1248;

public static void main(String[] args) {


try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


// Input and output streams for communicating with the server
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Read domain name from the console


BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter domain name: ");
String domainName = consoleInput.readLine();

// Send domain name to the server


out.println(domainName);

// Read and display the IP address from the server


String ipAddress = in.readLine();
System.out.println("IP address: " + ipAddress);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - (c)

Objective: Applications using TCP and UDP Sockets (like file transfer)
Program: Write a java program for file transfer using UDP sockets.

//UDPFileServer.java
import java.io.*;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPFileServer {

public static void main(String[] args) {

int port = 9313;

DatagramSocket socket = null;

try {

socket = new DatagramSocket(port);

System.out.println("UDP Server started. Waiting for packets...");

byte[] buffer = new byte[4096];

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

FileOutputStream fileOutputStream = new FileOutputStream("tmp/getfile.txt");

boolean receiving = true;

while (receiving) {

socket.receive(packet);

fileOutputStream.write(packet.getData(), 0, packet.getLength());

// Assuming end of file transmission

if (packet.getLength() < 4096) {

receiving = false;

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


}

System.out.println("File received.");

fileOutputStream.close();

socket.close();

} catch (IOException e) {

e.printStackTrace();

//UDPFileClient.java
import java.io.*;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPFileClient {

public static void main(String[] args) {

String serverAddress = "localhost";

int port = 9313;

DatagramSocket socket = null;

try {

socket = new DatagramSocket();

InetAddress serverInetAddress = InetAddress.getByName(serverAddress);

FileInputStream fileInputStream = new FileInputStream("tmp/sendfile.txt");

byte[] buffer = new byte[4096];

int bytesRead;

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


while ((bytesRead = fileInputStream.read(buffer)) != -1) {

DatagramPacket packet = new DatagramPacket(buffer, bytesRead, serverInetAddress, port);

socket.send(packet);

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

fileInputStream.close();

socket.close();

} catch (IOException e) {

e.printStackTrace();

Output

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 10

Objective: Study of Network simulator (NS).and Simulation of Congestion Control


Algorithms using NS

Assignment: Explain Network simulator (NS) and Simulation of Congestion Control Algorithms using NS.

Network Simulator (NS)


A Network Simulator (NS) is a tool that helps the people to study and understand how networks work.
Instead of setting up a real network with actual devices, you can use NS to create a virtual network on your
computer. This is useful for learning, testing new ideas, and seeing how different network setups perform.

Key Features of Network Simulator:


Virtual Networks: You can build a pretend network with computers and routers.

Testing Protocols: Try out different rules for how data moves through the network, like TCP and UDP.

Making Traffic: Create fake data to see how it affects the network.

Performance Checks: Measure things like how fast data moves, how long it takes, and if any data gets lost.

Customizable: You can add your own ideas and test new network protocols.

Simulating Congestion Control Algorithms with NS

Congestion control helps prevent networks from getting too crowded, which can slow down data. Using NS
to test these control methods helps researchers find the best ways to manage network traffic.

Steps to Simulate Congestion Control Algorithms:


Build Your Network: Set up a virtual network with computers and routers.

Add Congestion Control Methods: Put in different methods to control network traffic, like TCP Reno or TCP
Vegas.

Create Network Traffic: Make pretend data flows to see how the network handles different amounts of
traffic.

Run the Simulation: Start the virtual network and watch how it performs with the traffic you created.

Gather Results: Collect data on how well the network did, such as speed and data loss.

Compare Methods: Look at the results to see which congestion control method worked best.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 11

Objective: Perform case study on different routing algorithms.

1. Link State routing

Link State Routing is a method used in computer networks to figure out the best paths for data to travel.
Unlike another method called distance-vector routing, where routers share their whole list of paths with
their neighbours, Link State Routing has each router keeping a full map of the network. This helps routers
make better decisions about where to send data. One of the most well-known protocols that use Link State
Routing is called Open Shortest Path First, or OSPF.

Key Features of Link State Routing

Network Topology Awareness: Each router has a full view of the network topology.

Link State Advertisements (LSAs): Routers periodically broadcast information to neighbors.

Shortest Path First (SPF) Algorithm: Uses algorithms like Dijkstra’s to compute the shortest path.

Fast Convergence: Quickly adapt network changes and recalculates optimal paths.

2. Flooding

Flooding is a simple routing algorithm where every incoming packet is sent out on every outgoing line,
except the one it arrived on. This ensures that packets reach every node in the network, but can lead to
excessive redundancy and bandwidth usage.

Key Features of Flooding

Optimality: Guarantees that the packet reaches every node.

Economy: Highly inefficient due to excessive redundancy. Every node may receive multiple copies of the
same packet, leading to high bandwidth consumption and potential network congestion.

3. Distance vector Routing

Distance Vector Routing is a routing protocol used in computer networks to determine the best path for
data packets to travel from a source to a destination. It is based on the Bellman-Ford algorithm and is one
of the simplest types of routing protocols.

Each router maintains a table (or vector) that holds the distance (or cost) to every other router in the
network. This table is updated periodically based on information received from neighbouring routers.

Bellman-Ford Algorithm calculates the shortest path from a single source node to all other nodes in a
weighted graph. It helps to determine the shortest path to each destination.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Key Features of Distance Vector Routing

1. Initialization: Each router initializes its routing table with the direct distances between its immediate
neighbours. For all other destinations, the distance is set to infinity (unknown).

2. Periodic Updates: Routers periodically exchange routing tables with their immediate neighbours. Each
router updates own routing table based on the received information. If a router learns of a shorter path to
a destination through a neighbour, it updates its table with the new distance and next hop.

3. Bellman-Ford Update Rule: The routing table is updated using the Bellman-Ford equation:

Dv(y) = min (c(x, y) + Dx(y))


Here Dv(y) is the distance from router v to destination y, c(x, y) is the cost to reach neighbour x, and
Dx(y) is the distance from x to y.

4. Convergence: Over time, the routing tables across the network converge, meaning they become stable
and reflect the shortest paths to all destinations.

Performance Results

Algorithm Bandwidth Usage Delay Processing Power Scalability Optimality


Link State Low Low High Excellent Optimal path
Flooding High High Low Poor Guaranteed reach
Distance Vector Medium Medium Medium Moderate Good

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 12

Objective: To learn handling and configuration of networking hardware like RJ-45 connector, CAT-
6 cable, crimping tool, etc.

Learning how to use and install networking hardware including RJ-45 connectors, CAT-6 cables, and
crimping tools. These devices are necessary for establishing and maintaining network infrastructure. Here's
an easy guide to learn:

Tools and Materials Needed

CAT-6 Cable: The network cable.


RJ-45 Connectors: The connectors used to terminate the CAT-6 cable.
Crimping Tool: Used to attach RJ-45 connectors to the CAT-6 cable.
Cable Stripper: For stripping the outer jacket of the cable.
Cable Tester: To verify the connections are correct and functional.

Steps to Prepare and Crimp a CAT-6 Cable

1. Measure and Cut the Cable: Determine the length of cable you need and cut it to size using a cable
cutter.

2. Strip the Outer Jacket: Use the cable stripper to remove about 1-2 inches of the outer jacket from both
ends of the cable, exposing the twisted pairs inside.Be careful not to nick the wires inside while stripping
the jacket.

3. Untwist and Arrange the Wires: Untwist the pairs of wires and arrange them according to the T568B
wiring standard (most commonly used):

1) White/Orange
2) Orange
3) White/Green
4) Blue
5) White/Blue
6) Green
7) White/Brown
8) Brown

4. Cut the Wires Evenly: Ensure all the wires are flat and in the correct order, then cut them evenly to
about 0.5 inches in length from the jacket.

5. Insert Wires into the RJ-45 Connector: Holding the RJ-45 connector with the clip facing down, carefully
insert the wires into the connector, ensuring each wire goes into its correct slot. The wires should reach the
end of the connector.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


6. Crimp the Connector: Place the RJ-45 connector into the crimping tool and squeeze the handle firmly to
crimp the connector onto the cable. Repeat the process for the other end of the cable.

7. Test the Cable: Use a cable tester to verify that each wire is correctly connected and there are no shorts
or miss wires. Insert both ends of the cable into the tester and check the results.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Experiment No. - 14

Objective: Running and using services/commands like ping, traceroute, nslookup, arp,
telnet, ftp, etc.

Using various network commands you can diagnose and troubleshoot the network issues. Here are some
common networking commands with explanation:

1. Ping

Ping is used to test the reachability of a host on an IP network and to measure the round-trip time from the
originating host to the destination computer.

Syntax:

ping <hostname or IP address>

Example:

ping google.com

This command sends ICMP Echo Request messages to google.com and displays the time it takes for each
message to return.

2. Traceroute

Traceroute tracks the path packets take from one network host to another, showing each hop along the
way.

Syntax:

traceroute <hostname or IP address>

Example:

traceroute google.com

This command will list all the routers the packets pass through to reach google.com.

3. Nslookup

Nslookup queries the Domain Name System (DNS) to obtain domain name or IP address mapping
information.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Syntax:

nslookup <hostname>

Example:

nslookup google.com

This command will return the IP address associated with google.com.

4. ARP

ARP (Address Resolution Protocol) is used to map IP addresses to MAC addresses, allowing devices to find
each other on a local network.

Syntax:

arp -a

Example:

arp –a

This command will display the ARP table, showing the IP addresses and their corresponding MAC addresses.

5. Telnet

Telnet is a protocol used to remotely access another computer over a network. It is often used for
managing network devices.

Syntax:

telnet <hostname or IP address> <port>

Example:

telnet 192.168.1.1 23

This command will attempt to connect to the device at 192.168.1.1 on port 23.

6. FTP

FTP (File Transfer Protocol) is used to transfer files between computers on a network.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/


Syntax:

ftp <hostname or IP address>

Example:

ftp ftp.example.com

This command connects to an FTP server at ftp.example.com. Once connected, you can use commands like
put to upload files and get to download files.

7. SSH

SSH (Secure Shell) is used to securely access a remote device over a network.

Syntax:

ssh <username>@<hostname or IP address>

Example:

ssh user@192.168.1.1

This command will connect to the device at 192.168.1.1 using the username user.

www.CodeRevise.com Download without watermark => https://coderevise.com/lab-manual/

You might also like