0% found this document useful (0 votes)
19 views32 pages

CN Lab Manual 3rd Year

The document is a lab manual for a Computer Networks course at the Vision Institute of Technology, detailing various programming assignments related to networking protocols and socket programming in Java. It includes implementations of protocols like Stop and Wait, Sliding Window, ARP, RARP, and Remote Procedure Call (RPC), along with client-server models and subnetting calculations. The manual aims to equip students with practical skills in network design, traffic analysis, and programming using tools like Cisco Packet Tracer and Wireshark.
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)
19 views32 pages

CN Lab Manual 3rd Year

The document is a lab manual for a Computer Networks course at the Vision Institute of Technology, detailing various programming assignments related to networking protocols and socket programming in Java. It includes implementations of protocols like Stop and Wait, Sliding Window, ARP, RARP, and Remote Procedure Call (RPC), along with client-server models and subnetting calculations. The manual aims to equip students with practical skills in network design, traffic analysis, and programming using tools like Cisco Packet Tracer and Wireshark.
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/ 32

Vision Institute of Technology, Aligarh

B.Tech Computer Science 3rd year

Computer Network Lab Manual

BCS 653

Prepared by : Dr Naveen Singh


Course Outcomes

Subject Name: Computer Networks Lab Subject code: BCS-653

The students are expected to be able to demonstrate the following knowledge, skills and attitudes
after completing this course:

1. To understand the basic concepts of network devices and connectivity.

2. To analyze network traffic using wire shark tool.

3. To design and configure a network using Cisco Packet Tracer.

4. To implement a client/server chatting program using socket programming


Program 1 Implementation of Stop and wait protocol and sliding window protocol

1. Sender Implementation:
File Name: Sender.java

1. import java.io.*;
2. import java.net.*;
3. public class Sender {
4. public static void main(String[] args) throws Exception {
5. DatagramSocket socket = new DatagramSocket();
6. InetAddress receiverAddress = InetAddress.getByName("localhost");
7. int receiverPort = 9876;
8. int windowSize = 4;
9. byte[] data = "Hello, Sliding Window!".getBytes();
10. int base = 0;
11. while (base < data.length) {
12. for (int i = base; i < base + windowSize && i < data.length; i++) {
13. DatagramPacket packet = new DatagramPacket(data, i, 1, receiverAddress, receiverPor
t);
14. socket.send(packet);
15. }
16. DatagramPacket ackPacket = new DatagramPacket(new byte[1], 1);
17. socket.receive(ackPacket);
18. int ack = ackPacket.getData()[0];
19. if (ack >= base) {
20. base = ack + 1;
21. }
22. }
23. socket.close();
24. }
25. }

Output:

Sent: H
Sent: e
Sent: l
Sent: l
Received ACK: 0
Sent: o
Sent: ,
Sent: S
Received ACK: 1
Sent: l
Sent: i
Sent: d
Received ACK: 2
Sent: i
Sent: n
Received ACK: 3
Sent: g
Sent:
Received ACK: 4
Sent: W
Sent: i
Sent: n
Sent: d
Received ACK: 5
Sent: o
Sent: w
Sent: !
Received ACK: 6

2. Receiver Implementation:
File Name: Receiver.java

1. import java.io.*;
2. import java.net.*;
3. public class Receiver {
4. public static void main(String[] args) throws Exception {
5. DatagramSocket socket = new DatagramSocket(9876);
6. int expectedSeqNum = 0;
7. while (true) {
8. DatagramPacket packet = new DatagramPacket(new byte[1], 1);
9. socket.receive(packet);
10. int seqNum = packet.getData()[0];
11. if (seqNum == expectedSeqNum) {
12. System.out.println("Received: " + seqNum);
13. DatagramPacket ackPacket = new DatagramPacket(new byte[] { (byte) seqNum }, 1, p
acket.getAddress(), packet.getPort());
14. socket.send(ackPacket);
15. expectedSeqNum++;
16. }
17. }
18. }
19. }

Output:

Received: 0
Received: 1
Received: 2
Received: 3
Received: 4
Received: 5
Received: 6

Program 2 Study of Socket programming and Client Server model

A Java program for a Client

import java.io.*;

import java.net.*;

public class Client {

// initialize socket and input output streams

private Socket socket = null;

private DataInputStream input = null;

private DataOutputStream out = null;

// constructor to put ip address and port

public Client(String address, int port)

{
// establish a connection

try {

socket = new Socket(address, port);

System.out.println("Connected");

// takes input from terminal

input = new DataInputStream(System.in);

// sends output to the socket

out = new DataOutputStream(

socket.getOutputStream());

catch (UnknownHostException u) {

System.out.println(u);

return;

catch (IOException i) {

System.out.println(i);

return;

}
// string to read message from input

String line = "";

// keep reading until "Over" is input

while (!line.equals("Over")) {

try {

line = input.readLine();

out.writeUTF(line);

catch (IOException i) {

System.out.println(i);

// close the connection

try {

input.close();

out.close();

socket.close();

catch (IOException i) {
System.out.println(i);

public static void main(String args[])

Client client = new Client("127.0.0.1", 5000);

Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
 A ServerSocket which waits for the client requests (when a client makes a new Socket())
 A plain old Socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing the socket as well as
input/output streams.
 Java

// A Java program for a Server

import java.net.*;

import java.io.*;

public class Server


{

//initialize socket and input stream

private Socket socket = null;

private ServerSocket server = null;

private DataInputStream in = null;

// constructor with port

public Server(int port)

// starts server and waits for a connection

try

server = new ServerSocket(port);

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

System.out.println("Waiting for a client ...");

socket = server.accept();

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

// takes input from the client socket


in = new DataInputStream(

new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Over" is sent

while (!line.equals("Over"))

try

line = in.readUTF();

System.out.println(line);

catch(IOException i)

System.out.println(i);

System.out.println("Closing connection");
// close connection

socket.close();

in.close();

catch(IOException i)

System.out.println(i);

public static void main(String args[])

Server server = new Server(5000);

Important Points
 Server application makes a ServerSocket on a specific port which is 5000. This starts our
Server listening for client requests coming in for port 5000.
 Then Server makes a new Socket to communicate with the client.
socket = server.accept()
 The accept() method blocks(just sits there) until a client connects to the server.
 Then we take input from the socket using getInputStream() method. Our Server keeps
receiving messages until the Client sends “Over”.
 After we’re done we close the connection by closing the socket and the input stream.
 To run the Client and Server application on your machine, compile both of them. Then first
run the server application and then run the Client application.
To run on Terminal or Command Prompt
Open two windows one for Server and another for Client
1. First run the Server application as,
$ java Server
Server started
Waiting for a client …
2. Then run the Client application on another terminal as,
$ java Client
It will show – Connected and the server accepts the client and shows,
Client accepted
3. Then you can start typing messages in the Client window. Here is a sample input to the
Client
Hello
I made my first socket connection
Over
Which the Server simultaneously receives and shows,
Hello
I made my first socket connection
Over
Closing connection
Notice that sending “Over” closes the connection between the Client and the Server just like
said before.
If you’re using Eclipse or likes of such-
1. Compile both of them on two different terminals or tabs
2. Run the Server program first
3. Then run the Client program
4. Type messages in the Client Window which will be received and shown by the Server
Window simultaneously.
5. Type Over to end.

Program 3 Write a code simulating ARP and RARP protocols

ALGORITHM:

Client

1. Start the program


2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.
Server

1. Start the program


2. Accept the socket which is created by the client.
3. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Read the IP address which is send by the client.
5. Map the IP address with its MAC address and return the MAC address to client.

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

try
{

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


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

{
System.out.println(e);
}
}
}

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

}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2

Result: Thus the ARP protocol using TCP Sockets program was executed.
Program 4 To write a java program for simulating RARP protocols using UDP
ALGORITHM

Client

1. Start the program


2. using datagram sockets UDP function is established.
2. Get the MAC address to be converted into IP address.
3. Send this MAC address to server.
4. Server returns the IP address to client.

Server

1. Start the program.


2. Server maintains the table in which IP and corresponding MAC addresses are stored.
3. Read the MAC address which is send by the client.
4. Map the IP address with its MAC address and return the IP address to client.

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

DatagramSocket client=new DatagramSocket();


InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical address (MAC):");
String str=in.readLine(); sendbyte=str.getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);

String s=new String(receiver.getData());


System.out.println("The Logical Address is(IP): "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

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

DatagramSocket server=new DatagramSocket(1309);


while(true)
{

byte[] sendbyte=new byte[1024];


byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
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(s.equals(mac[i]))
{
sendbyte=ip[i].getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender); break;
}
}
break;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
I:\ex>java Serverrarp12 I:\ex>java
Clientrarp12
Enter the Physical address (MAC):
6A:08:AA:C2
The Logical Address is(IP): 165.165.80.80

Result : Thus the RARP program using UDP was executed.

Program 5
Remote Procedure Call (RPC) in Java using Java RMI (Remote Method Invocation), which is
Java's built-in support for RPC-style communication.

1. Adder.java – Remote Interface

java
CopyEdit
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Adder extends Remote {


int add(int x, int y) throws RemoteException;
}

2. AdderImpl.java – Implementation of the Interface


java
CopyEdit
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class AdderImpl extends UnicastRemoteObject implements Adder {

protected AdderImpl() throws RemoteException {


super();
}

public int add(int x, int y) throws RemoteException {


return x + y;
}
}

3. Server.java – Registering the Remote Object

java
CopyEdit
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class Server {


public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099); // Start RMI registry on port 1099
Adder adder = new AdderImpl();
Naming.rebind("rmi://localhost

Program 6

Enter IP address: 192.168.1.0


Enter number of subnets: 4
Java Program – Subnetting Implementation
import java.util.Scanner;

public class Subnetting {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter IP address (e.g., 192.168.1.0): ");


String ip = scanner.nextLine();
System.out.print("Enter number of subnets: ");
int subnets = scanner.nextInt();

String[] parts = ip.split("\\.");


int[] ipParts = new int[4];
for (int i = 0; i < 4; i++) {
ipParts[i] = Integer.parseInt(parts[i]);
}

// Subnet calculation (for Class C)


int borrowedBits = (int) Math.ceil(Math.log(subnets) / Math.log(2));
int subnetMask = 256 - (int) Math.pow(2, 8 - borrowedBits);
int totalSubnets = (int) Math.pow(2, borrowedBits);
int hostsPerSubnet = (int) Math.pow(2, 8 - borrowedBits) - 2;

System.out.println("\nBorrowed bits: " + borrowedBits);


System.out.println("Subnet mask: 255.255.255." + subnetMask);
System.out.println("Total subnets: " + totalSubnets);
System.out.println("Hosts per subnet: " + hostsPerSubnet);

int increment = 256 / totalSubnets;

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


int subnetStart = i * increment;
int subnetEnd = subnetStart + increment - 1;
System.out.println("\nSubnet " + (i + 1) + ":");
System.out.println("Network Address: " + ipParts[0] + "." + ipParts[1] + "." + ipParts[2] +
"." + subnetStart);
System.out.println("First Host: " + ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "." +
(subnetStart + 1));
System.out.println("Last Host: " + ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "." +
(subnetEnd - 1));
System.out.println("Broadcast Address: " + ipParts[0] + "." + ipParts[1] + "." + ipParts[2] +
"." + subnetEnd);
}

scanner.close();
}
}
Sample Output:
yaml
Copy
Edit
Enter IP address (e.g., 192.168.1.0): 192.168.1.0
Enter number of subnets: 4

Borrowed bits: 2
Subnet mask: 255.255.255.192
Total subnets: 4
Hosts per subnet: 62

Subnet 1:
Network Address: 192.168.1.0
First Host: 192.168.1.1
Last Host: 192.168.1.62
Broadcast Address: 192.168.1.63
Subnet 2:
Network Address: 192.168.1.64
First Host: 192.168.1.65
Last Host: 192.168.1.126
Broadcast Address: 192.168.1.127
...

Program 7
Applications using TCP and UDP Sockets like a. DNS b. SNMP c. File Transfer in JAVA

a) DNS Client using UDP Socket in Java

import java.net.*;

public class DNSClient {


public static void main(String[] args) {
try {
String domain = "example.com";
InetAddress ip = InetAddress.getByName(domain);
System.out.println("IP address of " + domain + " is: " + ip.getHostAddress());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

☑ This uses Java's built-in DNS resolution (UDP under the hood).

✅(b) SNMP-Like Simulation using UDP Socket

Java does not have a native SNMP API, but we can simulate a basic UDP request/response mechanism
similar to SNMP polling.

SNMP-like Server (UDP)

java
CopyEdit
import java.net.*;

public class SNMPServer {


public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket(5000)) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

System.out.println("SNMP-like Server running...");


socket.receive(packet);

String request = new String(packet.getData(), 0, packet.getLength());


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

String response = "System Uptime: 10234 seconds";


byte[] responseBytes = response.getBytes();

DatagramPacket responsePacket = new DatagramPacket(


responseBytes, responseBytes.length,
packet.getAddress(), packet.getPort());

socket.send(responsePacket);
} catch (Exception e) {
e.printStackTrace();
}
}
}

SNMP-like Client (UDP)

java
CopyEdit
import java.net.*;

public class SNMPClient {


public static void main(String[] args) {
try (DatagramSocket socket = new DatagramSocket()) {
String message = "GET sysUptime";
byte[] buffer = message.getBytes();

InetAddress address = InetAddress.getByName("localhost");


DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 5000);
socket.send(packet);

byte[] response = new byte[1024];


DatagramPacket responsePacket = new DatagramPacket(response, response.length);
socket.receive(responsePacket);

String reply = new String(responsePacket.getData(), 0, responsePacket.getLength());


System.out.println("Response: " + reply);
} catch (Exception e) {
e.printStackTrace();
}
}
}

(c) File Transfer using TCP in Java

FileServer.java (TCP)

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

public class FileServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(6000)) {
System.out.println("File server waiting for connection...");
Socket socket = serverSocket.accept();

FileInputStream fis = new FileInputStream("sample.txt");


BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

byte[] buffer = new byte[1024];


int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}

bos.flush();
fis.close();
socket.close();
System.out.println("File sent.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

FileClient.java (TCP)

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

public class FileClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 6000)) {
InputStream in = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("received.txt");

byte[] buffer = new byte[1024];


int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}

fos.close();
System.out.println("File received and saved as received.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Program 8

Java Program to Run Network Commands

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class NetworkCommands {

public static void runCommand(String command) {


try {
ProcessBuilder pb = new ProcessBuilder(command.split(" "));
pb.redirectErrorStream(true);
Process process = pb.start();

BufferedReader reader = new BufferedReader(


new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

process.waitFor();
} catch (Exception e) {
System.out.println("Error running command: " + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("=== PING ===");
runCommand("ping -c 4 google.com"); // Use `-n` on Windows

System.out.println("\n=== TRACEROUTE ===");


runCommand("traceroute google.com"); // Use `tracert` on Windows

System.out.println("\n=== NSLOOKUP ===");


runCommand("nslookup google.com");

System.out.println("\n=== ARP TABLE ===");


runCommand("arp -a");

// Telnet and FTP are interactive; we show basic usage


System.out.println("\n=== TELNET (will not work unless service is available) ===");
runCommand("telnet towel.blinkenlights.nl");

System.out.println("\n=== FTP (may fail if no service or credentials) ===");


runCommand("ftp");

// You can add commands like netstat, ipconfig/ifconfig similarly


}
}

Program 9

Java Code: Link State Routing (Dijkstra)

import java.util.*;

class Graph {
private int vertices;
private int[][] adjacencyMatrix;

public Graph(int v) {
this.vertices = v;
adjacencyMatrix = new int[v][v];
}

public void addEdge(int src, int dest, int weight) {


adjacencyMatrix[src][dest] = weight;
adjacencyMatrix[dest][src] = weight; // undirected graph
}

public void dijkstra(int source) {


int[] dist = new int[vertices];
boolean[] visited = new boolean[vertices];
int[] parent = new int[vertices];

Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
parent[source] = -1;

for (int i = 0; i < vertices - 1; i++) {


int u = minDistance(dist, visited);
visited[u] = true;

for (int v = 0; v < vertices; v++) {


if (!visited[v] && adjacencyMatrix[u][v] != 0 &&
dist[u] + adjacencyMatrix[u][v] < dist[v]) {
parent[v] = u;
dist[v] = dist[u] + adjacencyMatrix[u][v];
}
}
}

printPaths(source, dist, parent);


}

private int minDistance(int[] dist, boolean[] visited) {


int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < vertices; v++) {
if (!visited[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}

private void printPaths(int source, int[] dist, int[] parent) {


System.out.println("Router\t Distance from Source\tPath");
for (int i = 0; i < vertices; i++) {
if (i != source) {
System.out.print(source + " -> " + i + "\t\t" + dist[i] + "\t\t");
printPath(i, parent);
System.out.println();
}
}
}

private void printPath(int current, int[] parent) {


if (parent[current] == -1) {
System.out.print(current);
return;
}
printPath(parent[current], parent);
System.out.print(" -> " + current);
}
}

Main Program to Run

java
CopyEdit
public class LinkStateRoutingDemo {
public static void main(String[] args) {
Graph g = new Graph(6);

g.addEdge(0, 1, 4);
g.addEdge(0, 2, 2);
g.addEdge(1, 2, 1);
g.addEdge(1, 3, 5);
g.addEdge(2, 3, 8);
g.addEdge(2, 4, 10);
g.addEdge(3, 4, 2);
g.addEdge(3, 5, 6);
g.addEdge(4, 5, 3);

g.dijkstra(0); // Starting router (source node)


}
}

Output (Example)

rust
CopyEdit
Router Distance from Source Path
0 -> 1 3 0 -> 2 -> 1
0 -> 2 2 0 -> 2
0 -> 3 8 0 -> 2 -> 1 -> 3
0 -> 4 10 0 -> 2 -> 1 -> 3 -> 4
0 -> 5 13 0 -> 2 -> 1 -> 3 -> 4 -> 5

Program 10

Java Implementation of Distance Vector Routing

Sample Network Topology

Router Connected to (Cost)


Router Connected to (Cost)
A B(2), C(5)
B A(2), C(1), D(3)
C A(5), B(1), D(2)
D B(3), C(2)

Java Code

import java.util.*;

class DistanceVectorRouting {
static final int INF = 9999;
int[][] cost; // adjacency matrix
int[][] distance; // distance vectors
int[][] nextHop;
int routers;

public DistanceVectorRouting(int r) {
routers = r;
cost = new int[routers][routers];
distance = new int[routers][routers];
nextHop = new int[routers][routers];

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


for (int j = 0; j < routers; j++) {
if (i == j)
cost[i][j] = 0;
else
cost[i][j] = INF;

distance[i][j] = cost[i][j];
nextHop[i][j] = j;
}
}
}

public void addEdge(int src, int dest, int c) {


cost[src][dest] = c;
cost[dest][src] = c;
distance[src][dest] = c;
distance[dest][src] = c;
}

public void calculateDistanceVectors() {


boolean updated;
do {
updated = false;
for (int i = 0; i < routers; i++) {
for (int j = 0; j < routers; j++) {
for (int k = 0; k < routers; k++) {
if (distance[i][j] > cost[i][k] + distance[k][j]) {
distance[i][j] = cost[i][k] + distance[k][j];
nextHop[i][j] = k;
updated = true;
}
}
}
}
} while (updated);
}

public void printRoutingTable() {


for (int i = 0; i < routers; i++) {
System.out.println("Routing table for router " + (char)('A' + i) + ":");
System.out.println("Destination\tCost\tNext Hop");
for (int j = 0; j < routers; j++) {
if (i != j) {
System.out.println((char)('A' + j) + "\t\t" + distance[i][j] + "\t" + (char)('A' + nextHop[i][j]));
}
}
System.out.println();
}
}
}

▶ Main Program

java
CopyEdit
public class DVRoutingDemo {
public static void main(String[] args) {
DistanceVectorRouting dvr = new DistanceVectorRouting(4); // A, B, C, D

// Add edges: A=0, B=1, C=2, D=3


dvr.addEdge(0, 1, 2); // A-B
dvr.addEdge(0, 2, 5); // A-C
dvr.addEdge(1, 2, 1); // B-C
dvr.addEdge(1, 3, 3); // B-D
dvr.addEdge(2, 3, 2); // C-D

dvr.calculateDistanceVectors();
dvr.printRoutingTable();
}
}
🧾 Sample Output

less
CopyEdit
Routing table for router A:
Destination Cost Next Hop
B 2 B
C 3 B
D 6 B

Routing table for router B:


Destination Cost Next Hop
A 2 A
C 1 C
D 3 D
...

Program 11
Implementation of Subnetting

 Network Address
 Broadcast Address
 First and Last Host Address
 Number of Hosts

Java Code: Subnetting Implementation


java
CopyEdit
import java.util.Scanner;

public class SubnetCalculator {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter IP address (e.g., 192.168.1.10): ");


String ipAddress = sc.nextLine();

System.out.print("Enter CIDR notation (e.g., 24): ");


int cidr = sc.nextInt();

try {
String[] parts = ipAddress.split("\\.");
int ip = 0;
for (String part : parts) {
ip = (ip << 8) | Integer.parseInt(part);
}

int mask = 0xFFFFFFFF << (32 - cidr);


int network = ip & mask;
int broadcast = network | ~mask;

int firstHost = network + 1;


int lastHost = broadcast - 1;
int numberOfHosts = (int) Math.pow(2, (32 - cidr)) - 2;

System.out.println("\n--- Subnetting Details ---");


System.out.println("Network Address: " + intToIp(network));
System.out.println("Broadcast Address: " + intToIp(broadcast));
System.out.println("First Host Address: " + intToIp(firstHost));
System.out.println("Last Host Address: " + intToIp(lastHost));
System.out.println("Number of Hosts: " + numberOfHosts);

} catch (Exception e) {
System.out.println("Invalid IP address or CIDR input.");
}
}

private static String intToIp(int ip) {


return ((ip >> 24) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
(ip & 0xFF);
}
}

Sample Input:

Enter IP address (e.g., 192.168.1.10): 192.168.1.10


Enter CIDR notation (e.g., 24): 24
Sample Output:
--- Subnetting Details ---
Network Address: 192.168.1.0
Broadcast Address: 192.168.1.255
First Host Address: 192.168.1.1
Last Host Address: 192.168.1.254
Number of Hosts: 254

You might also like