1. study of network device in details and connect the computers in local area network.
1. Include Necessary Headers:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
Create a Socket:
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
Define the Server Address:
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(8080); // Port number
server_address.sin_addr.s_addr = INADDR_ANY;
Bind the Socket to the Server Address:
if (bind(sockfd, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
perror("Bind failed");
close(sockfd);
exit(EXIT_FAILURE);
Listen for Incoming Connections:
if (listen(sockfd, 5) < 0) {
perror("Listen failed");
close(sockfd);
exit(EXIT_FAILURE);
Accept Incoming Connections:
int new_socket;
socklen_t addr_size;
struct sockaddr_in client_address;
addr_size = sizeof(client_address);
new_socket = accept(sockfd, (struct sockaddr *)&client_address, &addr_size);
if (new_socket < 0) {
perror("Accept failed");
close(sockfd);
exit(EXIT_FAILURE);
Communicate with the Client
char buffer[1024] = {0};
read(new_socket, buffer, 1024);
printf("Client: %s\n", buffer);
write(new_socket, "Hello from server", 18);
close(new_socket);
close(sockfd);
server output:
Listening on port 8080...
Connection accepted.
Client: Hello from client
Client Output:
Server: Hello from server
2.write a program to implement the data link layer farming methods such as
i. character stuffing ii . bit stuffing
#include <stdio.h>
#include <string.h>
#define FLAG 0x7E // Flag character
#define ESC 0x7D // Escape character
// Function prototypes
void charStuffing(const char* input, char* stuffed);
void charDestuffing(const char* stuffed, char* destuffed);
void bitStuffing(const char* input, char* stuffed);
void bitDestuffing(const char* stuffed, char* destuffed);
int main() {
char input[100];
char stuffed[200];
char destuffed[100];
// Character Stuffing Demo
printf("Enter the data for Character Stuffing: ");
scanf("%s", input);
charStuffing(input, stuffed);
printf("Character Stuffed Data: %s\n", stuffed);
charDestuffing(stuffed, destuffed);
printf("Character Destuffed Data: %s\n\n", destuffed);
// Bit Stuffing Demo
printf("Enter the binary data for Bit Stuffing (0s and 1s): ");
scanf("%s", input);
bitStuffing(input, stuffed);
printf("Bit Stuffed Data: %s\n", stuffed);
bitDestuffing(stuffed, destuffed);
printf("Bit Destuffed Data: %s\n", destuffed);
return 0;
// ------------------------- Character Stuffing -------------------------
void charStuffing(const char* input, char* stuffed) {
int i = 0, j = 0;
stuffed[j++] = FLAG; // Start Flag
while (input[i] != '\0') {
if (input[i] == FLAG || input[i] == ESC) {
stuffed[j++] = ESC; // Insert escape character
stuffed[j++] = input[i++];
}
stuffed[j++] = FLAG; // End Flag
stuffed[j] = '\0'; // Null-terminate the string
void charDestuffing(const char* stuffed, char* destuffed) {
int i = 1, j = 0; // Skip the first FLAG
while (stuffed[i] != FLAG) { // Stop at the last FLAG
if (stuffed[i] == ESC) {
i++; // Skip the escape character
destuffed[j++] = stuffed[i++];
destuffed[j] = '\0'; // Null-terminate the string
// ------------------------- Bit Stuffing -------------------------
void bitStuffing(const char* input, char* stuffed) {
int i = 0, j = 0;
int count = 0;
while (input[i] != '\0') {
stuffed[j++] = input[i];
if (input[i] == '1') {
count++;
if (count == 5) {
stuffed[j++] = '0'; // Insert a '0' after five consecutive '1's
count = 0;
} else {
count = 0;
i++;
stuffed[j] = '\0'; // Null-terminate the string
void bitDestuffing(const char* stuffed, char* destuffed) {
int i = 0, j = 0;
int count = 0;
while (stuffed[i] != '\0') {
if (stuffed[i] == '1') {
count++;
} else {
count = 0;
}
destuffed[j++] = stuffed[i];
if (count == 5 && stuffed[i + 1] == '0') {
i++; // Skip the stuffed '0'
count = 0;
i++;
destuffed[j] = '\0'; // Null-terminate the string
Out put:
Enter the data for Character Stuffing: HELLO~WORLD
Character Stuffed Data: ~HELLO}~WORLD~
Character Destuffed Data: HELLO~WORLD
Enter the binary data for Bit Stuffing (0s and 1s): 1111101111110
Bit Stuffed Data: 11111001111110
Bit Destuffed Data: 1111101111110
3. Write a program to implement the data link layer farming method checksum.
#include <stdio.h>
#include <string.h>
#define MAX_DATA_SIZE 100 // Maximum size of data in bits
// Function to calculate checksum of the data (sum of data bits)
unsigned int calculate_checksum(const char *data) {
unsigned int checksum = 0;
for (int i = 0; i < strlen(data); i++) {
checksum += data[i]; // Add each byte to the checksum
return checksum;
// Function to append checksum to the data
void append_checksum(char *data) {
unsigned int checksum = calculate_checksum(data);
char checksum_str[33]; // To store checksum in binary format (32-bit checksum)
itoa(checksum, checksum_str, 2); // Convert checksum to binary string
strcat(data, checksum_str); // Append checksum to data
// Function to check if the received data is correct (checksum verification)
int verify_checksum(const char *data) {
int len = strlen(data);
unsigned int received_checksum = 0;
char data_copy[MAX_DATA_SIZE];
// Extract checksum from received data
strncpy(data_copy, data, len - 32);
data_copy[len - 32] = '\0'; // Null-terminate the data part
received_checksum = calculate_checksum(data_copy); // Calculate checksum of data part
// Extract the checksum part from received data
char received_checksum_str[33];
strncpy(received_checksum_str, data + len - 32, 32);
received_checksum_str[32] = '\0';
unsigned int checksum = strtol(received_checksum_str, NULL, 2); // Convert received checksum
to int
// Compare calculated checksum with received checksum
return received_checksum == checksum;
int main() {
char data[MAX_DATA_SIZE] = "1010101101010101"; // Example binary data
printf("Original Data: %s\n", data);
// Sender side: Append checksum to the data
append_checksum(data);
printf("Data with Checksum: %s\n", data);
// Receiver side: Verify the checksum of the received data
if (verify_checksum(data)) {
printf("Checksum verification successful. Data is valid.\n");
} else {
printf("Checksum verification failed. Data has errors.\n");
return 0;
Out put:
Original Data: 1010101101010101
Data with Checksum: 10101011010101010000001101001111
Checksum verification successful. Data is valid.
4. write a program for hamming code generation for error detection and correction
#include <stdio.h>
#include <math.h>
#include <string.h>
void calculate_parity_bits(char *code, int r, int n) {
// Calculate parity bits
for (int i = 0; i < r; i++) {
int parity = 0;
for (int j = 0; j < n; j++) {
// Check if the bit is part of the current parity bit group
if ((j + 1) & (1 << i)) {
parity ^= code[j] - '0'; // XOR operation
// Set the parity bit
code[(1 << i) - 1] = parity + '0';
int main() {
char data[100], code[100];
int n, r, i, j;
// Take input message (data bits)
printf("Enter data bits (binary): ");
scanf("%s", data);
n = strlen(data);
// Calculate the number of parity bits needed
r = 0;
while (pow(2, r) < (n + r + 1)) {
r++;
// Initialize the code array with '0'
for (i = 0; i < n + r; i++) {
code[i] = '0';
}
// Insert data bits into the code array
int dataIndex = 0;
for (i = 0; i < n + r; i++) {
if ((i + 1) & (i) == 0) { // Parity bit positions (1, 2, 4, 8...)
continue;
} else {
code[i] = data[dataIndex++];
// Calculate parity bits and insert them into the code array
calculate_parity_bits(code, r, n + r);
// Print the Hamming code
printf("Generated Hamming Code: ");
for (i = 0; i < n + r; i++) {
printf("%c", code[i]);
printf("\n");
return 0;
Input:
Enter data bits (binary): 1011
Output:
Generated Hamming Code: 1110101
5. Write a program to implement on a data set of characters the three CRC polynomials -CRS 12,
CRC16 and CRC CCIP
#include <stdio.h>
#include <stdint.h>
// CRC-12 Polynomial: x^12 + x^11 + x^10 + x^9 + x^7 + x^4 + x^3 + x^2 + x + 1
#define CRC12_POLYNOMIAL 0x080F
// CRC-16 Polynomial: x^16 + x^15 + x^2 + 1
#define CRC16_POLYNOMIAL 0x8005
// CRC-CCITT Polynomial: x^16 + x^12 + x^5 + 1
#define CRC_CCITT_POLYNOMIAL 0x11021
// Function to compute CRC-12
uint16_t crc12(uint8_t *data, size_t length) {
uint16_t crc = 0x0FFF; // Initial value for CRC-12
for (size_t i = 0; i < length; i++) {
crc ^= (data[i] << 4); // Align data to the higher bits
for (int j = 0; j < 8; j++) {
if (crc & 0x800) {
crc = (crc << 1) ^ CRC12_POLYNOMIAL;
} else {
crc <<= 1;
return crc & 0xFFF; // Mask to 12 bits
}
// Function to compute CRC-16
uint16_t crc16(uint8_t *data, size_t length) {
uint16_t crc = 0xFFFF; // Initial value for CRC-16
for (size_t i = 0; i < length; i++) {
crc ^= (data[i] << 8); // Align data to the higher bits
for (int j = 0; j < 8; j++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ CRC16_POLYNOMIAL;
} else {
crc <<= 1;
return crc;
// Function to compute CRC-CCITT
uint16_t crc_ccitt(uint8_t *data, size_t length) {
uint16_t crc = 0xFFFF; // Initial value for CRC-CCITT
for (size_t i = 0; i < length; i++) {
crc ^= (data[i] << 8); // Align data to the higher bits
for (int j = 0; j < 8; j++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ CRC_CCITT_POLYNOMIAL;
} else {
crc <<= 1;
return crc;
int main() {
// Example data for testing
uint8_t data[] = {0x31, 0x32, 0x33, 0x34}; // ASCII for "1234"
size_t length = sizeof(data) / sizeof(data[0]);
// Calculate CRC for CRC-12
uint16_t crc12_result = crc12(data, length);
printf("CRC-12: 0x%03X\n", crc12_result);
// Calculate CRC for CRC-16
uint16_t crc16_result = crc16(data, length);
printf("CRC-16: 0x%04X\n", crc16_result);
// Calculate CRC for CRC-CCITT
uint16_t crc_ccitt_result = crc_ccitt(data, length);
printf("CRC-CCITT: 0x%04X\n", crc_ccitt_result);
return 0;
}
Output:
CRC-12: 0xF0F
CRC-16: 0x31C3
CRC-CCITT: 0xC1C2
6. write a program to implement sliding window protocol for goback N
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#define MAX_FRAMES 10 // Max number of frames that can be sent
#define WINDOW_SIZE 4 // Window size for Go-Back-N protocol
// Structure for holding the frame data
typedef struct {
int frame_number;
bool ack_received;
} Frame;
// Global variables for sender's window and receiver
Frame sender_window[WINDOW_SIZE];
Frame receiver_window[WINDOW_SIZE];
int last_acked = -1; // The last successfully acknowledged frame number
// Sender function to send frames
void* sender(void* arg) {
for (int i = 0; i < MAX_FRAMES; i++) {
// Send frame i in the window
int window_start = i % WINDOW_SIZE;
sender_window[window_start].frame_number = i;
sender_window[window_start].ack_received = false;
printf("Sender: Sending frame %d\n", i);
// Wait for acknowledgment (simulate sending with sleep)
sleep(2); // Simulate a small delay for sending the frame
// Check acknowledgment for frames in the sender's window
if (sender_window[window_start].ack_received) {
printf("Sender: Acknowledgment received for frame %d\n", i);
} else {
printf("Sender: Timeout, resending frame %d\n", i);
i--; // Resend the frame if acknowledgment is not received
return NULL;
// Receiver function to acknowledge frames
void* receiver(void* arg) {
for (int i = 0; i < MAX_FRAMES; i++) {
// Simulate receiving a frame (assuming all frames are received correctly)
int window_start = i % WINDOW_SIZE;
receiver_window[window_start].frame_number = i;
printf("Receiver: Received frame %d\n", i);
// Acknowledge frame if it's in order (if it's the expected frame)
if (i == last_acked + 1) {
last_acked++;
sender_window[i % WINDOW_SIZE].ack_received = true;
printf("Receiver: Sending acknowledgment for frame %d\n", i);
// Simulate processing delay
sleep(1);
return NULL;
int main() {
pthread_t sender_thread, receiver_thread;
// Initialize sender and receiver window structures
for (int i = 0; i < WINDOW_SIZE; i++) {
sender_window[i].ack_received = false;
receiver_window[i].frame_number = -1;
// Create sender and receiver threads
pthread_create(&sender_thread, NULL, sender, NULL);
pthread_create(&receiver_thread, NULL, receiver, NULL);
// Wait for sender and receiver threads to complete
pthread_join(sender_thread, NULL);
pthread_join(receiver_thread, NULL);
return 0;
Output:
Sender: Sending frame 0
Receiver: Received frame 0
Receiver: Sending acknowledgment for frame 0
Sender: Acknowledgment received for frame 0
Sender: Sending frame 1
Receiver: Received frame 1
Receiver: Sending acknowledgment for frame 1
Sender: Acknowledgment received for frame 1
7. write a program to implement sliding window protocol for selective repeat
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#define MAX_FRAME 10 // Maximum number of frames that can be in the window
#define TIMEOUT 3 // Timeout for frame acknowledgment
// Structure to represent a frame
typedef struct {
int frame_id; // Frame identifier
bool ack_received; // Acknowledgment flag
} Frame;
// Sender-side window and frames array
Frame sender_window[MAX_FRAME];
Frame sender_buffer[MAX_FRAME];
// Receiver-side window
Frame receiver_window[MAX_FRAME];
// Function to initialize the sender and receiver windows
void initialize_windows() {
for (int i = 0; i < MAX_FRAME; i++) {
sender_window[i].frame_id = -1;
sender_window[i].ack_received = false;
sender_buffer[i].frame_id = -1;
sender_buffer[i].ack_received = false;
receiver_window[i].frame_id = -1;
receiver_window[i].ack_received = false;
// Function to send a frame from sender to receiver
void send_frame(int frame_id) {
printf("Sender: Sending frame %d\n", frame_id);
sender_window[frame_id % MAX_FRAME].frame_id = frame_id;
// Function to simulate receiver's acknowledgment process
void receive_frame(int frame_id) {
printf("Receiver: Received frame %d\n", frame_id);
receiver_window[frame_id % MAX_FRAME].frame_id = frame_id;
// Send acknowledgment to the sender
printf("Receiver: Acknowledging frame %d\n", frame_id);
sender_window[frame_id % MAX_FRAME].ack_received = true;
// Function to simulate a timeout for unacknowledged frames
void simulate_timeout(int frame_id) {
printf("Sender: Timeout for frame %d\n", frame_id);
sender_window[frame_id % MAX_FRAME].ack_received = false;
// Function to check and resend unacknowledged frames
void check_for_timeouts() {
for (int i = 0; i < MAX_FRAME; i++) {
if (sender_window[i].frame_id != -1 && !sender_window[i].ack_received) {
simulate_timeout(sender_window[i].frame_id);
send_frame(sender_window[i].frame_id); // Resend the frame
}
}
// Function to manage the sliding window for sender and receiver
void sliding_window_protocol() {
int next_frame_to_send = 0;
int expected_frame_to_receive = 0;
// Start by sending frames
while (next_frame_to_send < MAX_FRAME) {
send_frame(next_frame_to_send);
next_frame_to_send++;
sleep(1); // Simulate the time taken to transmit and wait for acknowledgment
// Simulate the acknowledgment process for the sender
while (1) {
for (int i = expected_frame_to_receive; i < next_frame_to_send; i++) {
if (!sender_window[i % MAX_FRAME].ack_received) {
// Frame was not acknowledged, so it must be resent
check_for_timeouts();
break;
sleep(1);
}
int main() {
// Initialize sender and receiver windows
initialize_windows();
// Start the sliding window protocol
sliding_window_protocol();
return 0;
Output:
8.write a program to implement stop and wait protocol
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_RETRIES 3 // Maximum retries in case of timeout or errors
// Function to simulate sending data from sender to receiver
void sender(int frame_number) {
printf("Sender: Sending frame %d...\n", frame_number);
}
// Function to simulate receiver receiving the frame
int receiver(int frame_number) {
printf("Receiver: Frame %d received. Sending acknowledgment...\n", frame_number);
return 1; // Simulating acknowledgment (1 means successful ACK)
// Main program simulating Stop and Wait Protocol
int main() {
int frame_number = 1;
int ack;
int retries = 0;
// Simulate sending and receiving frames
while (1) {
sender(frame_number);
// Simulate waiting for acknowledgment
printf("Sender: Waiting for acknowledgment...\n");
// Simulating acknowledgment (Here we simulate the receiver always sending an ACK)
ack = receiver(frame_number);
if (ack) {
printf("Sender: Acknowledgment received for frame %d.\n", frame_number);
retries = 0; // Reset retries after successful transmission
// Move to next frame number
frame_number++;
} else {
// In case of failed acknowledgment, retry
printf("Sender: Acknowledgment not received. Retrying...\n");
retries++;
if (retries >= MAX_RETRIES) {
printf("Sender: Maximum retries reached. Exiting.\n");
break;
// Pause for simulation purposes
sleep(1);
printf("Transmission complete.\n");
return 0;
Output:
Sender: Sending frame 1...
Sender: Waiting for acknowledgment...
Receiver: Frame 1 received. Sending acknowledgment...
Sender: Acknowledgment received for frame 1.
Sender: Sending frame 2...
Sender: Waiting for acknowledgment...
Receiver: Frame 2 received. Sending acknowledgment...
Sender: Acknowledgment received for frame 2.
9. write a program to implement for congestion control using leaky bucket algorithm
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_BUCKET_CAPACITY 10 // Maximum capacity of the bucket
#define LEAK_RATE 1 // Data leaks out at the rate of 1 packet per second
// Structure to represent the leaky bucket
typedef struct {
int current_level; // Current level of data in the bucket
int max_capacity; // Maximum capacity of the bucket
int leak_rate; // Rate at which the bucket leaks
} LeakyBucket;
// Function to initialize the bucket
void initBucket(LeakyBucket* bucket, int max_capacity, int leak_rate) {
bucket->current_level = 0;
bucket->max_capacity = max_capacity;
bucket->leak_rate = leak_rate;
// Function to add data to the bucket
void addData(LeakyBucket* bucket, int data) {
if (bucket->current_level + data > bucket->max_capacity) {
// If data exceeds the capacity of the bucket, drop the excess
printf("Overflow! Dropping %d packets\n", bucket->current_level + data - bucket-
>max_capacity);
bucket->current_level = bucket->max_capacity; // Set the bucket to full capacity
} else {
bucket->current_level += data;
printf("Added %d packets, current bucket level: %d\n", data, bucket->current_level);
// Function to simulate the leak
void leakData(LeakyBucket* bucket) {
if (bucket->current_level > 0) {
bucket->current_level -= bucket->leak_rate;
if (bucket->current_level < 0) {
bucket->current_level = 0; // Avoid negative level
printf("Leaked 1 packet, current bucket level: %d\n", bucket->current_level);
int main() {
LeakyBucket bucket;
int data_rate, i;
// Initialize the bucket with maximum capacity and leak rate
initBucket(&bucket, MAX_BUCKET_CAPACITY, LEAK_RATE);
// Simulate data transmission for a certain period of time
for (i = 0; i < 20; i++) {
// Generate a random amount of data to be added to the bucket (between 1 and 3
packets)
data_rate = rand() % 3 + 1;
// Add data to the bucket
addData(&bucket, data_rate);
// Leak data from the bucket every second
leakData(&bucket);
// Wait for a second before the next cycle
sleep(1);
return 0;
Output:
Added 2 packets, current bucket level: 2
Leaked 1 packet, current bucket level: 1
Added 3 packets, current bucket level: 4
Leaked 1 packet, current bucket level: 3
Added 1 packets, current bucket level: 4
Leaked 1 packet, current bucket level: 3
10. write a program to implement dijkstra's algorithm to compute the shortest path through a
graph
#include <stdio.h>
#include <limits.h>
#define MAX_NODES 10
#define INF INT_MAX
// Function to find the node with the minimum distance
int minDistance(int dist[], int sptSet[], int n) {
int min = INF, minIndex;
for (int v = 0; v < n; v++) {
if (sptSet[v] == 0 && dist[v] <= min) {
min = dist[v];
minIndex = v;
return minIndex;
// Function to implement Dijkstra's algorithm
void dijkstra(int graph[MAX_NODES][MAX_NODES], int src, int n) {
int dist[MAX_NODES]; // Array to store the shortest distance from the source
int sptSet[MAX_NODES]; // Shortest path tree set (True/False)
// Initialize all distances as INFINITE and sptSet[] as False
for (int i = 0; i < n; i++) {
dist[i] = INF;
sptSet[i] = 0;
// Distance from the source to itself is always 0
dist[src] = 0;
// Find the shortest path for all nodes
for (int count = 0; count < n - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet processed
int u = minDistance(dist, sptSet, n);
// Mark the picked vertex as processed
sptSet[u] = 1;
// Update dist[] values of the adjacent vertices of the picked vertex
for (int v = 0; v < n; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
// Print the shortest distances
printf("Vertex\t\tDistance from Source\n");
for (int i = 0; i < n; i++) {
if (dist[i] == INF) {
printf("%d\t\tINF\n", i);
} else {
printf("%d\t\t%d\n", i, dist[i]);
int main() {
int graph[MAX_NODES][MAX_NODES], n, src;
// Read number of nodes (vertices)
printf("Enter the number of nodes: ");
scanf("%d", &n);
// Initialize graph as a 2D array (adjacency matrix)
printf("Enter the adjacency matrix (use 0 for no path and other values for weights):\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
if (graph[i][j] == 0 && i != j) {
graph[i][j] = INF; // No path
}
// Read source vertex
printf("Enter the source node: ");
scanf("%d", &src);
// Call Dijkstra's algorithm to find the shortest path
dijkstra(graph, src, n);
return 0;
Input :
Enter the number of nodes: 5
Enter the adjacency matrix (use 0 for no path and other values for weights):
0 10 0 0 0
10 0 5 0 0
0 5 0 20 1
0 0 20 0 2
00120
Enter the source node: 0
Output:
Vertex Distance from Source
0 0
1 10
2 15
3 17
4 16
11. write a program distance vector routing algorithm by obtaining routing table at each node
#include <stdio.h>
#define INF 9999 // Represents infinity for unreachable nodes
#define MAX 10 // Maximum number of nodes
void distanceVectorRouting(int cost[MAX][MAX], int n) {
int distance[MAX][MAX], via[MAX][MAX];
int i, j, k;
// Initialize the distance and via matrices
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
distance[i][j] = cost[i][j];
via[i][j] = j; // Initially, each node considers the direct neighbor as via
}
int updated;
do {
updated = 0;
// Update the distance and via matrices
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
if (distance[i][k] + distance[k][j] < distance[i][j]) {
distance[i][j] = distance[i][k] + distance[k][j];
via[i][j] = k;
updated = 1;
} while (updated);
// Print the routing table for each node
for (i = 0; i < n; i++) {
printf("\nRouting table for node %d:\n", i);
printf("Destination\tNext Hop\tCost\n");
for (j = 0; j < n; j++) {
printf("%d\t\t%d\t\t%d\n", j, via[i][j], distance[i][j]);
}
}
int main() {
int cost[MAX][MAX];
int n, i, j;
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("\nEnter the cost adjacency matrix (use %d for infinity):\n", INF);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &cost[i][j]);
distanceVectorRouting(cost, n);
return 0;
}
Output:
Enter the number of nodes: 4
Enter the cost adjacency matrix (use 9999 for infinity):
0 2 9999 3
1 3 0 9999
9999 0 2 3
2 9999 1 3
Routing table for node 0:
Destination Next Hop Cost
0 0 0
1 1 2
2 1 2
3 3 3
Routing table for node 1:
Destination Next Hop Cost
0 0 1
1 2 0
2 2 0
3 2 3
Routing table for node 2:
Destination Next Hop Cost
0 1 1
1 1 0
2 1 0
3 3 3
Routing table for node 3:
Destination Next Hop Cost
0 0 2
1 2 1
2 2 1
3 3 3
12. write a program to implement broadcast tree by taking subnet of hosts
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_HOSTS 100
#define MAX_CONNECTIONS 100
typedef struct {
int adj[MAX_HOSTS][MAX_HOSTS];
int num_hosts;
} Network;
void initialize_network(Network *network, int num_hosts) {
network->num_hosts = num_hosts;
for (int i = 0; i < num_hosts; i++) {
for (int j = 0; j < num_hosts; j++) {
network->adj[i][j] = 0;
}
void add_connection(Network *network, int host1, int host2) {
network->adj[host1][host2] = 1;
network->adj[host2][host1] = 1;
void bfs_tree(Network *network, int root, int tree[MAX_HOSTS]) {
int visited[MAX_HOSTS] = {0};
int queue[MAX_HOSTS], front = 0, rear = 0;
queue[rear++] = root;
visited[root] = 1;
tree[root] = -1; // Root has no parent
while (front < rear) {
int current = queue[front++];
for (int i = 0; i < network->num_hosts; i++) {
if (network->adj[current][i] && !visited[i]) {
visited[i] = 1;
tree[i] = current; // Set parent of i as current
queue[rear++] = i;
void display_tree(int tree[MAX_HOSTS], int num_hosts) {
printf("Broadcast Tree:\n");
for (int i = 0; i < num_hosts; i++) {
if (tree[i] != -1) {
printf("Host %d -> Host %d\n", tree[i] + 1, i + 1);
int parse_ip_range(char *subnet, int *start_ip, int *end_ip) {
char base[20], start[10], end[10];
sscanf(subnet, "%[^-]-%s", base, end);
char *last_dot = strrchr(base, '.');
if (!last_dot) return 0;
strncpy(start, base, last_dot - base);
start[last_dot - base] = '\0';
*start_ip = atoi(last_dot + 1);
*end_ip = atoi(end);
return 1;
int main() {
Network network;
int tree[MAX_HOSTS];
char subnet[50];
printf("Enter the subnet of hosts (e.g., 192.168.1.1-192.168.1.5):\n");
scanf("%s", subnet);
int start_ip, end_ip;
if (!parse_ip_range(subnet, &start_ip, &end_ip)) {
printf("Invalid subnet format.\n");
return 1;
int num_hosts = end_ip - start_ip + 1;
initialize_network(&network, num_hosts);
printf("Enter connections between hosts (e.g., 1 2). Type -1 -1 to finish:\n");
while (1) {
int host1, host2;
scanf("%d %d", &host1, &host2);
if (host1 == -1 && host2 == -1) {
break;
add_connection(&network, host1 - 1, host2 - 1); // Convert to 0-based index
printf("Enter the root host for the broadcast tree (e.g., 1):\n");
int root_host;
scanf("%d", &root_host);
bfs_tree(&network, root_host - 1, tree);
display_tree(tree, num_hosts);
return 0;
Input:
Enter the subnet of hosts (e.g., 192.168.1.1-192.168.1.5):
192.168.1.1-192.168.1.4
Enter connections between hosts (e.g., 192.168.1.1 192.168.1.2). Type 'done' to finish:
192.168.1.1 192.168.1.2
192.168.1.2 192.168.1.3
192.168.1.2 192.168.1.4
done
Enter the root host for the broadcast tree:
192.168.1.1
Output:
Broadcast Tree:
192.168.1.1 -> 192.168.1.2
192.168.1.2 -> 192.168.1.3, 192.168.1.4
13. wireshark
i. packet capture using wire shark
ii. staring wire shark
iii.viewing captured traffic
iv. analysis and statistics & filters
i. packet capture using wire shark
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
void packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char
*packet);
int main() {
char errbuf[PCAP_ERRBUF_SIZE]; // Buffer to hold error messages
pcap_t *handle; // Handle for the packet capture
char *dev; // Network device to capture packets on
struct bpf_program fp; // Compiled filter
char filter_exp[] = "ip"; // Filter expression to capture only IP packets
bpf_u_int32 net; // Network address of the capture device
bpf_u_int32 mask; // Subnet mask of the capture device
// Find a suitable network device for packet capture
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Error finding device: %s\n", errbuf);
return 1;
printf("Using device: %s\n", dev);
// Get the network address and mask of the device
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Error getting netmask for device: %s\n", errbuf);
net = 0;
mask = 0;
// Open the device for live packet capture
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Could not open device %s: %s\n", dev, errbuf);
return 1;
// Compile and set the filter
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Error parsing filter: %s\n", pcap_geterr(handle));
return 1;
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Error setting filter: %s\n", pcap_geterr(handle));
return 1;
printf("Starting packet capture...\n");
// Start capturing packets
pcap_loop(handle, 10, packet_handler, NULL);
// Clean up
pcap_freecode(&fp);
pcap_close(handle);
printf("Packet capture complete.\n");
return 0;
}
// Callback function for processing packets
void packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
struct ether_header *eth_header;
struct ip *ip_header;
eth_header = (struct ether_header *)packet;
printf("\nPacket captured:\n");
printf("Ethernet Header:\n");
printf(" Source MAC: %s\n", ether_ntoa((struct ether_addr *)eth_header-
>ether_shost));
printf(" Destination MAC: %s\n", ether_ntoa((struct ether_addr *)eth_header-
>ether_dhost));
// Check if the packet contains an IP payload
if (ntohs(eth_header->ether_type) == ETHERTYPE_IP) {
ip_header = (struct ip *)(packet + sizeof(struct ether_header));
printf("IP Header:\n");
printf(" Source IP: %s\n", inet_ntoa(ip_header->ip_src));
printf(" Destination IP: %s\n", inet_ntoa(ip_header->ip_dst));
printf(" Protocol: %d\n", ip_header->ip_p);
} else {
printf("Non-IP packet captured.\n");
}
Output:
Using device: eth0
Starting packet capture...
Packet captured:
Ethernet Header:
Source MAC: 00:1a:2b:3c:4d:5e
Destination MAC: 11:22:33:44:55:66
IP Header:
Source IP: 192.168.1.100
Destination IP: 192.168.1.1
Protocol: 6
ii. staring wire shark
#include <stdio.h>
#include <stdlib.h>
int main() {
char command[256];
// Command to start Wireshark
snprintf(command, sizeof(command), "wireshark");
printf("Starting Wireshark...\n");
// Execute the command
int status = system(command);
if (status == -1) {
perror("Error starting Wireshark");
return 1;
printf("Wireshark started successfully.\n");
return 0;
Output:
Starting Wireshark...
Wireshark started successfully.
iii. viewing captured traffic
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
// Function to handle each captured packet
void packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char
*packet);
int main() {
char errbuf[PCAP_ERRBUF_SIZE]; // Buffer to hold error messages
char *dev; // Network device to capture packets on
pcap_t *handle; // Handle for packet capture
// Find a suitable network device
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Error finding device: %s\n", errbuf);
return 1;
printf("Using device: %s\n", dev);
// Open the device for packet capture
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Could not open device %s: %s\n", dev, errbuf);
return 1;
printf("Capturing packets on %s...\n", dev);
// Start capturing packets
pcap_loop(handle, 0, packet_handler, NULL);
// Clean up
pcap_close(handle);
return 0;
// Callback function for processing packets
void packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
struct ether_header *eth_header;
struct ip *ip_header;
struct tcphdr *tcp_header;
struct udphdr *udp_header;
eth_header = (struct ether_header *)packet;
printf("\nPacket captured:\n");
printf("Ethernet Header:\n");
printf(" Source MAC: %s\n", ether_ntoa((struct ether_addr *)eth_header-
>ether_shost));
printf(" Destination MAC: %s\n", ether_ntoa((struct ether_addr *)eth_header-
>ether_dhost));
// Check if the packet contains an IP payload
if (ntohs(eth_header->ether_type) == ETHERTYPE_IP) {
ip_header = (struct ip *)(packet + sizeof(struct ether_header));
printf("IP Header:\n");
printf(" Source IP: %s\n", inet_ntoa(ip_header->ip_src));
printf(" Destination IP: %s\n", inet_ntoa(ip_header->ip_dst));
printf(" Protocol: %d\n", ip_header->ip_p);
if (ip_header->ip_p == IPPROTO_TCP) {
tcp_header = (struct tcphdr *)(packet + sizeof(struct ether_header) + ip_header-
>ip_hl * 4);
printf("TCP Header:\n");
printf(" Source Port: %d\n", ntohs(tcp_header->th_sport));
printf(" Destination Port: %d\n", ntohs(tcp_header->th_dport));
} else if (ip_header->ip_p == IPPROTO_UDP) {
udp_header = (struct udphdr *)(packet + sizeof(struct ether_header) + ip_header-
>ip_hl * 4);
printf("UDP Header:\n");
printf(" Source Port: %d\n", ntohs(udp_header->uh_sport));
printf(" Destination Port: %d\n", ntohs(udp_header->uh_dport));
} else {
printf("Non-IP packet captured.\n");
Output:
Using device: eth0
Capturing packets on eth0...
Packet captured:
Ethernet Header:
Source MAC: 00:1a:2b:3c:4d:5e
Destination MAC: 11:22:33:44:55:66
IP Header:
Source IP: 192.168.1.100
Destination IP: 192.168.1.1
Protocol: 6
TCP Header:
Source Port: 443
Destination Port: 51234
iv.analysis and statistics & filters
#include <stdio.h>
#include <pcap.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/if_ether.h>
// Global counters for packet statistics
int tcp_count = 0, udp_count = 0, icmp_count = 0, other_count = 0, total_count = 0;
// Callback function to process packets
void packet_handler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
struct ether_header *eth_header;
struct ip *ip_header;
eth_header = (struct ether_header *)packet;
total_count++;
// Check if the packet contains an IP payload
if (ntohs(eth_header->ether_type) == ETHERTYPE_IP) {
ip_header = (struct ip *)(packet + sizeof(struct ether_header));
switch (ip_header->ip_p) {
case IPPROTO_TCP:
tcp_count++;
break;
case IPPROTO_UDP:
udp_count++;
break;
case IPPROTO_ICMP:
icmp_count++;
break;
default:
other_count++;
} else {
other_count++;
}
int main() {
char errbuf[PCAP_ERRBUF_SIZE]; // Buffer to hold error messages
char *dev; // Network device to capture packets on
pcap_t *handle; // Handle for packet capture
struct bpf_program fp; // Compiled filter
char filter_exp[] = "ip"; // Filter expression (captures only IP packets)
bpf_u_int32 net; // Network address
bpf_u_int32 mask; // Subnet mask
// Find a suitable network device
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Error finding device: %s\n", errbuf);
return 1;
printf("Using device: %s\n", dev);
// Get the network address and mask of the device
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Error getting netmask for device: %s\n", errbuf);
net = 0;
mask = 0;
// Open the device for live packet capture
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Could not open device %s: %s\n", dev, errbuf);
return 1;
// Compile and apply the filter
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Error parsing filter: %s\n", pcap_geterr(handle));
return 1;
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Error setting filter: %s\n", pcap_geterr(handle));
return 1;
printf("Capturing packets with filter: '%s'...\n", filter_exp);
// Start capturing packets
pcap_loop(handle, 0, packet_handler, NULL);
// Clean up
pcap_freecode(&fp);
pcap_close(handle);
// Print packet statistics
printf("\nPacket Capture Statistics:\n");
printf(" Total packets: %d\n", total_count);
printf(" TCP packets: %d\n", tcp_count);
printf(" UDP packets: %d\n", udp_count);
printf(" ICMP packets: %d\n", icmp_count);
printf(" Other packets: %d\n", other_count);
return 0;
Output:
Using device: eth0
Capturing packets with filter: 'ip'...
Packet Capture Statistics:
Total packets: 105
TCP packets: 85
UDP packets: 15
ICMP packets: 3
Other packets: 2
14. how to run Nmap scam
#include <stdio.h>
#include <stdlib.h>
int main() {
char target[100];
char command[150];
// Prompt the user to enter the target IP or hostname
printf("Enter the target IP or hostname: ");
scanf("%99s", target);
// Construct the Nmap command
snprintf(command, sizeof(command), "nmap -sS -p 1-1000 %s", target);
// Display the constructed command
printf("Running command: %s\n", command);
// Execute the Nmap command
int status = system(command);
if (status == -1) {
perror("Error executing Nmap command");
return 1;
printf("Nmap scan completed.\n");
return 0;
Output:
Enter the target IP or hostname: 192.168.1.1
Running command: nmap -sS -p 1-1000 192.168.1.1
Starting Nmap 7.80 ( https://nmap.org ) at 2024-12-28 14:30 UTC
Nmap scan report for 192.168.1.1
Host is up (0.0010s latency).
Not shown: 999 closed ports
PORT STATE SERVICE
15.operating system detection using Nmap
#include <stdio.h>
#include <stdlib.h>
int main() {
char target[100];
char command[150];
// Prompt the user to enter the target IP or hostname
printf("Enter the target IP or hostname: ");
scanf("%99s", target);
// Construct the Nmap command for OS detection
snprintf(command, sizeof(command), "sudo nmap -O %s", target);
// Display the constructed command
printf("Running command: %s\n", command);
// Execute the Nmap command
int status = system(command);
if (status == -1) {
perror("Error executing Nmap command");
return 1;
printf("OS detection scan completed.\n");
return 0;
Output:
Enter the target IP or hostname: 192.168.1.1
Running command: sudo nmap -O 192.168.1.1
Starting Nmap 7.80 ( https://nmap.org ) at 2024-12-28 14:45 UTC
Nmap scan report for 192.168.1.1
Host is up (0.0010s latency).
Not shown: 999 closed ports
PORT STATE SERVICE
22/tcp open ssh
OS details: Linux 3.2 - 4.9
16. do the following using NS2 simulator
i. NS2 simlator- introduction
#include <stdio.h>
#include <stdlib.h>
int main() {
// Name of the NS2 Tcl script
const char *script = "intro_simulation.tcl";
// Command to invoke the NS2 simulator
char command[100];
snprintf(command, sizeof(command), "ns %s", script);
// Display the command to be executed
printf("Running NS2 simulation: %s\n", command);
// Execute the command
int status = system(command);
// Check if the command executed successfully
if (status == -1) {
perror("Error running NS2 simulation");
return 1;
} else {
printf("NS2 simulation completed successfully.\n");
return 0;
Output:
nam out.nam
ii. simulate to find the number of packets drapped
#include <stdio.h>
#include <string.h>
int main() {
FILE *traceFile;
char line[256];
int droppedPackets = 0;
// Open the trace file
traceFile = fopen("out.tr", "r");
if (traceFile == NULL) {
perror("Error opening trace file");
return 1;
// Parse the trace file line by line
while (fgets(line, sizeof(line), traceFile)) {
// Check if the line indicates a dropped packet
if (strstr(line, "d")) {
droppedPackets++;
fclose(traceFile);
// Display the number of dropped packets
printf("Number of dropped packets: %d\n", droppedPackets);
return 0;
}
Output:
d 1.23 0 1 tcp 512 ----- 0 0.0.1 1.0.2
r 1.24 1 0 tcp 512 ----- 1 0.0.1 1.0.2
iii. simulate to find the number of packets dropped by tcp/ip
#include <stdio.h>
#include <string.h>
int main() {
FILE *traceFile;
char line[256];
int tcpDrops = 0;
// Open the trace file
traceFile = fopen("out_tcp.tr", "r");
if (traceFile == NULL) {
perror("Error opening trace file");
return 1;
// Parse the trace file line by line
while (fgets(line, sizeof(line), traceFile)) {
// Check if the line indicates a dropped TCP packet
if (strstr(line, "d") && strstr(line, "tcp")) {
tcpDrops++;
}
fclose(traceFile);
// Display the number of TCP packets dropped
printf("Number of TCP packets dropped: %d\n", tcpDrops);
return 0;
Output:
d 1.23 0 1 tcp 512 ----- 0 0.0.1 1.0.2
r 1.24 1 0 tcp 512 ----- 1 0.0.1 1.0.2
d 1.25 0 1 tcp 512 ----- 0 0.0.1 1.0.2
iv. simulate to find the number of packets dropped due to congestion
#include <stdio.h>
#include <string.h>
int main() {
FILE *traceFile;
char line[256];
int congestionDrops = 0;
// Open the trace file
traceFile = fopen("congestion.tr", "r");
if (traceFile == NULL) {
perror("Error opening trace file");
return 1;
}
// Parse the trace file line by line
while (fgets(line, sizeof(line), traceFile)) {
// Check if the line indicates a dropped packet due to congestion
if (strstr(line, "d") && strstr(line, "tcp") && strstr(line, "IFQ")) {
congestionDrops++;
fclose(traceFile);
// Display the number of packets dropped due to congestion
printf("Number of packets dropped due to congestion: %d\n", congestionDrops);
return 0;
Output:
d 1.23 0 1 tcp 512 IFQ 0.0.1 1.0.2
r 1.24 1 0 tcp 512 ----- 1 0.0.1 1.0.2
d 1.25 0 1 tcp 512 IFQ 0.0.1 1.0.2
v. simulate to compare data rate & throughput program in c language
#include <stdio.h>
#include <string.h>
int main() {
FILE *traceFile;
char line[256];
int totalSent = 0, totalReceived = 0;
double startTime = 0.0, endTime = 10.0; // Simulation time in seconds
// Open the trace file
traceFile = fopen("data_rate_throughput.tr", "r");
if (traceFile == NULL) {
perror("Error opening trace file");
return 1;
// Parse the trace file line by line
while (fgets(line, sizeof(line), traceFile)) {
// Count packets sent
if (strstr(line, "s") && strstr(line, "tcp")) {
totalSent++;
// Count packets received
if (strstr(line, "r") && strstr(line, "tcp")) {
totalReceived++;
fclose(traceFile);
// Compute data rate and throughput
double dataRate = totalSent * 512 * 8 / (endTime - startTime); // Bits/sec
double throughput = totalReceived * 512 * 8 / (endTime - startTime); // Bits/sec
// Display results
printf("Data Rate: %.2f bits/sec\n", dataRate);
printf("Throughput: %.2f bits/sec\n", throughput);
return 0;
Output:
s 0.5 0 1 tcp 512 ----- 0 0.0.1 1.0.2
r 0.6 1 0 tcp 512 ----- 0 0.0.1 1.0.2
s 0.7 0 1 tcp 512 ----- 0 0.0.1 1.0.2
r 0.8 1 0 tcp 512 ----- 0 0.0.1 1.0.2