CN Lab Manual 3rd Year
CN Lab Manual 3rd Year
BCS 653
The students are expected to be able to demonstrate the following knowledge, skills and attitudes
after completing this course:
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
import java.io.*;
import java.net.*;
{
// establish a connection
try {
System.out.println("Connected");
socket.getOutputStream());
catch (UnknownHostException u) {
System.out.println(u);
return;
catch (IOException i) {
System.out.println(i);
return;
}
// string to read message from input
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
catch (IOException i) {
System.out.println(i);
try {
input.close();
out.close();
socket.close();
catch (IOException i) {
System.out.println(i);
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
import java.net.*;
import java.io.*;
try
System.out.println("Server started");
socket = server.accept();
System.out.println("Client accepted");
new BufferedInputStream(socket.getInputStream()));
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);
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.
ALGORITHM:
Client
Progra
m
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
{
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
Server
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
{
public static void main(String args[])
{
try
{
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
{
public static void main(String args[])
{
try
{
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.
java
CopyEdit
import java.rmi.Remote;
import java.rmi.RemoteException;
java
CopyEdit
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
Program 6
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
import java.net.*;
☑ This uses Java's built-in DNS resolution (UDP under the hood).
Java does not have a native SNMP API, but we can simulate a basic UDP request/response mechanism
similar to SNMP polling.
java
CopyEdit
import java.net.*;
socket.send(responsePacket);
} catch (Exception e) {
e.printStackTrace();
}
}
}
java
CopyEdit
import java.net.*;
FileServer.java (TCP)
java
CopyEdit
import java.io.*;
import java.net.*;
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.*;
fos.close();
System.out.println("File received and saved as received.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Program 8
import java.io.BufferedReader;
import java.io.InputStreamReader;
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
Program 9
import java.util.*;
class Graph {
private int vertices;
private int[][] adjacencyMatrix;
public Graph(int v) {
this.vertices = v;
adjacencyMatrix = new int[v][v];
}
Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
parent[source] = -1;
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);
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 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];
distance[i][j] = cost[i][j];
nextHop[i][j] = j;
}
}
}
▶ Main Program
java
CopyEdit
public class DVRoutingDemo {
public static void main(String[] args) {
DistanceVectorRouting dvr = new DistanceVectorRouting(4); // A, B, 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
Program 11
Implementation of Subnetting
Network Address
Broadcast Address
First and Last Host Address
Number of Hosts
try {
String[] parts = ipAddress.split("\\.");
int ip = 0;
for (String part : parts) {
ip = (ip << 8) | Integer.parseInt(part);
}
} catch (Exception e) {
System.out.println("Invalid IP address or CIDR input.");
}
}
Sample Input: