Comnet

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

DEPARTMENT OF ARTIFICAL INTELLIGENCE AND DATA

SCIENCE
BONAFIDE CERTIFICATE

Name of the Student:

Register No.

This is to certify that this is a Bonafide record of the work done by the above student with

Roll No. of Semester B. Tech


Degree in in the
during
Laboratory

the academic year 2023 – 2024.

Staff-In-Charge Head of the Department

Date:

Submitted for the Practical Examination held on


Internal Examiner External Examiner
CS3591 – COMPUTER NETWORKS
INDEX

PAGE MARK
EX.NO DATE NAME OF THE EXPERIMENT SIGN
NO S
1 Learn to use commands like tcpdump,
netstat, ifconfig, nslookup and traceroute.
Capture ping and trace route PDUs using a
network protocol analyzer and examine
2 Write a HTTP web client program to
download a web page using TCP sockets.
3 Applications using TCP sockets like:
a) Echo client and echo server
b) Chat
4 Simulation of DNS using UDP sockets.
5 Use a tool like Wireshark to capture packets
and examine the packets
6 Write a code simulating ARP /RARP
protocols.
7 Study of Network simulator (NS) and
Simulation of Congestion Control
Algorithms using NS.
8 Study of TCP/UDP performance using
Simulation tool.
9 Simulation of Distance Vector/ Link State
Routing algorithm.
10 Simulation of an error correction code (like
CRC)
EXP NO: 1
Learn to use commands like tcpdump, netstat, ifconfig,
DATE
nslookup and traceroute ping.
AIM:
To Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute ping.

Tcpdump:
The tcpdump utility allows you to capture packets that flow within your network to assist in
network troubleshooting. The following are several examples of using tcpdump with different
options. Traffic is captured based on a specified filter.
Netstat
Netstat is a common command line TCP/IP networking available in most versions of
Windows, Linux, UNIX and other operating systems.
Netstat provides information and statistics about protocols in use and current TCP/IP network
connections.
ipconfig
ipconfig is a console application designed to run from the Windows command prompt.
This utility allows you to get the IP address information of a Windows computer.
From the command prompt, type ipconfig to run the utility with default options. The output of the
default command contains the IP address, network mask, and gateway for all physical and virtual
network adapter.
nslookup
The nslookup (which stands for name server lookup) command is a network utility program used
to obtain information about internet servers. It finds name server information for domains by
querying the Domain Name System.
Trace route:
Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an IP
network from source to destination. Traceroute also records the time taken for each hop the packet
makes during its route to the destination

Commands:

Tcpdump:
Display traffic between 2 hosts:
To display all traffic between two hosts (represented by variables host1 and host2): # tcpdump
host host1 and host2
Display traffic from a source or destination host only:
To display traffic from only a source (src) or destination (dst)
host: # tcpdump src host
# tcpdump dst host
Display traffic for a specific protocol
Provide the protocol as an argument to display only traffic for a specific protocol, for example tcp,
udp, icmp, arp
# tcpdump protocol
For example to display traffic only for the tcp traffic :
# tcpdump tcp
Filtering based on source or destination port
To filter based on a source or destination port:
# tcpdump src port ftp
# tcpdump dst port
http

2.Netstat
Netstat is a common command line TCP/IP networking available in most versions of
Windows, Linux, UNIX and other operating systems.
Netstat provides information and statistics about protocols in use and current TCP/IP
network connections. The Windows help screen (analogous to a Linux or UNIX for netstat reads as
follows: displays protocol statistics and current TCP/IP network connections.

#netstat

3. ipconfig

In Windows, ipconfig is a console application designed to run from the Windows command
prompt. This utility allows you to get the IP address information of a Windows computer.
Using ipconfig
From the command prompt, type ipconfig to run the utility with default options. The output of the
default command contains the IP address, network mask, and gateway for all physical and virtual
network adapter.

#ipconfig
4.nslookup
The nslookup (which stands for name server lookup) command is a network utility program used
to obtain information about internet servers. It finds name server information for domains by
querying the Domain Name System.

The nslookup command is a powerful tool for diagnosing DNS problems. You know you're
experiencing a DNS problem when you can access a resource by specifying its IP address but not its
DNS name.

#nslookup

5.Trace route:

Traceroute uses Internet Control Message Protocol (ICMP) echo packets with variable time to live
(TTL) values. The response time of each hop is calculated. To guarantee accuracy, each hop is queried
multiple times (usually three times) to better measure the response of that particular hop.
Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an IP network
from source to destination. Traceroute also records the time taken for each hop the packet makes
during its route to the destination. Traceroute uses Internet Control Message Protocol (ICMP) echo
packets with variable time to live (TTL) values.
The response time of each hop is calculated. To guarantee accuracy, each hop is queried
multiple times (usually three times) to better measure the response of that particular hop. Traceroute
sends packets with TTL values that gradually increase from packet to packet, starting with TTL value
of one. Routers decrement TTL values of packets by one when routing and discard packets whose
TTL value has reached zero, returning the ICMP error message ICMP Time Exceeded.

For the first set of packets, the first router receives the packet, decrements the TTL value and
drops the packet because it then has TTL value zero. The router sends an ICMP Time Exceeded
message back to the source. The next set of packets are given a TTL value of two, so the first router
forwards the packets, but the second router drops them and replies with ICMP Time Exceeded.
Proceeding in this way, traceroute uses the returned ICMP Time Exceeded messages to build a list of
routers that packets traverse, until the destination is reached and returns an ICMP Echo Reply
message.
With the tracert command shown above, we're asking tracert to show us the path from the local
computer all the way to the network device with the hostname

www.google.com.

#tracert

google.com

6. Ping:

The ping command sends an echo request to a host available on the network. Using this
command, you can check if your remote host is responding well or not. Tracking and isolating
hardware and software problems. Determining the status of the network and various foreign hosts.
The ping command is usually used as a simple way to verify that a computer can communicate over
the network with another computer or network device. The ping command operates by sending
Internet Control Message Protocol (ICMP) Echo Request messages to the destination computer and
waiting for a response

# ping172.16.6.2
RESULT:
Thus the various networks commands like tcpdump, netstat, ifconfig, nslookup and traceroute
ping are executed successfully.
EXP NO: 2
DATE
Write a HTTP web client program to download a
web page using TCP sockets.

AIM:
To write a HTTP web client program to download a web page using TCP sockets.

PROCEDURE:

1. Socket Creation: A TCP socket is created using new Socket(host, 80).

2. Output Stream: A PrintWriter is created to send the HTTP GET request.

3. Input Stream: A BufferedReader is created to read the server's response.

4. HTTP GET Request: The request is sent with the required headers (Host and Connection).

5. Response Handling: The response is read line by line and printed to the console.

6. Cleanup: The input and output streams and the socket are closed
PROGRAM:

import java.io.*;
import java.net.Socket;
public class HttpClient
{
public static void main(String[] args)
{
String host = "www.example.com";
String path = "/";
try
{
// Create a TCP socket
Socket socket = new Socket(host, 80);
// Create output stream to send request
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Create input stream to read response
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// Send HTTP GET request
out.println("GET " + path + " HTTP/1.1");
out.println("Host: " + host);
out.println("Connection: close");
out.println();
// Read and print the response
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
// Close the streams and socket
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT:

Result :
Thus the web page is downloaded using TCP sockets in java.

EXP NO: 3 a
Applications using TCP sockets like:
DATE
a) Echo client and echo server

AIM:
To implement the application of Echo client and server using TCP sockets.

PROCEDURE:

✔ Write the Code:

● Create two Java files: EchoServer.java and EchoClient.java.


● Copy and paste the provided server and client code into their respective files.

✔ Compile the Code:

● Open your command prompt or terminal.


● Navigate to the directory where you saved your Java files.
● Compile both files using the Java compiler (javac):

✔ Run the Server:

● In the terminal, start the server by executing the compiled EchoServer.class file:

✔ Run the Client:

● Open another terminal.


● Run the client by executing the compiled EchoClient.class file:

✔ Test the Application:

● Once the client and server are running, you can type messages in the client terminal.
● The server will receive these messages, echo them back, and you'll see the echoed messages in the
client terminal.
● Type "exit" in the client terminal to quit the client.

✔ Shutdown:

● To stop the server, press Ctrl + C in the terminal where it's running.
● The client can be stopped by typing "exit" and pressing Enter.
PROGRAM:

ECHO SERVER:

import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) {
final int PORT = 12345;

try{ ServerSocket serverSocket = new ServerSocket(PORT);


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

while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

// Start a new thread to handle client's request


new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static class ClientHandler extends Thread {


private Socket clientSocket;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

public void run() {


try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received from client: " + message);
writer.println("Server echo: " + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ECHO CLIENT:

import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args)
{
final String SERVER_ADDRESS = "localhost";
final int SERVER_PORT = 12345;
try
{
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader serverReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.println("Connected to server. Type 'exit' to quit.");
String message;
while (true)
{
System.out.print("Client: ");
message = reader.readLine();
if (message.equalsIgnoreCase("exit"))
{
break;
}
writer.println(message);
String response = serverReader.readLine();
System.out.println("Server: " + response);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}

OUTPUT:

RESULT:

Thus the Echo Server and Echo Client application is implemented using TCP sockets.
EXP NO: 3 b
Applications using TCP sockets like:
DATE
b) Chat

AIM:
To implement the application of Chat using TCP sockets.

PROCEDURE:

✔ Write the Code:

● Create two Java files: EchoServer.java and EchoClient.java.


● Copy and paste the provided server and client code into their respective files.

✔ Compile the Code:

● Open your command prompt or terminal.


● Navigate to the directory where you saved your Java files.
● Compile both files using the Java compiler (javac):

✔ Run the Server:

● In the terminal, start the server by executing the compiled EchoServer.class file:

✔ Run the Client:

● Open another terminal.


● Run the client by executing the compiled EchoClient.class file:

✔ Test the Application:

● Once the client and server are running, you can type messages in the client terminal.
● The server will receive these messages, echo them back, and you'll see the echoed messages in the
client terminal.
● Type "exit" in the client terminal to quit the client.

✔ Shutdown:

● To stop the server, press Ctrl + C in the terminal where it's running.
● The client can be stopped by typing "exit" and pressing Enter.
PROGRAM:

ECHO SERVER:

import java.io.*;
import java.net.*;
public class chatServer {
public static void main(String[] args) {
final int PORT = 12345;

try{ ServerSocket serverSocket = new ServerSocket(PORT);


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

while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

// Start a new thread to handle client's request


new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

private static class ClientHandler extends Thread {


private Socket clientSocket;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

public void run() {


try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received from client: " + message);
writer.println("Server echo: " + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
CHAT CHATLIENT:

import java.io.*;
import java.net.*;
public class chatClient
{
public static void main(String[] args)
{
final String SERVER_ADDRESS = "localhost";
final int SERVER_PORT = 12345;
try
{
Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader serverReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
System.out.println("Connected to server. Type 'exit' to quit.");
String message;
while (true)
{
System.out.print("Client: ");
message = reader.readLine();
if (message.equalsIgnoreCase("exit"))
{
break;
}
writer.println(message);
String response = serverReader.readLine();
System.out.println("Server: " + response);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
OUTPUT:

RESULT:

Thus the chat application is implemented using TCP sockets


EXP NO: 4
Simulation of DNS using UDP sockets
DATE

AIM:
To implement and simulate a basic DNS (Domain Name System) server using UDP (User
Datagram Protocol) sockets.

PROCEDURE:

✔ Compile the Java files:

● Save the DNSServer.java and DNSClient.java files in the same directory.


● Open a command prompt or terminal.
● Navigate to the directory containing the Java files.
● Compile both files using the javac command: javac DNSServer.java DNSClient.java

✔ Run the DNS Server:

● Start the DNS server by running the DNSServer class: java DNSServer

✔ Run the DNS Client:

● In a separate command prompt or terminal window, run the DNSClient class: java DNSClient

✔ Observe Output:

● After running the client, you should see the resolved IP address printed on the client's console.
PROGRAM:

DNS Server:

import java.net.*;

public class DNSServer {


public static void main(String[] args) {
try {
// Create a datagram socket and bind it to port 9876
DatagramSocket socket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024];


byte[] sendData = new byte[1024];

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

while (true) {
// Create a datagram packet to receive data from the client
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);

// Extract the hostname from the received packet


String hostname = new String(receivePacket.getData()).trim();

// Lookup IP address for the hostname


String ipAddress = lookupIPAddress(hostname);

// If IP address found, send it back to the client


if (ipAddress != null) {
sendData = ipAddress.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
socket.send(sendPacket);
System.out.println("Resolved " + hostname + " to " + ipAddress);
} else {
System.out.println("Hostname " + hostname + " not found");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

// Dummy method to lookup IP address based on hostname


private static String lookupIPAddress(String hostname) {
if (hostname.equals("example.com")) {
return "192.0.2.1";
} else if (hostname.equals("google.com")) {
return "172.217.168.110";
} else {
return null;
}
}
}

DNS Client:
import java.net.*;

public class DNSClient {


public static void main(String[] args) {
try {
// Create a datagram socket
DatagramSocket socket = new DatagramSocket();

// Prepare data to send


String hostname = "example.com";
byte[] sendData = hostname.getBytes();

// Send data to server


InetAddress serverAddress = InetAddress.getByName("localhost");
int serverPort = 9876;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
serverAddress, serverPort);
socket.send(sendPacket);
// Receive response from server
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
// Print the received IP address
String ipAddress = new String(receivePacket.getData()).trim();
System.out.println("Resolved IP address for " + hostname + ": " + ipAddress);
// Close the socket
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
RESULT:

Thus the Simulation of DNS using UDP sockets.


EXP NO: 5
Use a tool like Wireshark to capture packets and
DATE
examine the packets

AIM:

To create a simple Java client-server program using UDP sockets and examine the packets using
Wireshark.

PROCEDURE:

✔ Compile and Run Java Programs:

● Compile both UDPServer.java and UDPClient.java.


● Run the server program (UDPServer) first.
● Then, run the client program (UDPClient).

✔ Open Wireshark:

● Open Wireshark on your system.

✔ Select Network Interface:

● In Wireshark, select the network interface that you want to capture packets on. This is typically your
Wi-Fi or Ethernet interface.

✔ Start Packet Capture:

● Start capturing packets by clicking on the selected network interface in Wireshark.


● Wireshark will start capturing packets in real-time.

✔ Send Data from Client:

● In the client program, send data to the server by running the UDPClient.
● The client will send a message to the server over UDP.

✔ Observe Captured Packets:

● Switch back to Wireshark.


● You should see packets being captured and displayed in Wireshark's main window.

✔ Apply Filter (optional):

● Apply a display filter in Wireshark to focus on UDP traffic on the port used by your server (e.g.,
udp.port == 9876).
✔ Examine Packets:

● Click on individual packets in Wireshark to examine their details.


● You can analyze various aspects of each packet, including source and destination IP addresses,
source and destination ports, and packet payload.
● Look for packets exchanged between your client and server. These will typically include UDP
packets with the content of your message.

✔ Understand Packet Details:

● Wireshark provides detailed information about each packet, including the contents of the packet
payload.
● Examine the packet details to understand the sequence of packets exchanged between the client and
server, and the contents of the messages sent.

✔ Stop Packet Capture:

● Once you've captured enough packets and examined them, you can stop the packet capture in
Wireshark.

PROGRAM:

UDP server:

import java.net.*;

public class UDPServer {

public static void main(String[] args) {

try {

// Create a datagram socket and bind it to port 9876

DatagramSocket serverSocket = new DatagramSocket(9876);

byte[] receiveData = new byte[1024];

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

while (true) {

// Create a datagram packet to receive data from the client

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);
// Extract the received data

String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("Received from client: " + receivedMessage);

// Prepare response message

String responseMessage = "Hello from server";

// Get client's address and port from the received packet

InetAddress clientAddress = receivePacket.getAddress();

int clientPort = receivePacket.getPort();

// Convert response message to bytes

byte[] sendData = responseMessage.getBytes();

// Create a datagram packet to send data to the client

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress,


clientPort);

// Send the response packet to the client

serverSocket.send(sendPacket);

} catch (Exception e) {

e.printStackTrace();

UDP client:

import java.net.*;

public class UDPClient {

public static void main(String[] args) {


try {

// Create a datagram socket

DatagramSocket clientSocket = new DatagramSocket();

// Server address and port

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

int serverPort = 9876;

// Message to send

String message = "Hello from client";

// Convert message to bytes

byte[] sendData = message.getBytes();

// Create a datagram packet to send data to the server

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress,


serverPort);

// Send the packet to the server

clientSocket.send(sendPacket);

// Receive response from the server

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

clientSocket.receive(receivePacket);

// Extract received data

String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());

System.out.println("Received from server: " + receivedMessage);

// Close the socket

clientSocket.close();

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

}
OUTPUT

RESULT: Thus the packets are examined using wireshark


EXP NO: 6
Write a code simulating ARP /RARP protocols
DATE

AIM:

TO implementation of ARP (Address Resolution Protocol) and RARP (Reverse Address Resolution
Protocol).

PROCEDURE:

✔ Populate ARP Table:

● Initialize the ARP table with known mappings of IP addresses to MAC addresses.
● This step simulates the initial setup of the network's ARP cache.

✔ Send ARP Request:

● Simulate sending an ARP request from a source IP address to a destination IP address.


● This step represents a device on the network needing to resolve the MAC address associated with a
specific IP address.
● Print a message indicating the ARP request is being sent, specifying the source and destination IP
addresses.

✔ Receive ARP Reply:

● Simulate receiving an ARP reply containing the MAC address corresponding to the destination IP
address.
● Retrieve the MAC address from the ARP table using the destination IP address.
● Print a message indicating the received ARP reply, showing the resolved MAC address.
PROGRAM:
import java.util.HashMap;
import java.util.Map;

class ARP {
private static Map<String, String> arpTable = new HashMap<>();

public static void addEntry(String ipAddress, String macAddress) {


arpTable.put(ipAddress, macAddress);
}

public static String resolveMACAddress(String ipAddress) {


return arpTable.get(ipAddress);
}

public static void sendARPRequest(String sourceIPAddress, String destinationIPAddress) {


String destinationMACAddress = resolveMACAddress(destinationIPAddress);
System.out.println("Sending ARP request from " + sourceIPAddress + " to " + destinationIPAddress);
System.out.println("Received ARP reply: MAC address for " + destinationIPAddress + " is " +
destinationMACAddress);
}

public static void main(String[] args) {


addEntry("192.168.1.2", "00:11:22:33:44:55");
addEntry("192.168.1.3", "AA:BB:CC:DD:EE:FF");

sendARPRequest("192.168.1.2", "192.168.1.3");
}
}
OUTPUT:

Step 1: Sending ARP request from 192.168.1.2 to 192.168.1.3


Step 2: Received ARP reply: MAC address for 192.168.1.3 is AA:BB:CC:DD:EE:FF

RESULT: Thus the ARP /RARP protocols is implemented


EXP NO: 7
simulator (NS) and Simulation of Congestion Control
DATE
Study of Network Algorithms using NS.
AIM:
To implement the simulator (NS) and Simulation of Congestion Control Algorithms using NS

PROCEDURE:

✔ Install Java Development Kit (JDK):

Ensure you have JDK installed on your system. You can download it from the Oracle website or
use OpenJDK.

✔ Choose an Integrated Development Environment (IDE):

Use an IDE such as IntelliJ IDEA, Eclipse, or NetBeans to write and run your Java programs.
IDEs provide a convenient environment for Java development.

✔ Create the Node class:

o The Node class represents a network node with input and output queues for message passing.
o Define attributes and methods for sending and receiving messages.
o Implement Runnable interface for concurrent execution using threads.

✔ Create the NetworkSimulation class:

● Set up nodes (Node A and Node B) and simulate a direct link between them.
● Start threads for each node to simulate concurrent execution.
● Send messages between nodes and observe the communication.

✔ Compile the Java files:

● Open a terminal or command prompt.


● Navigate to the directory containing your Java files (Node.java and NetworkSimulation.java).
● Compile the files using javac:
Program:
Node.java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Node implements Runnable {


private final BlockingQueue<String> inputQueue;
private final BlockingQueue<String> outputQueue;
private final String name;

public Node(String name) {


this.name = name;
this.inputQueue = new ArrayBlockingQueue<>(10);
this.outputQueue = new ArrayBlockingQueue<>(10);
}

public BlockingQueue<String> getInputQueue() {


return inputQueue;
}

public BlockingQueue<String> getOutputQueue() {


return outputQueue;
}

public void sendMessage(String message) {


try {
outputQueue.put(message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}

@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String message = inputQueue.take();
System.out.println(name + " received message: " + message);
Thread.sleep(1000); // Simulate processing delay
sendMessage(message); // Echo back the message
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

NetworkSimulation.java:
public class NetworkSimulation {
public static void main(String[] args) {
Node nodeA = new Node("Node A");
Node nodeB = new Node("Node B");

Thread threadA = new Thread(nodeA);


Thread threadB = new Thread(nodeB);

// Connect nodes (simulate a direct link)


nodeA.getOutputQueue().addAll(nodeB.getInputQueue());
nodeB.getOutputQueue().addAll(nodeA.getInputQueue());

threadA.start();
threadB.start();

// Send messages
nodeA.sendMessage("Hello from Node A");

try {
Thread.sleep(3000); // Allow time for messages to propagate
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

// Interrupt threads to stop simulation


threadA.interrupt();
threadB.interrupt();
}
}

Output:

Node A received message: Hello from Node A


Node B received message: Hello from Node A
Node A received message: Hello from Node A
Node B received message: Hello from Node A
...

RESULT:

Thus the Congestion Control Algorithms is implemented using NS


EXP NO: 8
Study of TCP/UDP performance using Simulation tool.
DATE

AIM:
To write a program for TCP/UDP performance using Simulation tool.

Procedure:

✔ Server.java:

● Implements both UDP and TCP servers.


● The UDP server listens on port 9876, and the TCP server listens on port 6789.
● It receives messages from clients and prints them to the console.

✔ Client.java:

● Implements both UDP and TCP clients


● . The UDP client sends a "Hello UDP Server" message to the server running on localhost at port
9876.
● The TCP client establishes a connection with the server running on localhost at port 6789 and sends a
"Hello TCP Server" message.
Program:

Server.java:

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

public class Server {


public static void main(String[] args) {
DatagramSocket udpSocket = null;
ServerSocket tcpSocket = null;

try {
// UDP Server
udpSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

// TCP Server
tcpSocket = new ServerSocket(6789);
Socket clientSocket = tcpSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

while (true) {
// UDP Server
udpSocket.receive(receivePacket);
String udpMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("UDP Client: " + udpMessage);

// TCP Server
String tcpMessage = in.readLine();
System.out.println("TCP Client: " + tcpMessage);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (udpSocket != null) udpSocket.close();
if (tcpSocket != null) {
try {
tcpSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Client.java:

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

public class Client {


public static void main(String[] args) {
DatagramSocket udpSocket = null;
Socket tcpSocket = null;

try {
// UDP Client
udpSocket = new DatagramSocket();
InetAddress serverAddress = InetAddress.getByName("localhost");
byte[] sendData = "Hello UDP Server".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress,
9876);
udpSocket.send(sendPacket);

// TCP Client
tcpSocket = new Socket("localhost", 6789);
PrintWriter out = new PrintWriter(tcpSocket.getOutputStream(), true);
out.println("Hello TCP Server");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (udpSocket != null) udpSocket.close();
if (tcpSocket != null) {
try {
tcpSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Output:

UDP Client: Hello UDP Server


TCP Client: Hello TCP Server
Result:

Thus the packet is sent using TCP/UDP .


EXP NO: 9 Simulation of Distance Vector/ Link State
DATE Routing algorithm

Aim:
To implement the Distance Vector/ Link State Routing algorithm

Procedure:

✔ Router.java:

● Represents a router with its ID, distance vector (mapping of destination router ID to cost), and
forwarding table (mapping of destination router ID to next hop router ID).
● Initializes with initial distance vectors and updates based on received distance vectors.

✔ NetworkSimulation.java:

● Simulates a network with multiple routers (Router objects).


● Initializes routers with initial distance vectors.
● Simulates routing for a specified number of iterations, where routers exchange distance vectors and
update their tables accordingly.
● Outputs the state of each router (distance vector and forwarding table) after each iteration.
Program:

Router.java:

import java.util.*;

public class Router {


private final int id;
private final Map<Integer, Integer> distanceVector; // Destination Router ID -> Cost
private final Map<Integer, Integer> forwardingTable; // Destination Router ID -> Next Hop

public Router(int id) {


this.id = id;
this.distanceVector = new HashMap<>();
this.forwardingTable = new HashMap<>();
}

public void initializeDistanceVector(Map<Integer, Integer> initialVector) {


this.distanceVector.putAll(initialVector);
updateForwardingTable();
}

public void updateDistanceVector(int routerId, int cost) {


distanceVector.put(routerId, cost);
updateForwardingTable();
}

private void updateForwardingTable() {


forwardingTable.clear();
distanceVector.forEach((routerId, cost) -> {
if (cost != Integer.MAX_VALUE && routerId != id) {
forwardingTable.put(routerId, routerId); // Directly connected next hop
}
});
}

public Map<Integer, Integer> getDistanceVector() {


return distanceVector;
}

public Map<Integer, Integer> getForwardingTable() {


return forwardingTable;
}
}
NetworkSimulation.java:

import java.util.*;

public class NetworkSimulation {


private final Map<Integer, Router> routers;

public NetworkSimulation() {
this.routers = new HashMap<>();
}

public void addRouter(int id, Map<Integer, Integer> initialDistanceVector) {


Router router = new Router(id);
router.initializeDistanceVector(initialDistanceVector);
routers.put(id, router);
}

public void simulateRouting(int numIterations) {


for (int i = 0; i < numIterations; i++) {
System.out.println("Iteration " + (i + 1) + ":");
for (Router router : routers.values()) {
System.out.println("Router " + router.getId() + " Distance Vector: " + router.getDistanceVector());
System.out.println("Router " + router.getId() + " Forwarding Table: " +
router.getForwardingTable());
}
exchangeDistanceVectors();
}
}

private void exchangeDistanceVectors() {


for (Router router : routers.values()) {
Map<Integer, Integer> currentDistanceVector = router.getDistanceVector();
for (Map.Entry<Integer, Integer> entry : currentDistanceVector.entrySet()) {
int destinationRouterId = entry.getKey();
int currentCost = entry.getValue();

if (currentCost != Integer.MAX_VALUE) { // Only consider neighbors


Router neighborRouter = routers.get(destinationRouterId);
if (neighborRouter != null) {
Map<Integer, Integer> neighborDistanceVector = neighborRouter.getDistanceVector();
int newCost = currentCost + 1; // Simulated cost update
neighborRouter.updateDistanceVector(router.getId(), newCost);
}
}
}
}
}

public static void main(String[] args) {


NetworkSimulation simulation = new NetworkSimulation();

// Define initial distance vectors for each router


Map<Integer, Integer> dvRouter1 = new HashMap<>();
dvRouter1.put(1, 0); // Cost to self
dvRouter1.put(2, Integer.MAX_VALUE); // Cost to other routers
dvRouter1.put(3, Integer.MAX_VALUE);

Map<Integer, Integer> dvRouter2 = new HashMap<>();


dvRouter2.put(1, Integer.MAX_VALUE);
dvRouter2.put(2, 0);
dvRouter2.put(3, Integer.MAX_VALUE);

Map<Integer, Integer> dvRouter3 = new HashMap<>();


dvRouter3.put(1, Integer.MAX_VALUE);
dvRouter3.put(2, Integer.MAX_VALUE);
dvRouter3.put(3, 0);

// Add routers to the simulation


simulation.addRouter(1, dvRouter1);
simulation.addRouter(2, dvRouter2);
simulation.addRouter(3, dvRouter3);

// Simulate routing for a number of iterations


simulation.simulateRouting(5); // Adjust the number of iterations as needed
}
}

Output:

Iteration 1:
Router 1 Distance Vector: {1=0, 2=1, 3=2}
Router 1 Forwarding Table: {2=2, 3=3}
Router 2 Distance Vector: {1=1, 2=0, 3=1}
Router 2 Forwarding Table: {1=1, 3=3}
Router 3 Distance Vector: {1=2, 2=1, 3=0}
Router 3 Forwarding Table: {1=1, 2=2}

Result:
Thus the Distance Vector/ Link State Routing is implemented
EXP NO: 10
Simulation of an error correction code (like CRC)
DATE

Aim:
To implement the Simulation of an error correction code (like CRC)
Procedure:

● Implements a CRC error detection simulation using CRC-16-CCITT (XModem) polynomial


(0x1021) with an initial CRC value of 0xFFFF.
● The calculateCRC method computes the CRC checksum for given data using bitwise operations.
● In main, a string "Hello, world!" is converted to bytes, and CRC is appended to simulate data
transmission.
● Errors are simulated by flipping random bits in the received data (simulated 10% error rate).
● After receiving data, CRC is recalculated and compared to the received CRC to determine if the data
is corrupted.

.
Program:

Java Program for CRC Error Detection:

import java.util.*;

public class CRCSimulation {

// CRC parameters (polynomial divisor and initial CRC value)


private static final int POLYNOMIAL = 0x1021; // x^16 + x^12 + x^5 + 1 (CRC-16-CCITT)
private static final int INITIAL_CRC = 0xFFFF; // Initial CRC value

// Generate CRC for given data using CRC-16-CCITT (XModem)


public static int calculateCRC(byte[] data) {
int crc = INITIAL_CRC;

for (byte b : data) {


crc ^= (b & 0xFF) << 8; // XOR with next byte
for (int i = 0; i < 8; i++) {
if ((crc & 0x8000) != 0) { // Check if MSB is 1
crc = (crc << 1) ^ POLYNOMIAL;
} else {
crc <<= 1;
}
}
crc &= 0xFFFF; // Ensure 16-bit CRC
}

return crc;
}

public static void main(String[] args) {


// Simulate data transmission with CRC error detection
String dataString = "Hello, world!";
byte[] data = dataString.getBytes();

// Add CRC to data


int crcValue = calculateCRC(data);
byte[] dataWithCRC = new byte[data.length + 2]; // 2 bytes for CRC
System.arraycopy(data, 0, dataWithCRC, 0, data.length);
dataWithCRC[data.length] = (byte) ((crcValue >> 8) & 0xFF); // MSB
dataWithCRC[data.length + 1] = (byte) (crcValue & 0xFF); // LSB

// Simulate transmission and reception with possible errors


System.out.println("Original Data: " + Arrays.toString(data));
System.out.println("Data with CRC: " + Arrays.toString(dataWithCRC));

// Simulate reception with possible errors (flip some bits)


Random random = new Random();
byte[] receivedData = Arrays.copyOf(dataWithCRC, dataWithCRC.length);
for (int i = 0; i < receivedData.length; i++) {
if (random.nextDouble() < 0.1) { // Simulate 10% error rate
receivedData[i] ^= 1; // Flip a bit
}
}

// Verify CRC and determine if data is corrupted


byte[] receivedDataWithoutCRC = Arrays.copyOf(receivedData, receivedData.length - 2);
int receivedCRC = calculateCRC(receivedDataWithoutCRC);

System.out.println("Received Data: " + Arrays.toString(receivedData));


System.out.println("Received CRC: " + receivedCRC);

if (receivedCRC == 0) {
System.out.println("CRC check passed: Data is intact.");
} else {
System.out.println("CRC check failed: Data is corrupted.");
}
}
}

Output:

Original Data: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
Data with CRC: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, -96, -38]
Received Data: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, -96, -38]
Received CRC: 0
CRC check passed: Data is intact.

Result:

Thus the Error Correction code(CRC) is implemented.

You might also like