0% found this document useful (0 votes)
18 views27 pages

N&S Lab Manual

The document outlines various C programs implementing Data Link Layer framing methods, error detection/correction techniques, and network protocols such as Stop and Wait, Go Back-N, and Distance Vector Routing. Each section includes an aim, algorithm, program code, and output examples demonstrating the successful completion of the tasks. The programs cover Bit Stuffing, Character Stuffing, LRC, CRC, and various network communication protocols.

Uploaded by

yaminishrvani
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)
18 views27 pages

N&S Lab Manual

The document outlines various C programs implementing Data Link Layer framing methods, error detection/correction techniques, and network protocols such as Stop and Wait, Go Back-N, and Distance Vector Routing. Each section includes an aim, algorithm, program code, and output examples demonstrating the successful completion of the tasks. The programs cover Bit Stuffing, Character Stuffing, LRC, CRC, and various network communication protocols.

Uploaded by

yaminishrvani
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/ 27

EX.

NO: 1 Implement the Data Link Layer framing methods


DATE:

i) Bit stuffing

Aim:
To write a c program using Implement the Data Link Layer framing methods in Bit
Stuffing.

Algorithm:
STEP-1: Read the Frame Size from the user.
STEP-2: Read the key value from the user.
STEP-3: If the size convert add the loop values.
STEP-4: Values convert the frames
STEP-5: Display the Bit Stuffing obtained above

Program:
#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:
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

Result:
Thus, the above program was successfully completed and verified.
(ii) Character stuffing

Aim:
To write a c program using Implement the Data Link Layer framing methods in Character
Stuffing.

Algorithm:
STEP-1: Read the Frame Size from the user.
STEP-2: Read the Character from the user.
STEP-3: convert the Starting and ending delimiter
STEP-4: Values convert the frames
STEP-5: Display the Character Stuffing obtained above

Program:
#include <stdio.h>
#include <string.h>

int main() {
char a[30], fs[50] = "", t[3], sd, ed, x[3], s[3], d[3], y[3];
int i;

printf("Enter characters to be stuffed: ");


scanf("%s", a);
getchar(); // to consume the newline character

printf("\nEnter a character that represents starting delimiter: ");


scanf("%c", &sd); // this reads the starting delimiter
getchar(); // to consume the newline character

printf("\nEnter a character that represents ending delimiter: ");


scanf("%c", &ed); // this reads the ending delimiter

// Setting up initial delimiter values


x[0] = s[0] = sd;
x[1] = s[1] = '\0';
y[0] = d[0] = ed;
y[1] = d[1] = '\0';

// Start by concatenating the starting delimiter to the final string


strcat(fs, x);
// Process the input string character by character
for (i = 0; i < strlen(a); i++) {
t[0] = a[i];
t[1] = '\0';

// If we encounter the starting delimiter, we append the special string for starting delimiter
if (t[0] == sd) {
strcat(fs, s);
}
// If we encounter the ending delimiter, we append the special string for ending delimiter
else if (t[0] == ed) {
strcat(fs, d);
}
// Otherwise, just append the character as is
else {
strcat(fs, t);
}
}

// Finally, add the ending delimiter to the final string


strcat(fs, y);

// Output the result


printf("\nAfter stuffing: %s\n", fs);
return 0;
}

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.

Result::
Thus, the above program was Successfully completed and verified.
EX.NO: 2 Implementation of Error Detection / Correction Techniques
DATE:

Aim:
To write a c program using Implement of Error Detection / Correction Techniques in
LRC, CRC.

Algorithm:
STEP 1: Get the data and generator polynomial.
STEP 2: Let n be the length of the generator polynomial.
STEP 3: Append n-1 zeros to data.
STEP 4: Call the CRC function.
STEP 5: If the first bit is 1, then perform a XOR operation with the first n bits of data and the
generator polynomial.
STEP 6: Shift the bits by 1 position to leave the first bit.
STEP 7: Append a bit from the data. Repeat the process until all the bits in the data are
appended.

i) LRC,

Program:

#include <stdio.h>
void main() {
int l1, bit[100], count = 0, i, choice;
printf("Enter the length of the data stream: ");
scanf("%d", &l1);
printf("\nEnter the data stream (0 or 1): ");
for (i = 0; i < l1; i++) {
scanf("%d", &bit[i]);
if (bit[i] == 1) count++;
}
printf("Number of 1's are %d\n", count);
printf("\nEnter the choice to implement parity bit:");
printf("\n1 - Sender side\n2 - Receiver side\n");
scanf("%d", &choice);
switch (choice) {
case 1:
// Adding parity bit for even parity (even number of 1s)
if (count % 2 == 0) {
bit[l1] = 0; // If even, add 0 as the parity bit
} else {
bit[l1] = 1; // If odd, add 1 as the parity bit
}

printf("\nThe data stream after adding parity bit is:\n");


for (i = 0; i <= l1; i++) {
printf("%d", bit[i]);
}
printf("\n");
break;

case 2:
// Check if the number of 1's is even or odd
if (count % 2 == 0) {
printf("\nThere is no error in the received data stream.\n");
} else {
printf("\nThere is an error in the received data stream.\n");
}
break;

default:
printf("\nInvalid choice.\n");
break;
}
}
Output:
Enter the length of data stream: 10
Enter the data stream 1 1 0 1 0 1 1 1 0 1
Number of 1's are 7
Enter the choice to implement parity bit
1- Sender side
2- Receiver side
1

The data stream after adding parity bit is


11010111011

Enter the length of data stream: 10


Enter the data stream 1 1 1 1 1 0 0 0 1 0
Number of 1's are 6
Enter the choice to implement parity bit
1- Sender side
2- Receiver side
2
There is no error in the received data stream
(ii) CRC,

Program::
#include <stdio.h>
#include <string.h>
void main() {
int i, j, keylen, msglen;
char input[100], key[30], temp[30], quot[100], rem[30];
printf("Enter the Number: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
printf("Enter the divisor: ");
fgets(key, sizeof(key), stdin);
key[strcspn(key, "\n")] = '\0';
keylen = strlen(key);
msglen = strlen(input);
// Append (keylen - 1) zeros to the end of the message
for (i = 0; i < keylen - 1; i++) {
input[msglen + i] = '0';
}
input[msglen + i] = '\0';
strcpy(temp, input);
for (i = 0; i < msglen; i++) {
quot[i] = temp[0];
if (quot[i] == '0') {
for (j = 0; j < keylen; j++) {
key[j] = '0';
}
} else {
for (j = 0; j < keylen; j++) {
key[j] = key[j];
}
}
for (j = 0; j < keylen; j++) {
if (temp[j] == key[j]) {
rem[j] = '0';
} else {
rem[j] = '1';
}
}
for (j = 0; j < keylen - 1; j++) {
rem[j] = rem[j + 1];
}
rem[keylen - 1] = input[i + keylen];

strcpy(temp, rem);
}
printf("\nThe quotient is: ");
for (i = 0; i < msglen; i++) {
printf("%c", quot[i]);
}
printf("\nThe remainder is: ");
for (i = 0; i < keylen - 1; i++) {
printf("%c", rem[i]);
}
printf("\n");
}

Output:
Enter the Number:
1 01000 0 1
Enter the divisor
1001
The quotient is 10110111 and the remainder is 0111

Result::
Thus, the above program was Successfully completed and verified.
EX.NO: 3 Implementation of Stop and Wait, and Sliding Window Protocols
DATE:

Aim:

To write a c program using Implementation of Stop and Wait, and Sliding Window
Protocols

Algorithm:

STEP 1: Start the Program


STEP 2: Import all the necessary packages
STEP 3: Create two application sender and receiver
STEP 4: Connect both applications using socket
STEP 5: Sender port number and the frame is input as receiver
STEP 6: Sender frame is send to the receiver and display to the reciever

Program:
#include <stdio.h>
#include <string.h>
int main() {
char sender[50], receiver[50];
int i, winsize;

printf("\nENTER THE WINDOW SIZE: ");


scanf("%d", &winsize);
getchar();

printf("\nSENDER WINDOW IS EXPANDED TO STORE MESSAGE OR WINDOW\n");


printf("\nENTER THE DATA TO BE SENT: ");
fgets(sender, sizeof(sender), stdin);

sender[strcspn(sender, "\n")] = '\0';

for (i = 0; i < winsize && sender[i] != '\0'; i++) {


receiver[i] = sender[i];
}
receiver[i] = '\0';

printf("\nMESSAGE SENT BY THE SENDER:\n");


puts(sender);

printf("\nWINDOW SIZE OF RECEIVER IS EXPANDED\n");


printf("\nACKNOWLEDGEMENT FROM RECEIVER\n");

printf("\nACK:%d", i);

printf("\nMESSAGE RECEIVED BY RECEIVER IS: ");


puts(receiver);
printf("\nWINDOW SIZE OF RECEIVER IS SHRUNK\n");
return 0;
}
Output:
Enter the windows size : 10
Sender window is expanded to store message or window
Enter the data to be sent: forgetcode.com
Message send by the sender:
forgetcode.com
Window size of receiver is expanded
Acknowledgement from receiver
Ack:5
Message received by receiver is : forgetcode
Window size of receiver is shrinked

Result:
Thus, the above program was Successfully completed and verified.
EX.NO:4 Implementation of Go back-N and Selective Repeat Protocols.
DATE:

Aim:
To write a c program using Implementation of Go back-N and Selective Repeat Protocols

Algorithm:
STEP 1. Start.
STEP 2. Establish connection (recommended UDP)
STEP 3. Accept the window size from the client(should be <=40)
STEP 4. Accept the packets from the network layer.
STEP 5. Calculate the total frames/windows required.
STEP 6. Send the details to the client(totalpackets,totalframes.)
STEP 7. Initialise the transmit buffer.
STEP 8. Built the frame/window depending on the windowsize.
STEP 9. Transmit the frame.
STEP 10. Wait for the acknowledgement frame.
STEP 11. Close the connection.

Program:
#include<stdio.h>
int main()
{
int windowsize,sent=0,ack,i;
printf("enter window size\n");
scanf("%d",&windowsize);
while(1)
{
for( i = 0; i < windowsize; i++)
{
printf("Frame %d has been transmitted.\n",sent);
sent++;
if(sent == windowsize)
break;
}
printf("\nPlease enter the last Acknowledgement received.\n");
scanf("%d",&ack);

if(ack == windowsize)
break;
else
sent = ack;
}
return 0;
}

Output:-
Enter window size
8
Frame 0 has been transmitted.
Frame 1 has been transmitted.
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


2
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received. 8

Result::
Thus, the above program was Successfully completed and verified.
EX.NO:5 Implementation of Distance Vector Routing algorithm (Routing Information
DATE: Protocol) (Bellman-Ford).
Aim:
To write a c program using Implementation of Distance Vector Routing algorithm
(Routing Information Protocol) (Bellman-Ford)

Algorithm:
STEP 1. Open VI-RTSIM software from desktop
STEP 2. Click the Simulation menu bar
STEP 3. Select the “Distance – Vector Routing Algorithm” option from Routing
algorithm menu bar.
STEP 4: Network with routers connected through link is drawn by using option in editor
(add router, join link, delete router, delete link, Add caption to link, add caption to
router)
STEP 5. Select any two nodes to find the shortest distance between them.
STEP 6: Click the Find path Button to run the program.
STEP 7. Now the shortest paths between the two nodes are calculated.

Program:
#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);
printf("\nEnter the cost matrix:\n");
for(i = 0; i < nodes; i++) {
for(j = 0; j < nodes; j++) {
scanf("%d", &costmat[i][j]);
if(i == j) {
costmat[i][i] = 0; // Distance from a node to itself is 0
}
rt[i].dist[j] = costmat[i][j]; // Initialize distance as the cost matrix
rt[i].from[j] = j; // Initialize the next hop as the node itself
}
}

// Bellman-Ford Algorithm for Distance Vector Routing


do {
count = 0; // Reset the count for the current iteration
for(i = 0; i < nodes; i++) { // For each node (router)
for(j = 0; j < nodes; j++) { // For each destination node
for(k = 0; k < nodes; k++) { // Check if the path through another node k is shorter
if(rt[i].dist[j] > costmat[i][k] + rt[k].dist[j]) {
rt[i].dist[j] = costmat[i][k] + rt[k].dist[j]; // Update the distance
rt[i].from[j] = k; // Update the next hop
count++; // Increase the count to indicate that a change was made
}
}
}
}
} while(count != 0); // Repeat until no updates are made

for(i = 0; i < nodes; i++) {


printf("\n\nFor router %d\n", i + 1);
for(j = 0; j < nodes; j++) {
printf("\tNode %d via %d, Distance %d\n", j + 1, rt[i].from[j] + 1, rt[i].dist[j]);
}
}
printf("\n");
return 0;
Output::

A sample run of the program works as:-


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

Result::
Thus, the above program was Successfully completed and verified.
EX.NO: 6 Implementation of Link State Routing algorithm (Open Shortest Path First) with
DATE: 5 nodes (Dijkstra's).

Aim:
To write a c program using Implementation of Link State Routing algorithm (Open
Shortest Path First) with 5 nodes (Dijkstra's).

Algorithm:
STEP 1. Create a simulator object
STEP 2. Define different colors for different data flows
STEP 3. Open a nam trace file and define finish procedure then close the trace file, and execute
nam on trace file.
STEP 4. Create n number of nodes using for loop
STEP 5. Create duplex links between the nodes
STEP 6. Setup UDP Connection between n(0) and n(5)
STEP 7. Setup another UDP connection between n(1) and n(5)
STEP 8. Apply CBR Traffic over both UDP connections
STEP 9. Choose Link state routing protocol to transmit data from sender to receiver.
STEP 10. Schedule events and run the program.

Program:

#include <limits.h>
#include <stdio.h>
#include <stdbool.h>

#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;

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


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}

return min_index;
}

void printSolution(int dist[], int n) {


printf("Vertex Distance from Source\n");
for (int i = 0; i < n; i++) {
printf("%d \t %d\n", i, dist[i]);

}
}

void dijkstra(int graph[V][V], int src) {


int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}

dist[src] = 0;

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


int u = minDistance(dist, sptSet);
sptSet[u] = true;

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


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

printSolution(dist, V);
}

int main() {
int graph[V][V] = {
{ 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};

dijkstra(graph, 0);

return 0;
}
Output:

Vertex Distance from Source


0 0
1 6
2 14
3 21
4 21
5 11
6 9
7 8
8 15

Result:
Thus, the above program was Successfully completed and verified.
EX.NO:7 Data encryption and decryption using Data Encryption Standard algorithm.
DATE:

Aim:
To write a c program using Data encryption and decryption using Data Encryption
Standard algorithm.

Algorithm:
STEP-1: Read the 64-bit plain text.
STEP-2: Split it into two 32-bit blocks and store it in two different arrays.
STEP-3: Perform XOR operation between these two arrays.
STEP-4: The output obtained is stored as the second 32-bit sequence and the original second 32-
bit sequence forms the first part.
STEP-5: Thus the encrypted 64-bit cipher text is obtained in this way. Repeat the same process
for the remaining plain text characters.
Program:

#include <stdio.h>
#include <string.h>

int main() {
int i, x;
char str[100];
printf("\nPlease enter a string:\t");
fgets(str, sizeof(str), stdin);

str[strcspn(str, "\n")] = '\0';

printf("\nPlease choose the following options:\n");


printf("1 = Encrypt the string.\n");
printf("2 = Decrypt the string.\n");
scanf("%d", &x);

switch(x) {
case 1:
// Encrypt the string by shifting each character by 3
for(i = 0; str[i] != '\0'; i++) {
str[i] = str[i] + 3; // Shift ASCII value by 3
}
printf("\nEncrypted string: %s\n", str);
break;

case 2:
// Decrypt the string by shifting each character by -3
for(i = 0; str[i] != '\0'; i++) {
str[i] = str[i] - 3; // Shift ASCII value by -3
}
printf("\nDecrypted string: %s\n", str);
break;

default:
printf("\nInvalid option selected!\n");
}

return 0;
}

Output:
#Encryption

#Decryption

Result:
Thus, the above program was Successfully completed and verified.
EX.NO: 8 Data encryption and decryption using RSA (Rivest, Shamir and Adleman) algorithm.
DATE:

Aim:
To write a c program using Data encryption and decryption using RSA (Rivest, Shamir
and Adleman) algorithm

Algorithm:
STEP-1: Select two co-prime numbers as p and q.
STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as messagee * mod n.
STEP-7: Decryption is done as cipherdmod n.
Program:

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

int gcd(int a, int b) {


int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}

int modInverse(int e, int phi) {


int t = 0, newT = 1;
int r = phi, newR = e;
int quotient, temp;

while (newR != 0) {
quotient = r / newR;

temp = t;
t = newT;
newT = temp - quotient * newT;

temp = r;
r = newR;
newR = temp - quotient * newR;
}

if (r > 1) {
printf("Error: No modular inverse exists\n");
return -1;
}

if (t < 0) {
t = t + phi;
}

return t;
}

int modExp(int base, int exp, int mod) {


int result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 == 1) {
result = (result * base) % mod;
}
exp = exp >> 1; // Right shift exponent
base = (base * base) % mod;
}
return result;
}

int main() {
int p = 3, q = 7;
int n = p * q;
int phi = (p - 1) * (q - 1);

int e = 2;

while (gcd(e, phi) != 1) {


e++;
}

int d = modInverse(e, phi);

int msg = 12;

int c = modExp(msg, e, n);

int m = modExp(c, d, n);

printf("Message data = %d\n", msg);


printf("p = %d\n", p);
printf("q = %d\n", q);
printf("n = p * q = %d\n", n);
printf("phi = (p-1) * (q-1) = %d\n", phi);
printf("e = %d\n", e);
printf("d = %d\n", d);
printf("Encrypted data = %d\n", c);
printf("Original Message Sent = %d\n", m);
return 0;
Output:

Message data = 12
p=3
q=7
n = p * q = 21
phi = (p-1) * (q-1) = 12
e=5
d=5
Encrypted data = 17
Original Message Sent = 12

Result::
Thus, the above program was Successfully completed and verified.
EX.NO:9 Implement Client Server model using FTP protocol.
DATE:

Aim:
To write a c program using Implement Client Server model using FTP protocol.

Algorithm:
STEP 1. The server starts and waits for filename.
STEP 2. The client sends a filename.
STEP 3. The server receives filename. If file is present, server starts reading file and
continues to send a buffer filled with file contents encrypted until file-end is reached.
STEP 4. End is marked by EOF.
STEP 5. File is received as buffers until EOF is received. Then it is decrypted.
STEP 6. If Not present, a file not found is sent.

Program:

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/sendfile.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "a.txt"
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 65496

int main(int argc, char **argv) {


int socket_desc;
struct sockaddr_in server;
char request_msg[BUFSIZ], reply_msg[BUFSIZ];

int file_size, file_desc;


char *data;

socket_desc = socket(AF_INET, SOCK_STREAM, 0);


if (socket_desc == -1) {
perror("Could not create socket");
return 1;
}

server.sin_addr.s_addr = inet_addr(SERVER_IP);
server.sin_family = AF_INET;
server.sin_port = htons(SERVER_PORT);

if (connect(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) {


perror("Connection failed");
return 1;
}

strcpy(request_msg, "Get ");


strcat(request_msg, FILENAME);
if (write(socket_desc, request_msg, strlen(request_msg)) < 0) {
perror("Write failed");
return 1;
}

int bytes_received = recv(socket_desc, reply_msg, sizeof(reply_msg) - 1, 0);


if (bytes_received <= 0) {
perror("Failed to receive response from server");
return 1;
}
reply_msg[bytes_received] = '\0';

if (strcmp(reply_msg, "OK") == 0) {
// Receive the file size from the server
if (recv(socket_desc, &file_size, sizeof(int), 0) <= 0) {
perror("Failed to receive file size");
return 1;
}

data = malloc(file_size);
if (!data) {
perror("Memory allocation failed");
return 1;
}

file_desc = open(FILENAME, O_CREAT | O_WRONLY | O_TRUNC, 0666);


if (file_desc == -1) {
perror("Failed to open file for writing");
free(data);
return 1;
}

int bytes_received_total = 0;
while (bytes_received_total < file_size) {
int bytes_to_receive = file_size - bytes_received_total;
int bytes_received_now = recv(socket_desc, data + bytes_received_total, bytes_to_receive, 0);
if (bytes_received_now <= 0) {
perror("Failed to receive file data");
close(file_desc);
free(data);
return 1;
}
bytes_received_total += bytes_received_now;
}

// Write received data to the file


write(file_desc, data, file_size);

// Clean up
close(file_desc);
free(data);
printf("File received and saved as %s\n", FILENAME);
} else {
fprintf(stderr, "Bad request or file not found\n");
}

// Close the socket


close(socket_desc);
return 0;
}

Output:

Connection failed: Connection refused

Result:
Thus, the above program was Successfully completed and verified.

You might also like