0% found this document useful (0 votes)
10 views

CS8381 - Data Structures Laboratory

Comprehensive exercises on implementing and analyzing fundamental data structures and algorithms.

Uploaded by

Joshua Fernando
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

CS8381 - Data Structures Laboratory

Comprehensive exercises on implementing and analyzing fundamental data structures and algorithms.

Uploaded by

Joshua Fernando
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

1

SRI VENKATESWARAA COLLEGE OF TECHNOLOGY


BHB Nagar, Vadakal Village, Pondur Post, Sriperambudur - 602 105.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

BE- Computer Science and Engineering


&
BE – CSE (Cyber security)

Anna University Regulation: 2021

CS3591- Computer Networks

III Year/V Semester

Lab Manual

A B Prameela SVCT
2

Exercise No: 1

Learn to use commands like tcpdump, netstat, ifconfig, nslookup, and traceroute.
Capture ping and traceroute PDUs using a network protocol analyzer and examine.

Aim:

To use commands like tcpdump, netstat, ifconfig, nslookup, and traceroute. Capture ping and
traceroute PDUs using a network protocol analyzer and examine.

1. Tcpdump

Tcpdump is a command-line utility that allows you to capture and analyze network traffic going
through your system.

Procedure

1. Check if tcpdump is installed on your system:

bash

$ which tcpdump
/usr/sbin/tcpdump

If tcpdump is not installed:

bash

$ sudo apt install tcpdump

2. To get Supervisor Privilege:

bash

$ su
(and password 123456)
$ sudo -i # Change to root

3. Capturing packets with tcpdump: Use the command tcpdump -D to see which interfaces are
available for capture.

bash

[root@localhost cse]# tcpdump -D


1. nflog (Linux netfilter log (NFLOG) interface)
2. nfqueue (Linux netfilter queue (NFQUEUE) interface)
3. usbmon1 (USB bus number 1)
4. enp2s0
5. usbmon2 (USB bus number 2)
6. any (Pseudo-device that captures on all interfaces)

A B Prameela SVCT
3

7. lo [Loopback]

4. Capture all packets on any interface:

bash

[root@localhost cse]# tcpdump -i any


06:03:58.258143 ARP, Request who-has 172.16.51.87 tell 172.16.22.25, length 46
...
^C
5244 packets captured
59636 packets received by filter
54378 packets dropped by kernel

5. Filter packets based on source or destination IP Address:

bash

[root@localhost cse]# tcpdump -i any -c5 -nn src 172.16.20.138


6:10:30.712414 ARP, Request who-has 172.16.16.16 tell 172.16.20.138, length 28
...
5 packets captured

6. Filtering packets based on protocol: Capture only ICMP packets:

bash

[root@localhost cse]# tcpdump -i any -c5 icmp

Output:

bash

06:15:07.800786 IP localhost.localdomain > ec2-54-204-39-132.compute-


1.amazonaws.com: ICMP echo request, id 8180, seq 13, length 64
...
5 packets captured

7. In a different terminal, try to ping another machine:

bash

$ ping opensource.com

2. Netstat

Netstat (network statistics) is a command-line tool for monitoring network connections (both
incoming and outgoing) as well as viewing routing tables and interface statistics.

bash

[root@localhost cse]# netstat


Active Internet connections (w/o servers)
Proto Recv-Q Send-Q LocalAddress Foreign Address State
tcp 0 0 localhost.localdo:53318 ec2-52-206-98-166:https ESTABLISHED
tcp 0 0 localhost.localdo:36418 sg2plpkivs-v03.any:http TIME_WAIT

 -at → list all TCP ports


 -au → list all UDP ports
 -l → listening ports

A B Prameela SVCT
4

 -lt → listening TCP


 -lu → listening UDP
 -s → statistics of all ports
 -su → statistics of UDP
 -st → statistics of TCP

3. Ifconfig

Ifconfig displays details of a network interface card like IP address, MAC address, and the status of
the network interface card.

bash

[cse@localhost ~]$ ifconfig


enp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.16.20.138 netmask 255.255.0.0 broadcast 172.16.255.255
inet6 fe80::d884:13bc:fd22:2d43 prefixlen 64 scopeid 0x20<link>
ether a0:8c:fd:e7:10:86 txqueuelen 1000 (Ethernet)
RX packets 4474083 bytes 280780119 (267.7 MiB)
...

4. Nslookup

Nslookup (stands for “Name Server Lookup”) is a useful command for getting information from DNS
servers. It queries the Domain Name System (DNS) to obtain domain name or IP address mapping.

bash

[cse@localhost ~]$ nslookup annauniv.edu


Server: 8.8.8.8
Address: 8.8.8.8#53

Non-authoritative answer:
Name: annauniv.edu
Address: 103.70.60.38

5. Traceroute

The traceroute command is used in Linux to map the journey that a packet of information undertakes
from its source to its destination.

bash

[cse@localhost ~]$ traceroute annauniv.edu


traceroute to annauniv.edu (103.70.60.38), 30 hops max, 60 byte packets
1 117.193.124.33 (117.193.124.33) 1.389 ms 1.216 ms 1.072 ms
2 172.16.199.74 (172.16.199.74) 1.902 ms 1.834 ms 1.761 ms
...

Network Protocol Analyzer - Wireshark

Wireshark is a free and open-source network packet analyzer used for network analysis,
troubleshooting, etc. Wireshark has a graphical interface with built-in filtering options, making it easy
to use.

A B Prameela SVCT
5

Installation Commands for Wireshark:

bash
# sudo apt install wireshark

To Open Wireshark:

bash
# sudo wireshark

In Wireshark, filter ICMP packets:

Execute the following in a console:

bash

# ping www.sudo.com
# traceroute www.google.com

A B Prameela SVCT
6

Result:
Thus commands like tcpdump, netstat, ifconfig, nslookup and traceroute was used. Ping and
traceroute PDUs using a network protocol analyzer was captured and examined.

A B Prameela SVCT
7

Exercise No. 2

Write an HTTP Web Client Program to Download a Web Page Using TCP Sockets

Aim:

To write a program in Java to create an HTTP web client that downloads a web page using TCP
sockets.

Algorithm:

1. Start the program.


2. Read the file to be downloaded from the webpage.
3. To download an image, use the Java URL class, which can be found in the java.net package.
4. The file is downloaded from the server and stored in the current working directory.
5. Stop the program.

Program: Download.java
import java.io.*;
import java.net.URL;

public class Download {


public static void main(String[] args) throws Exception {
try {
String fileName = "digital_image_processing.jpg";
String website = "http://tutorialspoint.com/java_dip/images/" +
fileName;
System.out.println("Downloading File From: " + website);

URL url = new URL(website);


InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[2048];
int length;

while ((length = inputStream.read(buffer)) != -1) {


System.out.println("Buffer Read of length: " + length);
outputStream.write(buffer, 0, length);
}

inputStream.close();
outputStream.close();
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

Output
bash

A B Prameela SVCT
8

F:\Project\Lab>javac Download.java
F:\Project\Lab>java Download
Downloading File From:
http://tutorialspoint.com/java_dip/images/digital_image_processing.jpg
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1097
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1744
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1440
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 548
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 2048
Buffer Read of length: 1863

The downloaded file is stored in the current working directory.

Result:
Thus created a program in java for a HTTP web client program to download a web page using TCP
sockets is written and executed successfully.

A B Prameela SVCT
9

Exercise No. 3a

APPLICATION USING TCP SOCKETS - ECHO CLIENT AND ECHO SERVER

Aim:

To write a program in Java to implement applications using TCP sockets, specifically an echo client
and an echo server.

Algorithm:

1. Start the Program.


2. In the Server: a. Create a server socket and bind it to a port.
b. Listen for new connections; when a connection arrives, accept it.
c. Read the data from the client.
d. Echo the data back to the client.
e. Close all streams.
f. Close the server socket.
g. Stop.
3. In the Client: a. Create a client socket and connect it to the server’s port number.
b. Send user data to the server.
c. Display the data echoed by the server.
d. Close the input and output streams.
e. Close the client socket.
f. Stop.
4. Stop the Program.

Program: Server.java
java

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

public class Server {


public static final int PORT = 4000;

public static void main(String args[]) {


ServerSocket sersock = null;
Socket sock = null;

try {
sersock = new ServerSocket(PORT);
System.out.println("Server Started: " + sersock);
try {
sock = sersock.accept();
System.out.println("Client Connected: " + sock);
DataInputStream ins = new DataInputStream(sock.getInputStream());
System.out.println(ins.readLine());
PrintStream ios = new PrintStream(sock.getOutputStream());
ios.println("Hello from server");
ios.close();

A B Prameela SVCT
10

sock.close();
} catch (SocketException se) {
System.out.println("Server Socket problem: " + se.getMessage());
}
} catch (Exception e) {
System.out.println("Couldn't start: " + e.getMessage());
}
System.out.println("Connection from: " + sock.getInetAddress());
}
}

Program: Client.java
java

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

class Client {
public static void main(String args[]) {
Socket sock = null;
DataInputStream dis = null;
PrintStream ps = null;

System.out.println("Trying to connect");

try {
sock = new Socket(InetAddress.getLocalHost(), Server.PORT);
ps = new PrintStream(sock.getOutputStream());
ps.println("Hi from client");

DataInputStream is = new DataInputStream(sock.getInputStream());


System.out.println(is.readLine());
} catch (SocketException e) {
System.out.println("SocketException: " + e);
} catch (IOException e) {
System.out.println("IOException: " + e);
} finally {
try {
sock.close();
} catch (IOException ie) {
System.out.println("Close Error: " + ie.getMessage());
}
}
}
}

Output

In Server Window:

bash

F:\Project\Lab>javac Server.java
F:\Project\Lab>java Server
Server Started: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=4000]
Client Connected: Socket[addr=/192.168.1.18,port=1815,localport=4000]
Hi from client
Connection from: /192.168.1.18

A B Prameela SVCT
11

In Client Window:

bash

F:\Project\Lab>javac Client.java
F:\Project\Lab>java Client
Trying to connect
Hello from server

Result:

Thus, a program in Java was implemented to create applications using TCP sockets, including an echo
client and an echo server.

A B Prameela SVCT
12

Exercise No. 3b

APPLICATION USING TCP SOCKETS - CHAT

Aim:

To write a program in Java to implement an application using TCP sockets for chat functionality.

Algorithm:

1. Start the Program.


2. In the Server: a. Create a server socket and bind it to a port.
b. Listen for new connections; when a connection arrives, accept it.
c. Read the client's message and display it.
d. Get a message from the user and send it to the client.
e. Repeat steps 3-4 until the client sends "end".
f. Close all streams.
g. Close the server and client socket.
h. Stop.
3. In the Client: a. Create a client socket and connect it to the server’s port number.
b. Get a message from the user and send it to the server.
c. Read the server's response and display it.
d. Repeat steps 2-3 until chat is terminated with the "end" message.
e. Close all input/output streams.
f. Close the client socket.
g. Stop.
4. Stop the Program.

Program: tcpchatserver.java
java

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

class tcpchatserver {
public static void main(String args[]) throws Exception {
PrintWriter toClient;
BufferedReader fromUser, fromClient;

try {
ServerSocket Srv = new ServerSocket(4000);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client connected");

toClient = new PrintWriter(new BufferedWriter(new


OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));

String CltMsg, SrvMsg;

A B Prameela SVCT
13

while (true) {
CltMsg = fromClient.readLine();
if (CltMsg.equals("end"))
break;
else {
System.out.println("Server: " + CltMsg);
System.out.print("Message to Client: ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
} catch (Exception E) {
System.out.println(E.getMessage());
}
}
}

Program: tcpchatclient.java
java

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

class tcpchatclient {
public static void main(String args[]) throws Exception {
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;

try {
Clt = new Socket(InetAddress.getLocalHost(), 4000);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));

String CltMsg, SrvMsg;


System.out.println("Type \"end\" to Quit");

while (true) {
System.out.print("Message to Server: ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);

if (CltMsg.equals("end"))
break;

SrvMsg = fromServer.readLine();
System.out.println("Client: " + SrvMsg);
}
} catch (Exception E) {
System.out.println(E.getMessage());
}
}
}

A B Prameela SVCT
14

Output

In Server Window:

bash

F:\Project\Lab>javac tcpchatserver.java
F:\Project\Lab>java tcpchatserver
Server started
Client connected
Server: hai
Message to Client: hello
Client Disconnected

In Client Window:

bash

F:\Project\Lab>javac tcpchatclient.java
F:\Project\Lab>java tcpchatclient
Type "end" to Quit
Message to Server: hai
Client: hello
Message to Server: end

Result:

Thus, a program in Java was implemented to create an application using TCP sockets for chat.

A B Prameela SVCT
15

Exercise .No. 4

SIMULATION OF DNS USING UDP SOCKETS

Aim:

To write a program in Java to perform a simulation of DNS using UDP sockets.

Algorithm:

1. Start the Program.


2. In the Server: a. Create an array of hosts and another array for their corresponding IP addresses.
b. Create a DatagramSocket and bind it to a port.
c. Create a DatagramPacket to receive client requests.
d. Read the domain name from the client to be resolved.
e. Look up the host array for the domain name.
f. If found, retrieve the corresponding address.
g. Create a DatagramPacket and send the IP address to the client.
h. Repeat steps 3-7 to resolve further requests from clients.
i. Close the server socket.
j. Stop.
3. In the Client: a. Create a DatagramSocket.
b. Get the domain name from the user.
c. Create a DatagramPacket and send the domain name to the server.
d. Create a DatagramPacket to receive the server's message.
e. Read the server's response.
f. If it's an IP address, display it; otherwise, display "Domain does not exist."
g. Close the client socket.
h. Stop.
4. Stop the Program.

Program: dnsclient.java
java

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

public class dnsclient {


public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;

if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);

byte[] senddata = new byte[1024];


byte[] receivedata = new byte[1024];
int portaddr = 8080;

A B Prameela SVCT
16

System.out.print("Enter the hostname: ");


String sentence = br.readLine();
senddata = sentence.getBytes();

DatagramPacket pack = new DatagramPacket(senddata, senddata.length,


ipaddress, portaddr);
clientsocket.send(pack);

DatagramPacket recvpack = new DatagramPacket(receivedata,


receivedata.length);
clientsocket.receive(recvpack);

String modified = new String(recvpack.getData()).trim();


System.out.println("IP Address: " + modified);
clientsocket.close();
}
}

Program: dnsserver.java
java

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

public class dnsserver {


private static int indexOf(String[] array, String str) {
str = str.trim();
for (int i = 0; i < array.length; i++) {
if (array[i].equals(str)) return i;
}
return -1;
}

public static void main(String arg[]) throws IOException {


String[] hosts = {"yahoo.com", "gmail.com", "cricinfo.com",
"facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19", "80.168.92.140",
"69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");

while (true) {
DatagramSocket serversocket = new DatagramSocket(8080);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];

DatagramPacket recvpack = new DatagramPacket(receivedata,


receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData()).trim();
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;

System.out.println("Request for host: " + sen);


if (indexOf(hosts, sen) != -1)
capsent = ip[indexOf(hosts, sen)];
else
capsent = "Host Not Found";

senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata, senddata.length,
ipaddress, port);
serversocket.send(pack);

A B Prameela SVCT
17

serversocket.close();
}
}
}

Output

In Server Window:

bash

F:\Project\Lab>javac dnsserver.java
F:\Project\Lab>java dnsserver
Press Ctrl + C to Quit
Request for host yahoo.com

In Client Window:

bash

F:\Project\Lab>javac dnsclient.java
F:\Project\Lab>java dnsclient
Enter the hostname: yahoo.com
IP Address: 68.180.206.184

Result:

Thus, a program in Java performed a simulation of DNS using UDP sockets.

A B Prameela SVCT
18

Exercise No. 5

Aim: To use a tool like Wireshark to capture packets and examine them.

Procedure:

1. Implement code to capture packets.


2. Examine the captured packets using Wireshark.
3. Analyze protocols and identify the source and destination of the traffic.

Program:

A network packet analyzer captures network packets and displays the packet data in detail, identifying
and analyzing protocols, as well as identifying the source and destination of traffic.

python

import sys
from scapy.all import *

# Define the packet capturing function


def packet_handler(packet):
print(packet.show())

# Capture packets on the network interface


sniff(iface='eth0', prn=packet_handler)

Output:
makefile

###[ Ethernet ]###


dst = 00:11:22:33:44:55
src = 66:77:88:99:00:11
type = IPv4
###[ IP ]###
version = 4
ihl = 5
tos = 0x0
len = 1500
id = 52786
flags = DF
frag = 0
ttl = 128
proto = tcp
chksum = 0xe877
src = 192.168.1.10
dst = 216.58.194.78
###[ TCP ]###
sport = 54321
dport = http
seq = 3665840854
ack = 2542707921
dataofs = 5
reserved = 0
flags = FA
window = 8760

A B Prameela SVCT
19

chksum = 0x9d6c
urgptr = 0
options = [('MSS', 1460), ('SAckOK', ''), ('Timestamp', (12576855, 2413)), ('NOP',
None), ('WScale', 7)]
###[ Raw ]###
load = ''

Result:

Thus, the program was executed successfully using Wireshark to capture and examine packets.

A B Prameela SVCT
20

Exercise No. 6a

SIMULATION OF ARP PROTOCOLS

Aim:

To write a program in Java to simulate ARP protocols.

Algorithm:

1. Start the program.


2. In Client: a. Start the program.
b. Establish a socket connection between client and server.
c. Get the IP address to be converted into a MAC address.
d. Send this IP address to the server.
e. Server returns the MAC address to the client.
3. In Server: a. Start the program.
b. Accept the socket created by the client.
c. Maintain a table with IP and corresponding MAC addresses.
d. Read the IP address sent by the client.
e. Map the IP address to its MAC address and return it to the client.
4. Stop the program.

Program: Clientarp.java
java

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

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", 139);
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);
}
}
}

A B Prameela SVCT
21

Program: Serverarp.java
java

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

class Serverarp {
public static void main(String args[]) {
try {
ServerSocket obj = new ServerSocket(139);
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
bash

F:\ Project\2020-2021\Odd\Network Lab>java Serverarp


F:\ Project\2020-2021\Odd\Network Lab>java Clientarp
Enter the Logical address (IP): 165.165.80.80
The Physical Address is: 6A:08:AA:C2

Result:

Thus, a program in Java simulated ARP protocols.

A B Prameela SVCT
22

Exercise No. 6b

SIMULATION OF RARP PROTOCOLS

Aim:

To write a program in Java to simulate RARP protocols.

Algorithm:

1. Start the program.


2. In Client: a. Start the program.
b. Establish a socket connection between client and server.
c. Get the MAC address to be converted into an IP address.
d. Send this MAC address to the server.
e. Server returns the IP address to the client.
3. In Server: a. Start the program.
b. Accept the socket created by the client.
c. Maintain a table with IP and corresponding MAC addresses.
d. Read the MAC address sent by the client.
e. Map the MAC address to its corresponding IP address and return it to the client.
4. Stop the program.

Program: clientrarp.java
java

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

public 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[1204];
byte[] receiveByte = new byte[1024];

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));
System.out.println("Enter the Physical Address: ");
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: " + s.trim());
client.close();

A B Prameela SVCT
23

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

Program: serverrarp.java
java

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

public class serverrarp {


public static void main(String args[]) {
try {
DatagramSocket server = new DatagramSocket(1309);
while (true) {
byte[] sendByte = new byte[1204];
byte[] receiveByte = new byte[1204];

DatagramPacket receiver = new DatagramPacket(receiveByte,


receiveByte.length);
server.receive(receiver);

String str = new String(receiver.getData()).trim();


InetAddress addr = receiver.getAddress();
int port = receiver.getPort();

String[] ip = {"10.0.3.186"};
String[] mac = {"D4:3D:7E:12:A3:D9"};

for (int i = 0; i < ip.length; i++) {


if (str.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:
bash

F:\ Project\2020-2021\Odd\Network Lab>java serverrarp


F:\ Project\2020-2021\Odd\Network Lab>java clientrarp
Enter the Physical Address: D4:3D:7E:12:A3:D9
The Logical Address is: 10.0.3.186

Result:
Thus, a program in Java simulated RARP protocols.

A B Prameela SVCT
24

Exercise No. 7a

STUDY OF NETWORK SIMULATOR (NS)

AIM:

To study Network Simulator in detail.

INTRODUCTION:

Network Simulator (Version 2), widely known as NS2, is an event-driven simulation tool that has
proven useful in studying the dynamic nature of communication networks. Simulation of both wired
and wireless network functions and protocols (e.g., routing algorithms, TCP, UDP) can be performed
using NS2.

In general, NS2 provides users with a means to specify network protocols and simulate their
corresponding behaviors. Due to its flexibility and modular nature, NS2 has gained consistent
popularity in the networking research community since its inception in 1989. Over the years, several
revisions and enhancements have contributed to the growing maturity of the tool, thanks to substantial
contributions from key players in the field.

Notably, the University of California and Cornell University developed the REAL network simulator,
which serves as the foundation for NS. Since 1995, the Defense Advanced Research Projects Agency
(DARPA) has supported the development of NS through the Virtual InterNetwork Testbed (VINT)
project. Currently, the National Science Foundation (NSF) has also joined in the development efforts.

Moreover, a dedicated group of researchers and developers in the community are continuously
working to keep NS2 robust and versatile.

BASIC ARCHITECTURE :

The figure shows the basic architecture of NS2. NS2 provides users with an executable command ns,
which takes as input the name of a Tcl simulation scripting file. Users supply the name of a Tcl
simulation script (which sets up a simulation) as an argument to the ns executable command.

In most cases, a simulation trace file is created, which is used to plot graphs and/or create animations.
NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl). The
C++ part defines the internal mechanisms (backend) of the simulation objects, while OTcl is used to

A B Prameela SVCT
25

set up the simulation by assembling and configuring the objects, as well as scheduling discrete events
(frontend).

The C++ and OTcl components are linked using TclCL. Mapped to a C++ object, variables in the OTcl
domain are often referred to as handles. Conceptually, a handle (e.g., n as a Node handle) is simply a
string (e.g., _o10) in the OTcl domain and does not contain any functionality. Instead, the functionality
(e.g., receiving a packet) is defined in the corresponding C++ object (e.g., of class Connector). In the
OTcl domain, a handle acts as a frontend that interacts with users and other OTcl objects. It may define
its own procedures and variables to facilitate this interaction. Note that member procedures and
variables in the OTcl domain are referred to as instance procedures (instprocs) and instance variables
(instvars), respectively. Readers are encouraged to learn C++ and OTcl languages before proceeding
further.

NS2 provides a wide range of built-in C++ objects. It is advisable to use these objects to set up a
simulation with a Tcl simulation script. However, advanced users may find these objects insufficient
and may need to develop their own C++ objects, using an OTcl configuration interface to assemble
these objects. After simulation, NS2 outputs either text-based or animation-based results. Tools such as
NAM (Network AniMator) and XGraph can be used to interpret these results graphically and
interactively. Users can extract relevant subsets of text-based data to transform it into a more
understandable presentation.

CONCEPT OVERVIEW

NS2 employs two languages because the simulator has two different types of tasks it needs to perform.
On one hand, detailed simulations of protocols require a systems programming language that can
efficiently manipulate bytes, packet headers, and implement algorithms running over large data sets.
For these tasks, runtime speed is important, while turnaround time (i.e., run simulation, find bug, fix
bug, recompile, re-run) is less critical.

On the other hand, much of network research involves slightly varying parameters or configurations,
or quickly exploring numerous scenarios. In these cases, iteration time (i.e., change the model and re-
run) is more important. Since configuration runs only once (at the beginning of the simulation), the
runtime of this part of the task is less critical. NS2 addresses both of these needs with C++ and OTcl.

BASIC COMMANDS IN NS2

 Create Event Scheduler:

tcl

set ns [new Simulator]

 Trace Packets on All Links:

tcl

set nf [open out.nam]


$ns trace-all $nf
$ns namtrace-all $nf

 Nodes:

A B Prameela SVCT
26

tcl

set n0 [$ns node]


set n1 [$ns node]

 Links and Queuing:

tcl

$ns duplex-link $n0 $n1 <bandwidth> <delay> <queue_type>


# Example:
$ns duplex-link $n0 $n1 1Mb 10ms RED

 Creating a Larger Topology:

tcl

for {set i 0} {$i < 7} {incr i} {


set n($i) [$ns node]
}

for {set i 0} {$i < 7} {incr i} {


$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms RED
}

 Link Failures:

tcl

$ns rtmodel-at <time> up|down $n0 $n1

 Creating a UDP Connection:

tcl

set udp [new Agent/UDP]


set null [new Agent/Null]
$ns attach-agent $n0 $udp
$ns attach-agent $n1 $null
$ns connect $udp $null

 Creating Traffic (On Top of UDP):

tcl

set cbr [new Application/Traffic/CBR]


$cbr set packetSize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp

 Post-Processing Procedures:

tcl

proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}

A B Prameela SVCT
27

 Schedule Events:

tcl

$ns at <time> <event>


# Call ‘finish’
$ns at 5.0 "finish"

 Run the Simulation:

tcl

$ns run

RESULT:
Thus the study of NS was done successfully.

A B Prameela SVCT
28

Exercise No. 7b:

Simulation of Congestion Control Algorithms Using NS

Aim:

To perform a simulation of Congestion Control Algorithms (sliding window) using NS.

Algorithm:

1. Run NSG 2.1.


2. Create two nodes: n0 and n1.
3. Create a duplex link and set the following parameters:
o Queue type: DropTail
o Capacity: 0.2 Mbps
o Propagation delay: 200 ms
o Queue size: 10
4. Create a link from n0 to n1.
5. In the Agent tab, do the following:
o Packet size: 500 bytes
o Agent type: TCP (draw a line from n0).
o Agent type: TCP Sink (draw a line from n1).
o Draw a line from TCP to sink.
6. In the Application tab, do the following:
o Application Type: FTP
o Start time: 0.1
o Stop time: 3.5
o Draw a line from TCP.
7. In the Parameters tab, do the following:
o Simulation time: 5.0
o Trace file: sliding.tr
o NAM file: sliding.nam
o Click Done.
8. Click TCL and specify the window size of the sliding window and the transfer of packets, then save
the file as sliding.tcl in C:\cygwin\Your folder.

Program:

tcl

#===================================
# Simulation parameters setup
#===================================

set val(stop) 5.0 ;# time of simulation end

#===================================
# Initialization
#===================================
# Create a ns simulator
set ns [new Simulator]

# Open the NS trace file


set tracefile [open sliding.tr w]
$ns trace-all $tracefile

A B Prameela SVCT
29

# Open the NAM trace file


set namfile [open sliding.nam w]
$ns namtrace-all $namfile

#===================================
# Nodes Definition
#===================================
# Create 2 nodes
set n0 [$ns node]
set n1 [$ns node]

$ns at 0.0 "$n0 label Sender"


$ns at 0.0 "$n1 label Receiver"

#===================================
# Links Definition
#===================================
# Create links between nodes
$ns duplex-link $n0 $n1 0.2Mb 200ms DropTail
$ns queue-limit $n0 $n1 10

# Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right

#===================================
# Agents Definition
#===================================
# Setup a TCP connection
set tcp1 [new Agent/TCP]
$tcp1 set windowInit_ 4
$tcp1 set maxcwnd_ 4

$ns attach-agent $n0 $tcp1


set sink2 [new Agent/TCPSink]
$ns attach-agent $n1 $sink2
$ns connect $tcp1 $sink2
$tcp1 set packetSize_ 500

#===================================
# Applications Definition
#===================================
# Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp1

$ns add-agent-trace $tcp1 tcp


$ns monitor-agent-trace $tcp1 $tcp1 tracevar cwnd_

$ns at 0.1 "$ftp0 start"


$ns at 3.5 "$ftp0 stop"

$ns at 0.0 "$ns trace-annotate \"Sliding Window with window size 4 (normal
operation)\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.1\""
$ns at 0.11 "$ns trace-annotate \"Send Packet 0,1,2,3\""
$ns at 0.34 "$ns trace-annotate \"Receive Ack 0,1,2,3\""
$ns at 0.56 "$ns trace-annotate \"Send Packet 4,5,6,7\""
$ns at 0.79 "$ns trace-annotate \"Receive Ack 4,5,6,7\""
$ns at 0.99 "$ns trace-annotate \"Send Packet 8,9,10,11\""
$ns at 1.23 "$ns trace-annotate \"Receive Ack 8,9,10,11\""
$ns at 1.43 "$ns trace-annotate \"Send Packet 12,13,14,15\""
$ns at 1.67 "$ns trace-annotate \"Receive Ack 12,13,14,15\""
$ns at 1.88 "$ns trace-annotate \"Send Packet 16,17,18,19\""
$ns at 2.11 "$ns trace-annotate \"Receive Ack 16,17,18,19\""
$ns at 2.32 "$ns trace-annotate \"Send Packet 20,21,22,23\""
$ns at 2.56 "$ns trace-annotate \"Receive Ack 24,25,26,27\""
$ns at 2.76 "$ns trace-annotate \"Send Packet 28,29,30,31\""

A B Prameela SVCT
30

$ns at 3.00 "$ns trace-annotate \"Receive Ack 28\""


$ns at 3.1 "$ns trace-annotate \"FTP stops\""

#===================================
# Termination
#===================================
# Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam sliding.nam &
exit 0
}

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"


$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Steps to Execute:

1. Run Cygwin and change the directory:

bash

admin@CS03C037 ~ $ cd ..
admin@CS03C037 /home $ cd ..
admin@CS03C037 / $ ls
Cygwin.bat Cygwin.ico Project bin cygdrive dev etc home lib opt proc
tmp usr var
admin@CS03C037 / $ cd Project
admin@CS03C037 /Project $ ls
sliding.tcl

A B Prameela SVCT
31

2. Run the TCL file:

bash

admin@CS03C037 /Project $ ns sliding.tcl

3. Run the NAM file:


o Open nam-1.0a11a-win32.exe.
o In File → Open, select sliding.nam from C:\cygwin\Your folder.

Result:

Thus, the simulation of Congestion Control Algorithms (sliding window) using NS has been
performed.

A B Prameela SVCT
32

Exercise. No: 8:

Study of TCP/UDP Performance Using Simulation Tool

Aim:

To study the performance of TCP/UDP using the simulation tool (NS2).

Algorithm:

1. Create 4 nodes (n0, n1, n2, n3).


2. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay.
3. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay.
4. Each node uses a DropTail queue, with a maximum size of 10.
5. A TCP agent is attached to n0, and a connection is established to a TCP sink agent attached to n3.
6. By default, the maximum size of a packet that a TCP agent can generate is 1 KByte.
7. A TCP sink agent generates and sends ACK packets to the sender (TCP agent) and frees the received
packets.
8. A UDP agent attached to n1 is connected to a null agent attached to n3.
9. A null agent just frees the packets received.
10. An FTP and a CBR traffic generator are attached to TCP and UDP agents, respectively; the CBR is
configured to generate 1 KByte packets at the rate of 1 Mbps.
11. The CBR is set to start at 0.1 sec and stop at 4.5 sec, while FTP is set to start at 1.0 sec and stop at 4.0
sec.

Program:
tcl

# Create a simulator object


set ns [new Simulator]

# Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

# Open the NAM trace file


set nf [open out.nam w]
$ns namtrace-all $nf

# Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}

# Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

# Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail

A B Prameela SVCT
33

$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

# Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 10

# Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

# Monitor the queue for link (n2-n3) (for NAM)


$ns duplex-link-op $n2 $n3 queuePos 0.5

# Setup a TCP connection


set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

# Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

# Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp

set null [new Agent/Null]


$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2

# Setup a CBR over UDP connection


set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

# Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"

# Detach TCP and sink agents (not really necessary)


$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

# Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

# Print CBR packet size and interval


puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"

# Run the simulation


$ns run

A B Prameela SVCT
34

Result:
Thus studied the performance of TCP/UDP using Simulation Tool (NS2)

A B Prameela SVCT
35

Exercise No.9a:

Simulation of Distance Vector Routing Algorithm

Aim:

To perform a simulation of the Distance Vector Routing algorithm.

Algorithm:

1. Create a simulator object.


2. Define different colors for different data flows.
3. Open a NAM trace file and define a finish procedure; then close the trace file and execute NAM on the
trace file.
4. Create a number of nodes using a for loop.
5. Create duplex links between the nodes.
6. Set up a UDP connection between n(0) and n(5).
7. Set up another UDP connection between n(1) and n(5).
8. Apply CBR traffic over both UDP connections.
9. Choose the Distance Vector routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.

Program (Distance Vector Protocol)


tcl
# Create a simulator object
set ns [new Simulator]
# Open the trace files
set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
# Define finish procedure
proc finish {} {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
# Create nodes
for {set i 0} {$i < 12} {incr i} {
set n($i) [$ns node]
}
# Create duplex links between nodes
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i + 1]) 1Mb 10ms DropTail
}
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
# Setup UDP connections and CBR traffic
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]

A B Prameela SVCT
36

$cbr0 set packetSize_ 500


$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null1 [new Agent/Null]
$ns attach-agent $n(5) $null1
$ns connect $udp1 $null1
# Set routing protocol to Distance Vector
$ns rtproto DV
# Set link failures and restorations
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
# Define flow colors
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
# Schedule events
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
# Run the simulation
$ns run

Output

The output will include the results of the simulation based on the implemented Distance Vector
Routing protocol.

A B Prameela SVCT
37

Result:
Thus performed Simulation of Distance Vector Routing algorithm.

A B Prameela SVCT
38

Exercise No. 9b:

Simulation of Link State Routing Algorithm

Aim:

To perform a simulation of the Link State Routing algorithm.

Algorithm:

1. Create a simulator object.


2. Define different colors for different data flows.
3. Open a NAM trace file and define a finish procedure; then close the trace file and execute NAM on the
trace file.
4. Create a number of nodes using a for loop.
5. Create duplex links between the nodes.
6. Set up a UDP connection between n(0) and n(5).
7. Set up another UDP connection between n(1) and n(5).
8. Apply CBR traffic over both UDP connections.
9. Choose the Link State routing protocol to transmit data from sender to receiver.
10. Schedule events and run the program.

Program (Link State Protocol)


tcl

# Create a simulator object


set ns [new Simulator]

# Open the trace files


set nr [open link.tr w]
$ns trace-all $nr
set nf [open link.nam w]
$ns namtrace-all $nf

# Define finish procedure


proc finish {} {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam link.nam &
exit 0
}

# Create nodes
for {set i 0} {$i < 12} {incr i} {
set n($i) [$ns node]
}

# Create duplex links between nodes


for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i + 1]) 1Mb 10ms DropTail
}

$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail


$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail

A B Prameela SVCT
39

$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail


$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail

# Setup UDP connections and CBR traffic


set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0

set cbr0 [new Application/Traffic/CBR]


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

set null0 [new Agent/Null]


$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0

set udp1 [new Agent/UDP]


$ns attach-agent $n(1) $udp1

set cbr1 [new Application/Traffic/CBR]


$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

set null1 [new Agent/Null]


$ns attach-agent $n(5) $null1
$ns connect $udp1 $null1

# Set routing protocol to Link State


$ns rtproto LS

# Set link failures and restorations


$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)

# Define flow colors


$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green

# Schedule events
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"

# Run the simulation


$ns run

A B Prameela SVCT
40

Output:

Result:
Thus performed Simulation of Link State Routing algorithm.

A B Prameela SVCT
41

Exercise No. 10:

Simulation of Error Correction Code (CRC)

Aim:

To write a program in Java to implement the Simulation of Error Correction Code (CRC).

Algorithm:

At Sender Side:

1. Start the program.


2. Read the number of bits to be sent. Let nnn be the number of bits in data to be sent from the sender
side.
3. Read the number of bits in the divisor. Let kkk be the number of bits in the divisor (key obtained from
the generator polynomial).
4. The binary data is first increased by adding k−1k-1k−1 zeros at the end of the data.
5. Use modulo-2 binary division to divide the binary data by the divisor and store the remainder of the
division.
6. Append the remainder at the end of the data to form the encoded data and send it.

At Receiver Side:

1. Perform modulo-2 division again. If the remainder is 0, then there are no errors.

Modulo-2 Division:

 In each step, a copy of the divisor (or data) is XORed with the kkk bits of the dividend.
 The result of the XOR operation (remainder) is (n−1)(n-1)(n−1) bits, which is used for the next step
after pulling down 1 extra bit to make it nnn bits long.
 When there are no bits left to pull down, we have a result. The (n−1)(n-1)(n−1)-bit remainder is
appended at the sender side.

Program (CRC Implementation in Java)


java
Copy code
import java.io.*;
import java.util.*;

class CRC {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n;

// Read input for data size


System.out.println("Enter the size of the data:");
n = input.nextInt();
int[] data = new int[n];
System.out.println("Enter the data, bit by bit:");
for (int i = 0; i < n; i++) {
System.out.println("Enter bit number " + (n - i) + ":");
data[i] = input.nextInt();
}

A B Prameela SVCT
42

// Read Divisor
System.out.println("Enter the size of the divisor:");
n = input.nextInt();
int[] divisor = new int[n];
System.out.println("Enter the divisor, bit by bit:");
for (int i = 0; i < n; i++) {
System.out.println("Enter bit number " + (n - i) + ":");
divisor[i] = input.nextInt();
}

// Perform Division
int[] remainder = divide(data, divisor);
System.out.print("Remainder: ");
for (int i = 0; i < remainder.length - 1; i++) {
System.out.print(remainder[i]);
}
System.out.println("\nThe CRC code generated is:");

// Print data + remainder


for (int i = 0; i < data.length; i++) {
System.out.print(data[i]);
}
for (int i = 0; i < remainder.length - 1; i++) {
System.out.print(remainder[i]);
}
System.out.println();

// Append the remainder


int[] sentData = new int[data.length + remainder.length - 1];
System.arraycopy(data, 0, sentData, 0, data.length);
System.arraycopy(remainder, 0, sentData, data.length, remainder.length -
1);

// Simulate sending data


System.out.println("Enter the data to be sent:");
for (int i = 0; i < sentData.length; i++) {
System.out.println("Enter bit number " + (sentData.length - i) + ":");
sentData[i] = input.nextInt();
}

// Receive and check data


receive(sentData, divisor);
}

static int[] divide(int[] oldData, int[] divisor) {


int[] remainder = new int[divisor.length];
int[] data = new int[oldData.length + divisor.length];
System.arraycopy(oldData, 0, data, 0, oldData.length);

// Initially copy the first bits into remainder


System.arraycopy(data, 0, remainder, 0, divisor.length);
for (int i = 0; i < oldData.length; i++) {
System.out.println((i + 1) + ".) First data bit is: " + remainder[0]);
System.out.print("Remainder: ");

// XOR operation based on the first bit of remainder


for (int j = 1; j < divisor.length; j++) {
if (remainder[0] == 1) {
remainder[j - 1] = exor(remainder[j], divisor[j]);
} else {
remainder[j - 1] = exor(remainder[j], 0);
}
System.out.print(remainder[j - 1]);
}
remainder[divisor.length - 1] = data[i + divisor.length];
System.out.println(remainder[divisor.length - 1]);
}

A B Prameela SVCT
43

return remainder;
}

static int exor(int a, int b) {


return a == b ? 0 : 1;
}

static void receive(int[] data, int[] divisor) {


int[] remainder = divide(data, divisor);
for (int value : remainder) {
if (value != 0) {
System.out.println("There is an error in received data...");
return;
}
}
System.out.println("Data was received without any error.");
}
}

Output
yaml
Copy code
D:\Project>javac crc.java
D:\Project>java crc
Enter the size of the data:
7
Enter the data, bit by bit:
Enter bit number 7:
1
Enter bit number 6:
0
Enter bit number 5:
0
Enter bit number 4:
1
Enter bit number 3:
1
Enter bit number 2:
0
Enter bit number 1:
1
Enter the size of the divisor:
4
Enter the divisor, bit by bit:
Enter bit number 4:
1
Enter bit number 3:
0
Enter bit number 2:
1
Enter bit number 1:
1
First data bit is: 1
Remainder: 0101
First data bit is: 0
Remainder: 1010
First data bit is: 1
Remainder: 0011
First data bit is: 0
Remainder: 0110
First data bit is: 0
Remainder: 1100
First data bit is: 1
Remainder: 1110

A B Prameela SVCT
44

First data bit is: 1


Remainder: 1010
101
The CRC code generated is: 1001101101
Enter the data to be sent:
Enter bit number 10:
1
Enter bit number 9:
0
Enter bit number 8:
0
Enter bit number 7:
1
Enter bit number 6:
1
Enter bit number 5:
0
Enter bit number 4:
1
Enter bit number 3:
1
Enter bit number 2:
0
Enter bit number 1:
1
1.) First data bit is: 1
Remainder: 0101
2.) First data bit is: 0
Remainder: 1010
3.) First data bit is: 1
Remainder: 0011
4.) First data bit is: 0
Remainder: 0111
5.) First data bit is: 0
Remainder: 1110
6.) First data bit is: 1
Remainder: 1011
7.) First data bit is: 1
Remainder: 0000
8.) First data bit is: 0
Remainder: 0000
9.) First data bit is: 0
Remainder: 0000
10.) First data bit is: 0
Remainder: 0000
Data was received without any error.

Result:

Thus, a program in Java was implemented to simulate Error Correction Code (CRC).

A B Prameela SVCT

You might also like