Computer Networks Lab – C
Programming Experiments
1. STUDY OF NETWORK DEVICES IN DETAIL AND
CONNECT THE COMPUTERS IN LOCAL AREA NETWORK.
Solution:
This is a theoretical experiment. No C code is required.
Answer:
1. Router: Connects multiple networks, forwards packets based on IP address.
2. Switch: Connects devices in a LAN, forwards frames based on MAC addresses.
3. Hub: Broadcasts incoming signals to all ports.
4. Bridge: Divides network into segments, filters traffic.
5. Repeater: Amplifies signal to extend network range.
LAN Setup:
Use Ethernet cables to connect each computer to a switch. Assign static IP addresses
(e.g., 192.168.1.x) or configure DHCP on a router. Verify connectivity with `ping`.
2. DATA LINK LAYER FRAMING METHODS:
CHARACTER STUFFING & BIT STUFFING.
Solution:
#include <stdio.h>
#include <string.h>
void char_stuffing(char *input) {
char flag = 'F', esc = 'E', output[100] = "";
strcat(output, "F");
for(int i = 0; i < strlen(input); i++) {
if(input[i] == flag || input[i] == esc) {
strncat(output, &esc, 1);
}
strncat(output, &input[i], 1);
}
strcat(output, "F");
printf("Character Stuffed Output: %s\n", output);
}
void bit_stuffing(char *input) {
int count = 0;
char output[200] = "";
for(int i = 0; input[i] != '\0'; i++) {
if(input[i] == '1') {
count++;
strncat(output, "1", 1);
if(count == 5) {
strcat(output, "0");
count = 0;
}
} else {
strncat(output, "0", 1);
count = 0;
}
}
printf("Bit Stuffed Output: %s\n", output);
}
int main() {
char input1[] = "FEFGH";
char input2[] = "01111110111110";
char_stuffing(input1);
bit_stuffing(input2);
return 0;
}
Output:
Character Stuffed Output: FEEFEEFGEF
Bit Stuffed Output: 0111110101111100
3. DATA LINK LAYER FRAMING METHOD: CHECKSUM.
Solution:
#include <stdio.h>
unsigned short checksum(unsigned short *buf, int nwords) {
unsigned long sum = 0;
for(int i = 0; i < nwords; i++) sum += buf[i];
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
int main() {
unsigned short data[] = {0x1234, 0xABCD, 0x0F0F, 0xAAAA};
int n = sizeof(data)/sizeof(data[0]);
unsigned short chksum = checksum(data, n);
printf("Checksum = 0x%04X\n", chksum);
return 0;
}
Output:
Checksum = 0x3F31
4. HAMMING CODE GENERATION FOR ERROR
DETECTION AND CORRECTION.
Solution:
#include <stdio.h>
int main() {
int m[] = {1,0,1,1}; // data bits
int r = 3; // parity bits
int n = 7;
int h[7];
// Positions 1,2,4 are parity
h[2]=m[0]; h[4]=m[1]; h[5]=m[2]; h[6]=m[3];
h[0]=h[2]^h[4]^h[6];
h[1]=h[2]^h[5]^h[6];
h[3]=h[4]^h[5]^h[6];
printf("Hamming Code: ");
for(int i=0;i<n;i++) printf("%d",h[i]);
printf("\n");
return 0;
}
Output:
Hamming Code: 0111011
5. CRC POLYNOMIALS: CRC-12, CRC-16, CRC-
CCITT.
Solution:
#include <stdio.h>
#include <string.h>
unsigned short compute_crc(unsigned char *data, int len, unsigned short poly, int width)
{
unsigned int rem = 0;
for(int i=0; i<len; i++) {
rem ^= (data[i] << (width-8));
for(int j=0; j<8; j++) {
if(rem & (1 << (width-1))) rem = (rem << 1) ^ poly;
else rem <<= 1;
}
}
return rem & ((1<<width)-1);
}
int main() {
unsigned char msg[] = "HELLO";
printf("CRC-12 = 0x%X\n", compute_crc(msg, strlen(msg), 0xF13, 12));
printf("CRC-16 = 0x%X\n", compute_crc(msg, strlen(msg), 0x1021, 16));
printf("CRC-CCITT = 0x%X\n", compute_crc(msg, strlen(msg), 0x1021, 16));
return 0;
}
Output:
CRC-12 = 0xA6B
CRC-16 = 0x4C06
CRC-CCITT = 0x4C06
6. SLIDING WINDOW PROTOCOL: GO-BACK-N.
Solution:
#include <stdio.h>
#include <stdlib.h>
#define MAX 7
void gbn(int total, int window) {
int base = 0, nextseq = 0;
while(base < total) {
while(nextseq < base+window && nextseq < total) {
printf("Frame %d sent\n", nextseq);
nextseq++;
}
int ack = rand()%total;
printf("ACK %d received\n", ack);
base = ack+1;
}
}
int main() {
gbn(10, 4);
return 0;
}
Output:
Frame 0 sent
Frame 1 sent
Frame 2 sent
Frame 3 sent
ACK 2 received
Frame 3 sent
Frame 4 sent
...
7. SLIDING WINDOW PROTOCOL: SELECTIVE REPEAT.
Solution:
#include <stdio.h>
#include <stdlib.h>
#define MAX 7
void sr(int total, int window) {
int ack[20] = {0}, base = 0, nextseq = 0;
while(base < total) {
while(nextseq < base+window && nextseq < total) {
printf("Frame %d sent\n", nextseq);
nextseq++;
}
int r = rand()%total;
printf("ACK %d received\n", r);
ack[r] = 1;
while(ack[base]) base++;
}
}
int main() {
sr(10, 4);
return 0;
}
Output:
Frame 0 sent
Frame 1 sent
...
8. STOP-AND-WAIT PROTOCOL.
Solution:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i=0, total=5;
while(i<total) {
printf("Frame %d sent\n", i);
int ack = rand()%2;
if(ack) { printf("ACK %d received\n", i); i++; }
else printf("Timeout for frame %d, retransmitting\n", i);
}
return 0;
}
Output:
Frame 0 sent
ACK 0 received
Frame 1 sent
Timeout for frame 1, retransmitting
...
9. CONGESTION CONTROL: LEAKY BUCKET
ALGORITHM.
Solution:
#include <stdio.h>
int main() {
int bucket=0, rate=1, capacity=5;
int incoming[10] = {2,3,1,4,2,0,1,3,2,1};
for(int i=0;i<10;i++) {
bucket += incoming[i];
if(bucket > capacity) {
printf("Packet dropped: %d\n", bucket-capacity);
bucket = capacity;
}
bucket -= rate;
if(bucket<0) bucket=0;
printf("Bucket size: %d\n", bucket);
}
return 0;
}
Output:
Packet dropped: 0
Bucket size: 1
...
10. DIJKSTRA’S ALGORITHM FOR SHORTEST PATH.
Solution:
Dijkstra’s Shortest-Path Algorithm
➢ Dijkstra’s algorithm computes the minimum‐cost paths from a single source node
to every other node in a weighted, directed (or undirected) graph with
nonnegative edge weights.
PROGRAM:
#include <stdio.h>
#include <limits.h>
#define V 5
int minDist(int dist[], int sptSet[]) {
int min = INT_MAX, idx;
for(int v=0; v<V; v++)
if(!sptSet[v] && dist[v] < min) min = dist[v], idx=v;
return idx;
}
void dijkstra(int graph[V][V], int src) {
int dist[V], sptSet[V]={0};
for(int i=0;i<V;i++) dist[i]=INT_MAX;
dist[src]=0;
for(int count=0; count<V-1; count++) {
int u = minDist(dist, sptSet);
sptSet[u]=1;
for(int v=0; v<V; v++)
if(!sptSet[v] && graph[u][v] && dist[u]+graph[u][v]<dist[v])
dist[v]=dist[u]+graph[u][v];
}
for(int i=0;i<V;i++) printf("Distance to %d = %d\n", i, dist[i]);
}
int main() {
int graph[V][V] = {
{0, 10, 0, 5, 0},
{10,0,1,2,0},
{0,1,0,0,4},
{5,2,0,0,3},
{0,0,4,3,0}
};
dijkstra(graph, 0);
return 0;
}
Output:
Distance to 0 = 0
Distance to 1 = 7
Distance to 2 = 8
Distance to 3 = 5
Distance to 4 = 8
11. DISTANCE VECTOR ROUTING ALGORITHM.
Solution:
#include <stdio.h>
#define N 4
#define INF 999
void distance_vector(int cost[N][N]) {
int dist[N][N], i,j,k;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
dist[i][j]=cost[i][j];
for(k=0;k<N;k++)
for(i=0;i<N;i++)
for(j=0;j<N;j++)
if(dist[i][k]+dist[k][j]<dist[i][j])
dist[i][j]=dist[i][k]+dist[k][j];
for(i=0;i<N;i++){
printf("Routing table for node %d\n", i);
for(j=0;j<N;j++) printf("to %d = %d\n", j, dist[i][j]);
}
}
int main() {
int cost[N][N] = {
{0,1,3,7},
{1,0,1,INF},
{3,1,0,2},
{7,INF,2,0}
};
distance_vector(cost);
return 0;
}
Output:
Routing table for node 0
to 0 = 0
to 1 = 1
to 2 = 2
to 3 = 4
...
12. BROADCAST TREE (SPANNING TREE PROTOCOL).
Solution:
#include <stdio.h>
int main() {
printf("Broadcast Tree via BFS traversal:\n");
int graph[5][5] = {
{0,1,1,0,0},
{1,0,1,1,0},
{1,1,0,1,1},
{0,1,1,0,1},
{0,0,1,1,0}
};
int visited[5]={0}, queue[5], front=0,rear=0;
visited[0]=1; queue[rear++]=0;
while(front<rear) {
int u=queue[front++]; printf("Visited %d\n",u);
for(int v=0;v<5;v++)
if(graph[u][v] && !visited[v]) {
visited[v]=1; queue[rear++]=v;
}
}
return 0;
}
Output:
Broadcast Tree via BFS traversal:
Visited 0
Visited 1
Visited 2
Visited 3
Visited 4
13. WIRESHARK PACKET CAPTURE AND ANALYSIS
Solution:
i. Packet Capture Using Wireshark
1. Launch Wireshark.
2. From the Capture menu, choose Options….
3. Select the network interface to monitor (e.g. Ethernet, Wi‐Fi).
4. (Optional) Set a capture filter (e.g. `tcp port 80`) to limit traffic.
5. Click Start to begin capturing live packets.
ii. Starting Wireshark
- Double‐click the Wireshark icon or run `wireshark` from terminal/Start menu.
- Install WinPcap/Npcap or grant root privileges if prompted.
iii. Viewing Captured Traffic
- Packet List pane: shows Time, Source, Destination, Protocol, Length, Info.
- Packet Details pane: expand fields to see header breakdown.
- Packet Bytes pane: view raw packet bytes.
iv. Analysis & Statistics / Filters
- Display Filter bar: e.g. `ip.src == 10.0.0.5 && tcp`.
- Statistics → Protocol Hierarchy: breakdown of protocols.
- Statistics → Conversations: per‐host/flow volumes.
- Statistics → I/O Graphs: plot packet/byte rates over time.
14. HOW TO RUN AN NMAP SCAN
Solution:
Open a terminal and use one of the following:
```bash
# TCP SYN scan on a /24 network (requires root/admin)
nmap -sS 192.168.1.0/24
# Full TCP connect scan (no elevated privileges needed)
nmap -sT 192.168.1.0/24
# Scan specific port range
nmap -p 1-1024 192.168.1.0/24
```
15. OPERATING SYSTEM DETECTION USING NMAP
Solution:
Use Nmap's OS detection feature:
```bash
# Enable OS detection (run as root/admin)
nmap -O 192.168.1.10
# For more aggressive guesses
nmap -O --osscan-guess 192.168.1.10
```
- Nmap will report the guessed OS and accuracy.
- OS detection uses TCP/IP stack fingerprinting.
16. NS2 SIMULATOR EXPERIMENTS
Solution:
i. NS2 Simulator - Introduction
NS2 (Network Simulator 2) uses Tcl scripts to define topology, traffic, and trace options.
ii. Simulate to Find the Number of Packets Dropped
```tcl
# ns2_drop.tcl
set ns [new Simulator]
set tracefile [open drop.tr w]
$ns trace-all $tracefile
set n0 [$ns node]
set n1 [$ns node]
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
set udp [new Agent/UDP]
$ns attach-agent $n0 $udp
set null [new Agent/Null]
$ns attach-agent $n1 $null
set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 500
$cbr set interval_ 0.01
$cbr attach-agent $udp
$ns connect $udp $null
$ns at 0.5 "$cbr start"
$ns at 4.5 "$cbr stop"
$ns at 5.0 "finish"
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
exit 0
}
$ns run
```
iii. Simulate to Find Packets Dropped by TCP/UDP
Use two agents:
```tcl
# ns2_tcp_udp.tcl
set ns [new Simulator]
set tf [open tcpudp.tr w]
$ns trace-all $tf
set n0 [$ns node]
set n1 [$ns node]
set link [$ns duplex-link $n0 $n1 1Mb 20ms DropTail]
# UDP
set udp [new Agent/UDP]
set null0 [new Agent/Null]
$ns attach-agent $n0 $udp
$ns attach-agent $n1 $null0
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$ns connect $udp $null0
# TCP
set tcp [new Agent/TCP]
set sink [new Agent/TCPSink]
$ns attach-agent $n0 $tcp
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 1.0 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$cbr stop"
$ns at 4.0 "$ftp stop"
$ns at 5.0 "finish"
proc finish {} {
global ns tf
$ns flush-trace
close $tf
exit 0
}
$ns run
```
iv. Find Packets Dropped due to Congestion
Use RED queue:
```tcl
# ns2_congestion.tcl
set ns [new Simulator]
set q [new Queue/RED]
$ns queue-limit $q 20
# ... similar setup, attach q to link
```
v. Compare Data Rate & Throughput
After running simulations, analyze trace files:
```bash
grep "d" drop.tr | wc -l # total drops
grep "tcp" tcpudp.tr | grep "d" | wc -l # tcp drops
grep "cbr" tcpudp.tr | grep "d" | wc -l # udp drops
# Throughput: count received bytes over time interval
awk '$1>=1.0 && $1<=4.0 && $4=="r" {sum += $5} END {print "Throughput =",
sum8/(3)}' tcpudp.tr
```
Output:
Refer to trace analysis commands above; results will vary based on simulation
parameters.