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

Rajat CN_LAB_FILE

This document is a practical lab file for a Computer Network course at Delhi Technological University, detailing various experiments related to networking protocols and algorithms. It includes tasks such as implementing data stuffing techniques, executing networking commands, and algorithms like Dijkstra's and Kruskal's for pathfinding and minimum spanning trees. Each experiment is accompanied by theoretical explanations and code implementations in C++.

Uploaded by

zerotwo02x02x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Rajat CN_LAB_FILE

This document is a practical lab file for a Computer Network course at Delhi Technological University, detailing various experiments related to networking protocols and algorithms. It includes tasks such as implementing data stuffing techniques, executing networking commands, and algorithms like Dijkstra's and Kruskal's for pathfinding and minimum spanning trees. Each experiment is accompanied by theoretical explanations and code implementations in C++.

Uploaded by

zerotwo02x02x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

CO - 306

COMPUTER NETWORK

PRACTICAL LAB FILE

DELHI TECHNOLOGICAL
UNIVERSITY
(FORMERLY Delhi College of Engineering)
Bawana Road, Delhi-110042

Submitted To: Submitted by:


RAJAT
PRASAD
2K22/CO/359
INDEX

S.No. Experiment Date


1. Write a program to implement
Character stuffing , Bit stuffing,Byte Stuffing

2. Execute the following networking command:


rp , ipconfig, hostname, netdiag,
netstart,nslookup,ping, pathping,route , tracert

3. Implement Cyclic Redundancy check.

4. Implement Dijkstra Algorithm

5. Implement Kruskal’s Algorithm

6. Write a program to implement a distance


vector algorithm

7. Implement link state routing algorithm

8. Write a program to simulate stop and wait


protocol

9. Write a program to simulate the sliding window


protocol

10. Write a program to Implement a client-server


architecture.
EXPERIMENT – 01

Aim : Write a program to implement Character stuffing , Bit stuffing , Byte Stuffing

Theory : These techniques are used in data link layer protocols to prevent
misinterpretation of data as control information.
• Character stuffing inserts special characters to distinguish data from
control flags.
• Bit stuffing adds a 0 after five consecutive 1s to prevent false flag
detection in bit- oriented protocols.
• Byte stuffing is similar to character stuffing but works with bytes,
commonly used in byte-oriented protocols like PPP.

Code Character Stuffing:

#include
<iostream> #include
<string> using
namespace std;

string characterStuffing(string data) {


string flag = "FLAG";
string esc = "ESC";
string stuffed = flag;

for (size_t i = 0; i < data.length(); i+ ) {


if (data.substr(i, flag.length()) = flag
| data.substr(i, esc.length()) =
esc) {
stuffed += esc;
}
stuffed += data[i];
}

stuffed += flag;
return stuffed;
}

int main() {
string data;
cout < "Enter the data: ";
cin > data;

string result = characterStuffing(data);


cout < "Character Stuffed Data: " < result < endl;
return 0;
}
Output:

Code Bit Stuffing :


#include
<iostream>
#include <string>
using namespace
std;

string bitStuffing(string data) {


string stuffed = "";
int count = 0;

for (char bit : data) {


if (bit = '1') {
count+ ;
stuffed +=
bit;
if (count = 5) {
stuffed += '0'; / insert 0 after
five 1s count = 0;
}
} else {
stuffed +=
bit; count = 0;
}
}

return stuffed;
}

int main() {
string data;
cout < "Enter the binary
data: "; cin > data;

string result = bitStuffing(data);


cout < "Bit Stuffed Data: " < result < endl;

return 0;
}
OUTPUT:
CODE Byte Stuffing
#include
<iostream>
#include <string>
using namespace
std;

string byteStuffing(string data)


{ string flag = "F";
string esc = "E";
string stuffed =
flag;

for (char ch : data) {


if (ch = 'F' | ch = 'E') {
stuffed += esc;/ escape the byte
}
stuffed += ch;
}

stuffed += flag;
return stuffed;
}

int main() {
string data;
cout < "Enter the data string (use capital
letters): "; cin > data;

string result = byteStuffing(data);


cout < "Byte Stuffed Data: " < result < endl;

return 0;
}
OUTPUT:
EXPERIMENT – 02
AIM: Execute the following networking command:
arp , ipconfig, hostname, netdiag, netstart, nslookup, pathping, ping,
route,tracert

Theory :

Comman Purpose
d

ipconfig Displays IP address, subnet mask, default gateway (Windows).

hostname Shows the system's hostname.

nslookup Queries DNS to get IP of a domain or vice versa.

ping Checks connectivity between source and destination.

tracert Traces the route (hops) packets take to reach a host


(Windows).
pathping Combines ping and tracert, showing packet loss at each hop.

route Displays/modifies the routing table.

netstat Displays active network connections, ports, and routing info.

netdiag Diagnoses network connectivity (used in older Windows


systems).
net start Lists running network services on Windows.

arp Shows or modifies the ARP cache (used to map IP to MAC


address).
CODE :
#include <iostream>
using namespace std;

void runCommand(const string& cmd) {


cout < "\n---- Output of: " < cmd < " \n";
system(cmd.c_str());
}

int main() {
cout < "Networking Commands Execution:\n";

runCommand("ipconfig");
runCommand("hostname");
runCommand("nslookup
google.com"); runCommand("ping
8.8.8.8"); runCommand("tracert
google.com");
runCommand("pathping
google.com"); runCommand("route
print"); runCommand("netstat");
runCommand("net start");
runCommand("arp -a");

return 0;
}

OUTPUT:

Networking Commands Execution:

---- Output of: ipconfig ----

Windows IP Configuration

Ethernet adapter Ethernet:

Media State . . . . . . . . . . . : Media


disconnected Connection-specific DNS Suffix
. : ccdtu.ac.in

Wireless LAN adapter Local Area Connection* 9:

Media State . . . . . . . . . . . : Media disconnected


Connection-specific DNS Suffix . :

Wireless LAN adapter Local Area Connection* 10:

Media State . . . . . . . . . . . : Media


disconnected Connection-specific DNS Suffix . :

Wireless LAN adapter Wi-Fi:

Connection-specific DNS Suffix

. :
IPv6 Address. . . . . . . . . . . : 2409:40d0:1039:8c93:fa4a:39a4:4953:2207
Temporary IPv6 Address. . . . . . :
2409:40d0:1039:8c93:dc3:bca6:a88:9891 Link-local IPv6 Address
. . . . . : fe80 9149:be89:f6e1:ce2d%18
IPv4 Address. . . . . . . . . . . : 192.168.124.216
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : fe80 20d7:f3ff:fe7a:1c7%18
192.168.124.46

---- Output of: hostname


---- DESKTOP-765ILPF

---- Output of: nslookup


google.com ---- Server: UnKnown
Address: 192.168.124.46

Non-authoritative answer:
Name: google.com
Addresses: 2404:6800:4002:80f
200e 142.250.193.14

---- Output of: ping 8.8.8.8 ----

Pinging 8.8.8.8 with 32 bytes of

data:
Reply from 8.8.8.8: bytes=32 time=31ms TTL=53
Reply from 8.8.8.8: bytes=32 time=33ms
TTL=53 Reply from 8.8.8.8: bytes=32
time=26ms TTL=53 Reply from 8.8.8.8:
bytes=32 time=53ms TTL=53

Ping statistics for 8.8.8.8:


Packets: Sent = 4, Received = 4, Lost = 0 (0%
loss), Approximate round trip times in milli-
seconds:
Minimum = 26ms, Maximum = 53ms, Average = 35ms

---- Output of: tracert google.com ----

Tracing route to google.com [2404:6800:4002:80f


200e] over a maximum of 30 hops:

1 2 ms 2 ms 2 ms 2409:40d0:1039:8c93 a0
2 34 ms 19 ms 14 ms 2405:200:5202:20:3924:0:
3:53
3 69 ms 14 ms 14 ms 2405:200:5202:20:3925
ff09
4 * * * Request timed out.
5 * * * Request timed out.
6 77 ms 37 ms 40 ms 2405:200:801:300 f54
7 * * * Request timed out.
EXPERIMENT – 03

AIM: Write a program to find the cyclic redundancy check for the given
data

Theory: Cyclic Redundancy Check (CRC) is an error-detecting


code used to identify changes to raw data during transmission or
storage. It’s widely used in networking protocols like Ethernet,
USB, and storage devices.

CODE:
#include <iostream>
#include <string>
using namespace std;

// XOR operation between two binary strings


string xorOperation(string a, string b) {
string result = "";
for (int i = 1; i < b.length(); i++) {
result += (a[i] == b[i]) ? '0' : '1';
}
return result;
}

// Modulo-2 Division
string mod2Division(string dividend, string divisor) {
int pick = divisor.length();
string temp = dividend.substr(0, pick);

while (pick < dividend.length()) {


if (temp[0] == '1') {
temp = xorOperation(divisor, temp) + dividend[pick];
} else {
temp = xorOperation(string(pick, '0'), temp) + dividend[pick];
}
pick++;
}

// Final step
if (temp[0] == '1') {
temp = xorOperation(divisor, temp);
} else {
temp = xorOperation(string(pick, '0'), temp);
}

return temp;
}

// Encode the data with CRC


string encodeData(string data, string key) {
int keyLen = key.length();
string appendedData = data + string(keyLen - 1, '0');
string remainder = mod2Division(appendedData, key);
string codeword = data + remainder;

cout << "\nOriginal Data: " << data;


cout << "\nDivisor (Key): " << key;
cout << "\nRemainder (CRC): " << remainder;
cout << "\nTransmitted Codeword: " << codeword << endl;

return codeword;
}

int main() {
string data, key;
cout << "Enter binary data: ";
cin >> data;

cout << "Enter generator polynomial (binary): ";


cin >> key;

string transmitted = encodeData(data, key);

// Check for error at receiver


string checkRemainder = mod2Division(transmitted, key);
if (checkRemainder.find('1') != string::npos) {
cout << "\nError detected during transmission.\n";
} else {
cout << "\nNo error detected. Data is received correctly.\n";
}

return 0;
}

Output:
EXPERIMENT – 04

AIM : Write a program to implement the shortest path algorithm.


(Dijkstra’s Algorithm)

Theory:
• Purpose: Dijkstra's algorithm is used to find the shortest path from
a single source vertex to all other vertices in a weighted graph with
non-negative edge weights.
• Mechanism: It works by maintaining a set of visited nodes and
iteratively selecting the unvisited node with the smallest tentative
distance, updating the distances to its neighbors.
• Time Complexity: The algorithm has a time complexity of O(V^2) with a
simple implementation or O((V + E) log V) using a priority queue,
where V is the number of vertices and E is the number of edges.
• Application: It is widely used in network routing protocols and GPS
navigation systems to determine the most efficient paths.

CODE:

#include
<iostream>
#include <vector>
#include <climits>
using namespace
std;

const int INF = INT_MAX;

int minDistance(vector<int>& dist, vector<bool>& visited, int V) {


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

void dijkstra(const vector<vector<int> & graph, int src, int


V) { vector<int> dist(V, INF);
vector<bool> visited(V, false);
dist[src] = 0;

for (int count = 0; count < V - 1;


count+ ) { int u =
minDistance(dist, visited, V); if (u
= -1) break;
for (int v = 0; v < V; v+ ) {
if (!visited[v] & graph[u][v] &
dist[u] 2 INF & dist[u]
+ graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

cout < "\nVertex \t Distance from Source\n";


for (int i = 0; i < V; i+ )
cout < i < " \t\t " < dist[i] < endl;
}

int main() {
int V, E;
cout < "Enter number of
vertices: "; cin > V;
cout < "Enter number of
edges: "; cin > E;

/ Initialize adjacency matrix


vector<vector<int> graph(V,
vector<int>(V, 0));

cout < "Enter edges as: source destination weight\n";


for (int i = 0; i < E; i+ ) {
int u, v, w;
cin > u > v >
w; graph[u]
[v] = w;
graph[v][u] = w; / Remove this line for directed graph
}

int source;
cout < "Enter the source vertex:
"; cin >source;

dijkstra(graph, source, V);


return 0;
OUTPUT:
EXPERIMENT – 05

AIM: Write a program to implement Kruskal’s Algorithm.

Theory:
• Purpose: Kruskal's algorithm is used to find the minimum
spanning tree (MST) of a connected, undirected, and weighted
graph, ensuring the total edge weight is minimized.
• Mechanism: It works by sorting all edges by weight in ascending order
and greedily adding the smallest edge that does not create a cycle, using
a disjoint-set data structure to track connected components.
• Time Complexity: The algorithm has a time complexity of O(E log E) or
O(E log V) with an efficient union-find data structure, where E is the
number of edges and V is the number of vertices.
• Application: It is commonly applied in network design, such as
laying cables or building roads, to minimize costs.

CODE:
#include
<iostream>
#include
<vector>
#include
<algorithm>
using namespace
std;

struct Edge {
int u, v, weight;
};

bool compare(Edge a, Edge b)


{ return a.weight <
b.weight;
}

/ Disjoint Set (Union-Find)


implementation vector<int> parent,
dsuRank;

int find(int x) {
if (parent[x] 2 x)
parent[x] = find(parent[x]); / Path
compression return parent[x];
}

void unionSet(int x, int


y) { int xRoot =
find(x);
parent[yRoot] =
xRoot; else {
parent[yRoot] = xRoot;
dsuRank[xRoot]+ ;
}
}

void kruskal(int V, vector<Edge>& edges)


{ sort(edges.begin(), edges.end(),
compare);

parent.resize(V);
dsuRank.resize(V, 0);
for (int i = 0; i < V;
i+ ) parent[i] = i;

vector<Edge>
mst; int
totalWeight = 0;

for (Edge e : edges) {


if (find(e.u) 2 find(e.v))
{ mst.push_back(e);
totalWeight +=
e.weight;
unionSet(e.u, e.v);
}
}

cout < "\nEdges in Minimum Spanning


Tree:\n"; for (Edge e : mst)
cout < e.u < " - " < e.v < " weight: " < e.weight
< endl;

cout < "Total weight of MST: " < totalWeight < endl;
}

int main() {
int V, E;
cout < "Enter number of
vertices: "; cin > V;
cout < "Enter number of
edges: "; cin > E;

vector<Edge> edges(E);
cout < "Enter edges as: source
destination weight\n"; for (int i = 0; i < E;
i+ ) {
cin > edges[i].u > edges[i].v >
edges[i].weight;
}

kruskal(V, edges);
return 0;
}
OUTPUT:
EXPERIMENT – 06

AIM: Write a program to implement a distance vector algorithm.

Theory: The Distance Vector Routing Algorithm is used to calculate the


shortest path between routers in a network. Each router maintains a table
(vector) that lists the minimum distance to all other routers and periodically
shares this table with its neighbors.

🔹 Working Principle:
• Based on the Bellman-Ford Algorithm.
• Routers exchange distance vectors with neighbors.
• They update their tables if a shorter route is discovered.

CODE:

#include <iostream>
using namespace std;

const int INF = 999;

int main() {
int n;
cout < "Enter number of routers:
"; cin > n;

int cost[n][n], dist[n][n], nextHop[n][n];

/ Input cost matrix


cout < "Enter cost matrix (use 999 for INF):\n";
for (int i = 0; i < n; i+ ) {
for (int j = 0; j < n; j+ )
{ cin > cost[i][j];
dist[i][j] = cost[i][j];
if (cost[i][j] 2 INF & i 2 j)
nextHop[i][j] = j;
else
nextHop[i][j] = -1;
}
}

/ Distance vector update (like Bellman-Ford)


for (int k = 0; k < n; k+ ) {
for (int i = 0; i < n; i+ ) {
for (int j = 0; j < n; j+ ) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
nextHop[i][j] = nextHop[i][k];
}
}
}
}

/ Print final routing tables


for (int i = 0; i < n; i+ ) {
cout < "\nRouting table for Router " < i <
":\n"; cout <
"Destination\tNext Hop\tDistance\n";
for (int j = 0; j < n; j+ ) {
if (i 2 j) {
cout < j < "\t\t";
if (nextHop[i][j] =
-1) cout
< "-";
else
cout < nextHop[i][j];
cout < "\t\t" < dist[i][j] < "\n";
}
}
}

return 0;
}

OUTPUT
EXPERIMENT-07

AIM: Write a program to implement the Link State Routing Algorithm.


Theory: Link State Routing (LSR) is a routing protocol in which routers
build a complete topological map of the network by gathering information
about the status (state) of their links to neighbors.
🔹 How It Works:
1. Each router discovers its neighbors and measures the cost to each.
2. Routers broadcast link-state packets (LSPs) to all other routers.
3. All routers receive all LSPs and use Dijkstra’s algorithm to compute
the shortest paths.
4. Every router ends up with the same network map.
🔹 Key Characteristics:
• Uses Dijkstra's algorithm.
• Fast convergence.
• Less prone to routing loops.
• More memory-intensive than Distance Vector.

CODE:

#include
<iostream>
#include <vector>
#include
<climits> using
namespace std;

void dijkstra(vector<vector<int> &graph, int src) {


int V = graph.size();
vector<int> dist(V,
INT_MAX); vector<bool>
visited(V, false);

dist[src] = 0;

for (int count = 0; count < V - 1; count+ ) {


int u = -1, minDist = INT_MAX;

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


if (!visited[i] & dist[i] <
}
}

visited[u] = true;

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


if (!visited[v] & graph[u][v] &dist[u] 2 INT_MAX
& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

/ Output routing table


cout < "\nRouting Table for Router " < src
< ":\n"; cout <
"Destination\tCost\n";
for (int i = 0; i < V; i+ ) {
if (i 2 src)
cout < i < "\t\t" < dist[i] < "\n";
}
}

int main() {
int V;
cout < "Enter number of
routers: "; cin > V;

vector<vector<int> graph(V, vector<int>(V));


cout < "Enter the cost adjacency matrix (0 for same
router, 999 for no connection):\n";

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


for (int j = 0; j < V;
j+ ) { cin > graph[i]
[j];
if (graph[i][j] = 999)
graph[i][j] = 0; / Treat 999 as no direct edge
}
}

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


dijkstra(graph, i);
}

return 0;
}
OUTPUT:
EXPERIMENT – 08
AIM: Write a program to simulate stop and wait protocol
Theory: The Stop and Wait Protocol is a simple flow control protocol
used in data communication. It ensures reliable transmission by sending
one frame at a time and waiting for an acknowledgment (ACK) before
sending the next.
🔹 Working:
1. Sender transmits one frame.
2. Waits for ACK from receiver.
3. If ACK is received → send next frame.
4. If no ACK (timeout) → resend the same frame.
It prevents frame loss or errors and maintains a one-at-a-time
transmission, making it simple but slower for long-distance or high-
speed networks.

CODE:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <unistd.h> / for sleep()
using namespace std;

void sender(int frames) {


for (int i = 0; i < frames; i+ ) {
cout < "\nSending Frame " < i < ".
\n"; sleep(1); / Simulate
delay

/ Simulate whether ACK is received or not

if (ack)
{ "ACK received for Frame i < "\
cout < " < n";
} else "ACK lost! Resending i " \
{ Frame " < < . n";
cout Resend same frame
} < i-
cout < "\nAll frames sent successfully!\
n";
}

int main() {
srand(time(0));
int n;
cout < "Enter number of frames to
send: "; cin > n;

sender(n);
return 0;
}

OUTPUT:
EXPERIMENT- 09
AIM: Write a program to simulate the sliding window protocol
Theory: The Sliding Window Protocol is an efficient method of flow
control used in data communication systems. Unlike Stop-and-Wait, it
allows multiple frames to be sent before needing an ACK, improving
bandwidth utilization.
🔹 Key Concepts:
• Window Size (N): Number of frames that can be sent without waiting
for ACK.
• Sender Window: Slides forward as ACKs are received.

• Receiver Window: Accepts frames within a specific range.

CODE:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <unistd.h> / For sleep()
using namespace std;

void slidingWindow(int totalFrames, int windowSize) {


int sentUpto = 0;
while (sentUpto <
totalFrames) { cout < "\
nSending frames: ";
for (int i = 0; i < windowSize &
sentUpto +
i < totalFrames; i+ ) {
cout < sentUpto + i < " ";
}
cout < "\n";
sleep(1); / simulate delay

/ Simulate ACK for a random number of frames


int ack = rand() % (windowSize + 1); / could
be 0 to windowSize
if (ack =0) {
cout < "No ACK received! Resending from
frame " < sentUpto < ". \n";
} else {
cout < "ACK received for frames upto " <
sentUpto + ack - 1 < "\n";
sentUpto += ack;
}
}
cout < "\nAll frames sent successfully using sliding
window protocol!\n";
}

int main() {
srand(time(0));
int totalFrames, windowSize;

cout < "Enter total number of frames to send:


"; cin > totalFrames;

cout < "Enter window


size: "; cin >
windowSize;

slidingWindow(totalFrames, windowSize);
return 0;
}

OUTPUT:
EXPERIMENT – 10
AIM: Write a program to implement a client-server architecture.
Theory: Client-Server Architecture is a network model where:
• The server provides services/resources.
• The client requests services from the server.
This architecture is widely used in networking for web services, database access,
etc.
🔹 Key Features:
• Client initiates communication.
• Server waits for incoming connections.
• Based on sockets, using protocols like TCP/IP.
• Common in chat apps, file transfers, websites, etc.

CODE:
server.cpp

#include <iostream>
#include <cstring>
#include <unistd.h>
#include
<sys/socket.h>
#include
<netinet/in.h> #define
PORT 8080

using namespace std;

int main() {
int server_fd,
new_socket; char
buffer[1024] = {0};
struct sockaddr_in
address; int opt = 1;
int addrlen = sizeof(address);

/ Create socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd = 0) {
perror("Socket
failed");
exit(EXIT_FAILURE);
}
/ Bind address and port
address.sin_family = AF_INET;
address.sin_addr.s_addr =
INADDR_ANY; address.sin_port =
htons(PORT);

bind(server_fd, (struct sockaddr * &address,


sizeof(address));

/ Listen for
connections
listen(server_fd, 3);
cout < "Server listening on port " < PORT < ". \
n";

/ Accept client
new_socket = accept(server_fd, (struct sockaddr *
&address, (socklen_t* &addrlen);

/ Read data from client


read(new_socket, buffer,
1024);
cout < "Message from client: " < buffer < endl;

/ Send reply
const char *msg = "Hello from server!";
send(new_socket, msg, strlen(msg), 0);

close(server_fd);

Client.cpp

#include <iostream>
#include <unistd.h>
#include
<sys/socket.h>
#include
<arpa/inet.h>
#include <cstring>
#define PORT 8080

using namespace std;

int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
/ Create socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
cout < "Socket creation error\n";
return -1;
}

serv_addr.sin_family =
AF_INET; serv_addr.sin_port =
htons(PORT);

/ Convert IPv4 address


inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);

/ Connect to server
connect(sock, (struct sockaddr * &serv_addr,
sizeof(serv_addr));

/ Send message
const char *hello = "Hello from
client!"; send(sock, hello,
strlen(hello), 0);

/ Receive reply
read(sock, buffer,
1024);
cout < "Message from server: " < buffer < endl;

close(sock);
return 0;

OUTPUT:

You might also like