CNS Lab Manual
CNS Lab Manual
CNS Lab Manual
#include <stdio.h>
void generateHammingCode(int data[], int m, int r) {
int hammingCode[m + r];
int i, j, parityBitPosition = 0;
int main() {
int m, r;
// Input data
int data[m];
printf("Enter data (bit by bit): ");
for (int i = 0; i < m; i++) {
scanf("%d", &data[i]);
}
// Generate and display Hamming Code
generateHammingCode(data, m, r);
return 0;
}
OUTPUT :
Enter data size (m): 4
Enter number of redundant bits (r): 3
Enter data (bit by bit): 1 0 1 1
Hamming Code: 1 0 1 1 0 1 1 1
6. Implementation of Stop and Wait Protocol and sliding window
Stop-and-Wait Protocol:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define FRAME_SIZE 4
int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4};
// Simulate Stop-and-Wait protocol
stopAndWait(frames, FRAME_SIZE);
return 0;
}
Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
Acknowledge 1
2 -
Transmission...
- 2
Processing...
Acknowledge 2
3 -
Transmission...
NAK received, Resending 3
3 -
Transmission...
- 3
Processing...
Acknowledge 3
4 -
Transmission...
- 4
Processing...
Acknowledge 4
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WINDOW_SIZE 3
int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4};
4 -
Transmission...
- 4
Processing...
Acknowledge 4
7. Implementation and study of Goback-N and selective repeat protocols
Go-Back-N Protocol:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define WINDOW_SIZE 3
#define FRAME_SIZE 5
// Acknowledge receipt
printf("Acknowledge %d\n", receiverIndex);
} else {
printf("NAK received, Resending frames\n");
senderIndex = receiverIndex; // Go back to the first unacknowledged frame
}
printf("\n");
}
}
int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4, 5};
// Simulate Go-Back-N protocol
goBackN(frames, FRAME_SIZE);
return 0;
}
Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
2 -
Transmission...
- 2
Processing...
3 -
Transmission...
- 3
Processing...
Acknowledge 3
4 -
Transmission...
- 4
Processing...
Acknowledge 4
5 -
Transmission...
- 5
Processing...
Acknowledge 5
// Receive frames
for (int i = 0; i < WINDOW_SIZE && receiverIndex < frameCount; i++) {
if (acknowledge[i]) {
printf("-\t%d\n", frames[receiverIndex]);
receiverIndex++;
int main() {
int frames[FRAME_SIZE] = {1, 2, 3, 4, 5};
// Simulate Selective Repeat protocol
selectiveRepeat(frames, FRAME_SIZE);
return 0;
}
Output :
Sender Receiver
1 -
Transmission...
- 1
Processing...
2 -
Transmission...
- 2
Processing...
3 -
Transmission...
- 3
Processing...
Acknowledge Status: 1 1 1
4 -
Transmission...
- 4
Processing...
Acknowledge Status: 0 1 1
NAK received for frame 4, Resending frame 4
4 -
Transmission...
- 4
Processing...
Acknowledge Status: 1 1 1
5 -
Transmission...
- 5
Processing...
Acknowledge Status: 0 0 1
NAK received for frame 5, Resending frame 5
5 -
Transmission...
- 5
Processing...
Acknowledge Status: 1 1 1
8. Implementation of High Level Data Link Control
#include <stdio.h>
#include <string.h>
// HDLC Frame structure
struct HDLCFrame {
char delimiter;
char data[100];
short fcs; // Frame Check Sequence (Checksum)
};
// Calculate FCS
frame.fcs = calculateFCS(data);
int main() {
const char *dataToSend = "Hello, HDLC!";
Output:
Sent HDLC Frame:
Delimiter: 0x7E
Data: Hello, HDLC!
FCS: 0x67DA
#include <stdio.h>
#include <limits.h>
#define MAX_NODES 10
// Function to find the next node to visit based on the current costs
int findNextNode(struct Node *node, int nodeCount) {
int minCost = INT_MAX;
int nextNode = -1;
return nextNode;
}
int main() {
int nodeCount;
printf("Enter the number of nodes: ");
scanf("%d", &nodeCount);
return 0;
}
OUTPUT :
Enter the number of nodes: 3
Enter cost from Node 0 to Node 1 (or -1 if no direct link): 2
Enter cost from Node 0 to Node 2 (or -1 if no direct link): -1
Enter cost from Node 1 to Node 0 (or -1 if no direct link): 2
Enter cost from Node 1 to Node 2 (or -1 if no direct link): 1
Enter cost from Node 2 to Node 0 (or -1 if no direct link): -1
Enter cost from Node 2 to Node 1 (or -1 if no direct link): 1
1. Character Stuffing:
#include<stdio.h>
#include<string.h>
void main()
{
char a[30], fs[50] = " ", t[3], sd, ed, x[3], s[3], d[3], y[3];
int i, j, p = 0, q = 0;
clrscr();
printf("Enter characters to be stuffed:");
scanf("%s", a);
printf("\nEnter a character that represents starting delimiter:");
scanf(" %c", &sd);
printf("\nEnter a character that represents ending delimiter:");
scanf(" %c", &ed);
x[0] = s[0] = s[1] = sd;
x[1] = s[2] = '\0';
y[0] = d[0] = d[1] = ed;
d[2] = y[1] = '\0';
strcat(fs, x);
for(i = 0; i < strlen(a); i++)
{
t[0] = a[i];
t[1] = '\0';
if(t[0] == sd)
strcat(fs, s);
else if(t[0] == ed)
strcat(fs, d);
else
strcat(fs, t);
}
strcat(fs, y);
printf("\n After stuffing:%s", fs);
getch();
}
Output:-
Enter characters to be stuffed: goodday
Enter a character that represents starting delimiter: d
Enter a character that represents ending delimiter: g
After stuffing: dggooddddayg.
2. Bit Stuffing:
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1; a[k]==1 && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else b[j]=a[i];
i++;
j++;
}
printf("After Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}
OUTPUT for BIT STUFFING:
Enter frame size (Example: 8):12
Enter the frame in the form of 0 and 1 :0 1 0 1 1 1 1 1 1 0 0 1
After Bit Stuffing :0101111101001
11. Write a program to compute CRC code for the polynomials CRC-12,
CRC-16 and CRC CCIP
#include<stdio.h>
#include<string.h>
#define N strlen(g)
char t[28],cs[28],g[]="10001000000100001";
int a,i,j;
void xor()
{
for(j = 1;j < N; j++)
cs[j] = (( cs[j] == g[j])?'0':'1');
}
void crc()
{
for(i=0;i<N;i++)
cs[i]=t[i];
do
{
if(cs[0]=='1')
xor();
for(j=0;j<N-1;j++)
cs[j]=cs[j+1];
cs[j]=t[i++];
}while(i<=a+N-1);
}
int main()
{
printf("\nEnter data : ");
scanf("%s",t);
printf("\n----------------------------------------");
printf("\nGeneratng polynomial : %s",g);
a=strlen(t);
for(i=a;i<a+N-1;i++)
t[i]='0';
printf("\n----------------------------------------");
printf("\nModified data is : %s",t);
printf("\n----------------------------------------");
crc();
printf("\nChecksum is : %s",cs);
for(i=a;i<a+N-1;i++)
t[i]=cs[i-a];
printf("\n----------------------------------------");
printf("\nFinal codeword is : %s",t);
printf("\n----------------------------------------");
printf("\nEnter received message ");
scanf("%s",t);
crc();
for(i=0;(i<N-1) && (cs[i]!='1');i++);
if(i<N-1)
printf("\nError detected\n\n");
else
printf("\nNo error detected\n\n");
printf("\n----------------------------------------\n");
return 0;
}
12. Develop a simple data link layer that performs the flow control using the
sliding window protocol and loss recovery using the Go-Back-N mechanism.
import time
import random
class Frame:
def __init__(self, seq_num, data):
self.seq_num = seq_num
self.data = data
class SimpleDataLinkLayer:
def __init__(self, window_size):
self.window_size = window_size
self.frames = []
self.expected_seq_num = 0
self.sent_seq_num = 0
def simulate_network(self):
while True:
if random.random() < 0.8: # Simulating 80% success rate
if random.random() < 0.2: # Simulating 20% packet loss
print("Packet lost.")
else:
if self.frames:
ack_frame = Frame(self.expected_seq_num - 1, None)
print(f"Sending ACK {ack_frame.seq_num}")
else:
ack_frame = Frame(self.expected_seq_num, None)
print(f"Sending ACK {ack_frame.seq_num}")
time.sleep(1) # Simulating network delay
self.receive_frame(ack_frame)
else:
print("Network error. Retransmitting...")
time.sleep(1) # Simulating network delay
def main():
data_link_layer = SimpleDataLinkLayer(window_size=3)
for i in range(10):
data_link_layer.send_frame(f"Data{i}")
data_link_layer.simulate_network()
if __name__ == "__main__":
main()
OUTPUT :
Sending Frame 0
Sending Frame 1
Sending Frame 2
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Window is full. Waiting for ACKs...
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Sending ACK -1
Received out-of-order frame -1. Discarding.
Network error. Retransmitting...
Network error. Retransmitting...
13. Implement Dijsktra‘s algorithm to compute the shortest path through a
network
#include<stdio.h>
void main()
{
int path[5][5],i,j,min,a[5][5],p,st=1,ed=5,stp,edp,t[5],index;
clrscr();
printf("enter the costmatrix\n");
for(i=1;i<=5;i++)
for(j=1;j<=5;j++)
scanf("%d",&a[i][j]);
printf("enter the paths\n");
scanf("%d",&p);
printf("enter possible paths\n");
for(i=1;i<=p;i++)
for(j=1;j<=5;j++)
scanf("%d",&path[i][j]);
for(i=1;i<=p;i++)
{
t[i]=0;
stp=st;
for(j=1;j<=5;j++)
{
edp=path[i][j+1];
t[i]=t[i]+a[stp][edp];
if(edp==ed) break;
else stp=edp;
}
}
min=t[st];
index=st;
for(i=1;i<=p;i++)
{
if(min>t[i])
{
min=t[i];
index=i;
}
}
printf("minimum costd",min);
printf("\n minimum cost path ");
for(i=1;i<=5;i++)
{
printf("-->%d",path[index][i]);
if(path[index][i]==ed)
break;
}
getch();
}
OUTPUT :
14. Take an example subnet of hosts and obtain a broadcast tree for the
subnet.
#include <stdio.h>
#include <limits.h>
#define MAX_NODES 10
// Pick the minimum distance vertex from the set of vertices not yet processed
for (int v = 0; v < num_nodes; v++) {
if (!visited[v] && distance[v] <= min_distance) {
min_distance = distance[v];
min_index = v;
}
}
visited[min_index] = 1;
// Update the distance value of the neighboring vertices of the picked vertex
for (int v = 0; v < num_nodes; v++) {
if (!visited[v] && graph[min_index][v] && distance[min_index] != INT_MAX &&
distance[min_index] + graph[min_index][v] < distance[v]) {
distance[v] = distance[min_index] + graph[min_index][v];
}
}
}
printf("Broadcast Tree for Subnet:\n");
printf("Node\tDistance from Source\n");
for (int i = 0; i < num_nodes; i++) {
printf("%d\t\t\t%d\n", i, distance[i]);
}
}
int main() {
// Example subnet with distances between nodes
int graph[MAX_NODES][MAX_NODES] = {
{0, 2, 0, 4, 0},
{2, 0, 3, 0, 0},
{0, 3, 0, 1, 4},
{4, 0, 1, 0, 2},
{0, 0, 4, 2, 0}
};
int num_nodes = 5;
int source = 0;
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int costmat[20][20];
int nodes,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&nodes);//Enter the nodes
printf("\nEnter the cost matrix :\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];
rt[i].from[j]=j;
}
}
do{
count=0;
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\n For router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d ",
j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
getch();
}
Output:
Enter the number of nodes :
3
Enter the cost matrix :
027
201
710
For router 1
node 1 via 1 Distance 0
node 2 via 2 Distance 2
node 3 via 3 Distance 3
For router 2
node 1 via 1 Distance 2
node 2 via 2 Distance 0
node 3 via 3 Distance 1
For router 3
node 1 via 1 Distance 3
node 2 via 2 Distance 1
node 3 via 3 Distance 0
16. Write a program for congestion control using Leaky bucket algorithm
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX 5
#define LEAK_RATE 1
OUTPUT :
Iteration 1:
Incoming packets: 7
Bucket overflow! Dropping excess packets.
Packets sent: 1
Remaining packets in the bucket: 4
Iteration 2:
Incoming packets: 3
Packets sent: 1
Remaining packets in the bucket: 3
Iteration 3:
Incoming packets: 2
Packets sent: 1
Remaining packets in the bucket: 2
17. Do the following using NS2 Simulator
a. NS2 Simulator - Introduction:
NS2, or Network Simulator 2, is a widely used open-source network simulation tool that
facilitates the study and analysis of various networking protocols and scenarios. Developed in
C++ and OTCL (Object-oriented Tool Command Language), NS2 enables researchers,
engineers, and students to simulate and emulate the behaviour of complex networks, both
wired and wireless. With its modular architecture, NS2 supports the integration of custom
protocols and algorithms, making it a versatile platform for testing and validating new
networking concepts. The simulator provides components such as nodes, links, agents, and
applications that can be configured through TCL scripts. NS2's event-driven simulation
model allows users to define and observe discrete events over time, enabling the analysis of
network performance under different conditions. Visualization tools within NS2 aid in
understanding the dynamics of network protocols, making it an indispensable tool in the field
of computer networking research and education.
b. Simulate to Find the Number of Packets Dropped using Python:
Assuming you have an NS2 simulation script that generates a trace file (e.g., `.tr` file), you
can use Python to analyze this file and find the number of dropped packets. For simplicity,
let's assume the trace file contains lines with information about each packet transmission and
reception.
Python Analysis Script (analyze.py):
def analyze_trace_file(trace_file_path):
dropped_packets = 0
if __name__ == "__main__":
trace_file_path = "output.tr" # Replace with your actual trace file path
dropped_packets = analyze_trace_file(trace_file_path)
print(f"Number of Dropped Packets: {dropped_packets}")
c. Simulate to Find the Number of Packets Dropped by TCP/UDP using Python:
You can extend the Python script to differentiate between TCP and UDP packets by
modifying the conditions within the analysis loop. Adjust the script according to the specifics
of your NS2 simulation output.
Sample Modification for TCP/UDP Differentiation:
def analyze_trace_file(trace_file_path):
dropped_tcp_packets = 0
dropped_udp_packets = 0
if __name__ == "__main__":
trace_file_path = "output.tr" # Replace with your actual trace file path
dropped_tcp, dropped_udp = analyze_trace_file(trace_file_path)
print(f"Number of Dropped TCP Packets: {dropped_tcp}")
print(f"Number of Dropped UDP Packets: {dropped_udp}")
def send_packet(self):
# Simulate packet arrival
new_packet = random.randint(1, 10)
if len(self.buffer) < self.buffer_size:
self.buffer.append(new_packet)
print(f"Packet {new_packet} sent successfully.")
else:
print(f"Packet {new_packet} dropped due to congestion.")
self.dropped_packets += 1
# Example usage
buffer_size = 5
num_packets_to_send = 20
network = Network(buffer_size)
network.simulate_network(num_packets_to_send)
e. Simulate to Compare Data Rate& Throughput.
import time
class DataTransferSimulation:
def __init__(self, data_rate_1, data_rate_2):
self.data_rate_1 = data_rate_1 # Data rate for scenario 1 (in Mbps)
self.data_rate_2 = data_rate_2 # Data rate for scenario 2 (in Mbps)
start_time = time.time()
end_time = start_time + duration
# Example usage
data_rate_scenario_1 = 10 # Mbps
data_rate_scenario_2 = 5 # Mbps
simulation_duration = 5 # seconds
class NetworkSimulation:
def __init__(self, num_sources, num_destinations):
self.num_sources = num_sources
self.num_destinations = num_destinations
self.congestion_data = np.zeros((num_sources, num_destinations))
def plot_congestion(self):
plt.imshow(self.congestion_data, cmap='viridis', interpolation='nearest')
plt.colorbar(label='Congestion Count')
plt.xlabel('Destination')
plt.ylabel('Source')
plt.title('Congestion Simulation')
plt.show()
# Example usage
num_sources = 5
num_destinations = 5
num_iterations = 100
import simpy
import random
class Packet:
def __init__(self, id, size):
self.id = id
self.size = size
# Simulation parameters
num_packets = 10
packet_size = 100 # in bits
transmission_rate = 1000 # in bits per second
env = simpy.Environment()
channel = simpy.Resource(env, capacity=1)
env.process(packet_generator(env, num_packets, packet_size, transmission_rate, channel))
env.run()
h. To create scenario and study the performance of network with CSMA/CA protocol
and CSMA/CD protocols
import simpy
import random
class Node:
def __init__(self, env, name, channel):
self.env = env
self.name = name
self.channel = channel
def transmit_packet(self):
print(f"{self.name} is attempting to transmit a packet.")
with self.channel.request() as req:
yield req
print(f"{self.name} is transmitting a packet.")
yield self.env.timeout(random.uniform(0.1, 0.5))
print(f"{self.name} finished transmitting.")
env = simpy.Environment()
env.process(simulate_csma_ca(env, num_nodes=3))
env.run()
18. Implement the following executing protocols of Internet in action using
Wireshark Lab.
a. Packet Capture and Observations using Packet Sniffer.
def packet_callback(packet):
# Process the packet here
print(packet.show())
import http.client
conn = http.client.HTTPSConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
conn.close()
def trace_dns(domain):
answers = dns.resolver.query(domain, 'A')
for answer in answers:
print(f"IP Address for {domain}: {answer.address}")
# Example usage
trace_dns("www.example.com")
d. Analysis and Obtain various parameters-Values for TCP Protocol in action
from scapy.all import sniff, TCP
def tcp_packet_callback(packet):
if packet.haslayer(TCP):
# Process TCP packet
tcp_flags = packet[TCP].flags
src_port = packet[TCP].sport
dest_port = packet[TCP].dport
print(f"TCP Packet - Source Port: {src_port}, Destination Port: {dest_port}, Flags:
{tcp_flags}")
def start_echo_server():
host = '127.0.0.1'
port = 12345
if __name__ == "__main__":
start_echo_server()
def start_echo_client():
host = '127.0.0.1'
port = 12345
def start_ping_server():
host = '127.0.0.1'
port = 12346
if __name__ == "__main__":
start_ping_server()
import socket
def start_ping_client():
host = '127.0.0.1'
port = 12346
if __name__ == "__main__":
start_ping_client()
client_socket.close()
def start_chat_server():
host = '127.0.0.1'
port = 12347
while True:
client_socket, address = server_socket.accept()
print(f"Accepted connection from {address}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,
address))
client_handler.start()
if __name__ == "__main__":
start_chat_server()
def start_chat_client():
host = '127.0.0.1'
port = 12347
while True:
message = input("Enter message to send to the server (or 'exit' to quit): ")
if message.lower() == 'exit':
break
client_socket.sendall(message.encode())
if __name__ == "__main__":
start_chat_client()
import socket
def start_dns_server():
host = '127.0.0.1'
port = 53 # DNS standard port
while True:
data, client_address = server_socket.recvfrom(1024)
print(f"Received DNS query from {client_address}")
# Implement DNS resolution logic here
# Respond to the client with the appropriate DNS information
if __name__ == "__main__":
start_dns_server()
21. Planning Network-based Firewalls
5. Select Technology: Choose the right firewall type (stateful, NGFW, proxy, UTM).
7. Logging and Monitoring: Configure logs and implement monitoring for threat detection.
9. Update and Patch Management: Regularly update firewall firmware and apply patches.
11. Testing and Evaluation: Conduct regular tests and evaluations, including penetration
testing.
12. Training and Awareness: Train personnel on firewall management and raise security
awareness.
15. Regular Review: Periodically review and update firewall configurations to adapt to
changes.
This planning ensures that firewalls are strategically positioned, configured, and maintained
to protect the network against various threats while meeting compliance standards.