0% found this document useful (0 votes)
24 views16 pages

CN Practical File

The document contains code snippets for implementing various algorithms: 1) Bellman-Ford algorithm for shortest path 2) A client-server program to request and send files using TCP sockets 3) Leaky bucket algorithm for congestion control 4) CRC checksum using CRC-CCITT algorithm 5) Simple RSA encryption/decryption algorithm.

Uploaded by

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

CN Practical File

The document contains code snippets for implementing various algorithms: 1) Bellman-Ford algorithm for shortest path 2) A client-server program to request and send files using TCP sockets 3) Leaky bucket algorithm for congestion control 4) CRC checksum using CRC-CCITT algorithm 5) Simple RSA encryption/decryption algorithm.

Uploaded by

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

1.

Write a program to find the shortest path


between vertices using bellman-ford algorithm

#include <stdio.h>
#include <limits.h>
#define MAX_VERTEX 100
int graph[MAX_VERTEX][MAX_VERTEX];
int BellmanFord(int V, int E, int src) {
int dist[V];
// Initialize all distances as INFINITE and predecessor as -1
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
}
dist[src] = 0;
// Relax all edges V-1 times. A simple solution is to relax edges V
times
// assuming all weights are positive
for (int i = 1; i <= V - 1; i++) {
for (int u = 0; u < V; u++) {
for (int v = 0; v < V; v++) {
if (graph[u][v] != 0 && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
}
// Check for negative-weight cycles
for (int i = 0; i < V - 1; i++) {
for (int u = 0; u < V; u++) {
for (int v = 0; v < V; v++) {
if (graph[u][v] != 0 && dist[u] + graph[u][v] < dist[v]) {
printf("Graph contains negative weight cycle\n");
return -1;
}
}
}
}
// Print the shortest distance from source to all other vertices
printf("Vertex \t\tDistance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t%d\n", i, dist[i]);
}
return 0;
}
int main() {
int V, E;
printf("Enter the number of vertices and edges: ");
scanf("%d %d", &V, &E);
printf("Enter the graph matrix:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}
int src;
printf("Enter the source vertex: ");
scanf("%d", &src);

if (BellmanFord(V, E, src) == 0) {
printf("Shortest distances calculated successfully\n");
}

return 0;
}
2. Using TCP/IP sockets, write a client server
program to make the client send the file name
and to make the server sends back the content of
requested file if present.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAX_BUFFER 1024
#define PORT 8080
int main() {
int sockfd, connfd;
struct sockaddr_in servaddr, cliaddr;
// Create socket descriptor
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Set server address
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind socket to address
if (bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(sockfd, 5) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Server waiting for connections on port %d\n", PORT);
while (1) {
int len = sizeof(cliaddr);
// Accept connection request from client
connfd = accept(sockfd, (struct sockaddr*)&cliaddr,
(socklen_t*)&len);
if (connfd < 0) {
perror("accept failed");
continue;
}
char buffer[MAX_BUFFER];
int n;
// Receive filename from client
n = recv(connfd, buffer, MAX_BUFFER, 0);
if (n <= 0) {
perror("recv failed");
close(connfd);
continue;
}
buffer[n] = '\0';
printf("Client requested file: %s\n", buffer);
// Open requested file
FILE* fp = fopen(buffer, "rb");
if (fp == NULL) {
printf("File not found\n");
n = send(connfd, "File not found", strlen("File not found"), 0);
if (n == -1) {
perror("send failed");
}
close(connfd);
continue;
}
// Read file content and send to client
while ((n = fread(buffer, 1, MAX_BUFFER, fp)) > 0) {
if (send(connfd, buffer, n, 0) == -1) {
perror("send failed");
break;
}
}

fclose(fp);
close(connfd);
}

close(sockfd);
return 0;
}
3. Write a program for congestion control using
leaky bucket algorithm.

#include <stdio.h>
#include <time.h>
#define BUCKET_SIZE 10 // Maximum number of packets the bucket
can hold
#define LEAK_RATE 2 // Rate at which packets are removed from
the bucket (packets/second)
int main() {
int bucket_level = 0; // Current number of packets in the bucket
int packet_arrival_rate; // Rate at which packets arrive
(packets/second)
srand(time(NULL)); // Seed random number generator
while (1) {
// Simulate random packet arrival rate
packet_arrival_rate = rand() % 5 + 1; // Generate a random arrival
rate between 1 and 5 packets/second

// Check if bucket is full


if (bucket_level == BUCKET_SIZE) {
printf("Bucket is full, packet dropped\n");
} else {
// Add arriving packets to the bucket
int packets_to_add = packet_arrival_rate;
if (packets_to_add + bucket_level > BUCKET_SIZE) {
packets_to_add = BUCKET_SIZE - bucket_level;
}
bucket_level += packets_to_add;
printf("Received %d packets, bucket level: %d\n",
packets_to_add, bucket_level);
}
// Simulate leaking packets at a constant rate
if (bucket_level > 0) {
if (bucket_level >= LEAK_RATE) {
bucket_level -= LEAK_RATE;
printf("Leaked %d packets, bucket level: %d\n", LEAK_RATE,
bucket_level);
} else {
bucket_level = 0;
printf("Leaked %d packets, bucket level: %d (empty)\n",
bucket_level, bucket_level);
}
}
sleep(1); // Simulate 1 second interval
}
return 0;
}
4. Write a program for error detecting code using
CRC-CCITT(16-bits).

#include <stdio.h>

#define WIDTH (sizeof(unsigned short) * 8) // Assuming 16-bit


unsigned short for CRC

// CRC-CCITT (16-bits) polynomial


static const unsigned short crc_poly = 0x10201;

unsigned short crc_ccitt(const unsigned char *data, size_t len) {


unsigned short crc = 0xFFFF; // Initialize CRC register to all ones

for (size_t i = 0; i < len; i++) {


// Reflect the current byte in for efficient bit-by-bit computation
unsigned char current_byte = data[i];
for (int j = 0; j < WIDTH; j++) {
unsigned short bit = ((current_byte >> j) & 1) << (WIDTH - j - 1); //
Reflect current bit
crc = (crc ^ bit) ? (crc << 1) ^ crc_poly : (crc << 1); // XOR and shift
}
}
// Invert CRC for final checksum
return ~crc;
}

int main() {
unsigned char data[] = "1011001010111111"; // Example data string
size_t len = sizeof(data) - 1; // Exclude null terminator

unsigned short crc = crc_ccitt(data, len);

printf("Data: %s\n", data);


printf("CRC-CCITT (16-bits) checksum: 0x%04X\n", crc);

return 0;
}
5. Write a program for simple RSA algorithm.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int isPrime(int n) {
if (n <= 1) return 0;
if (n <= 3) return 1;
if (n % 2 == 0 || n % 3 == 0) return 0;

for (int i = 5; i * i <= n; i += 6) {


if (n % i == 0 || n % (i + 2) == 0) {
return 0;
}
}
return 1;
}

int gcd(int a, int b) {


if (a == 0) return b;
return gcd(b % a, a);
}
int modInverse(int a, int m) {
int m0 = m;
int y = 0, x = 1;

if (m == 1) return 0;

while (a > 1) {
int q = a / m;
int t = m;

m = a % m;
a = t;
t = y;

y = x - q * y;
x = t;
}

if (x < 0) x += m0;

return x;
}
int generateKeyPair(int* publicKey, int* privateKey, int p, int q) {
if (!isPrime(p) || !isPrime(q)) {
printf("Both p and q must be prime numbers.\n");
return -1;
}

int n = p * q;
int phi_n = (p - 1) * (q - 1);

// Find a public exponent (e) that is coprime to phi_n and between 1


and phi_n-1
int e = 2;
while (gcd(e, phi_n) != 1 || e >= phi_n) {
e++;
}

// Find the private exponent (d) using modular inverse


int d = modInverse(e, phi_n);

*publicKey = e;
*privateKey = d;
return n;
}
int encrypt(int message, int publicKey, int n) {
return (int)pow(message, publicKey) % n;
}

int decrypt(int encryptedMessage, int privateKey, int n) {


return (int)pow(encryptedMessage, privateKey) % n;
}

int main() {
int p, q, publicKey, privateKey, n;

printf("Enter two prime numbers (p and q): ");


scanf("%d %d", &p, &q);

if (generateKeyPair(&publicKey, &privateKey, p, q) == -1) {


return 1;
}

printf("Public key (e): %d\n", publicKey);


printf("Private key (d): %d\n", privateKey);
printf("Modulus (n): %d\n", n);

int message;
printf("Enter a message to encrypt: ");
scanf("%d", &message);

int encryptedMessage = encrypt(message, publicKey, n);


printf("Encrypted message: %d\n", encryptedMessage);

int decryptedMessage = decrypt(encryptedMessage, privateKey, n);


printf("Decrypted message: %d\n", decryptedMessage);

return 0;
}

You might also like