Assignment 1
Click the button to copy this code:
File Handling
#include stdio.h>
#include stdlib.h>
void main()
{
FILE *fptr1 = NULL, *fptr2 = NULL;
char c;
fptr1 = fopen("input.bin", "rb");
if (fptr1 == NULL)
{
printf("Error");
fclose(fptr1);
}
fptr2 = fopen("destination.bin", "wb");
if (fptr2 == NULL)
{
printf("Error");
fclose(fptr2);
}
while ((c = fgetc(fptr1)) != EOF)
{
fputc(c, fptr2);
}
fclose(fptr1);
fclose(fptr2);
printf("Successfully copied");
}
TCP Chatting Server
Click the button to copy this code:
#include stdio.h>
#include netdb.h>
#include netinet/in.h>
#include stdlib.h>
#include string.h>
#include sys/socket.h>
#include sys/types.h>
#include unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int connfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(connfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(connfd, buff, sizeof(buff));
// if msg contains "Exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
// Function for chatting between client and server
func(connfd);
// After chatting close the socket
close(sockfd);
}
TCP Chatting Client
Click the button to copy this code:
#include arpa/inet.h> // inet_addr()
#include netdb.h>
#include stdio.h>
#include stdlib.h>
#include string.h>
#include strings.h> // bzero()
#include sys/socket.h>
#include unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr))
!= 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
UDP Chatting Server
Click the button to copy this code:
// server program for udp connection
#include stdio.h>
#include strings.h>
#include sys/types.h>
#include arpa/inet.h>
#include sys/socket.h>
#include etinet/in.h>
#define PORT 5000
#define MAXLINE 1000
// Driver code
int main()
{
char buffer[100];
char *message = "Hi Client";
int listenfd, len;
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof(servaddr));
// Create a UDP Socket
listenfd = socket(AF_INET, SOCK_DGRAM, 0);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// bind server address to socket descriptor
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
//receive the datagram
len = sizeof(cliaddr);
int n = recvfrom(listenfd, buffer, sizeof(buffer),
0, (struct sockaddr*)&cliaddr,&len); //receive message from server
buffer[n] = '\0';
puts(buffer);
// send the response
sendto(listenfd, message, MAXLINE, 0,
(struct sockaddr*)&cliaddr, sizeof(cliaddr));
}
UDP Chatting Client
Click the button to copy this code:
// udp client driver program
#include stdio.h>
#include strings.h>
#include sys/types.h>
#include arpa/inet.h>
#include sys/socket.h>
#include netinet/in.h>
#include unistd.h>
#include stdlib.h>
#define PORT 5000
#define MAXLINE 1000
// Driver code
int main()
{
char buffer[100];
char *message = "Hi Server";
int sockfd, n;
struct sockaddr_in servaddr;
// clear servaddr
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// create datagram socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// connect to server
if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("\n Error : Connect Failed \n");
exit(0);
}
// request to send datagram
// no need to specify server address in sendto
// connect stores the peers IP and port
sendto(sockfd, message, MAXLINE, 0, (struct sockaddr*)NULL, sizeof(servaddr));
// waiting for response
recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)NULL, NULL);
puts(buffer);
// close the descriptor
close(sockfd);
}
String TCP Client
Click the button to copy this code:
#include arpa/inet.h> // inet_addr()
#include netdb.h>
#include stdio.h>
#include stdlib.h>
#include string.h>
#include strings.h> // bzero()
#include sys/socket.h>
#include unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
char message[101] = {0}; // 100 characters + null terminator
char buffer[101] = {0}; // Buffer for receiving the modified string
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// Prompt the user to input a message
printf("Enter a string (up to 100 characters): ");
fgets(message, 100, stdin);
message[strcspn(message, "\n")] = 0; // Remove trailing newline
// Send the message to the server
send(sockfd, message, strlen(message), 0);
printf("Message sent: %s\n", message);
// Receive the modified message from the server
int bytes_received = read(sockfd, buffer, 100);
if (bytes_received > 0)
{
printf("Received reversed and capitalized string: %s\n", buffer);
}
// close the socket
close(sockfd);
// abc
}
String TCP Server
Click the button to copy this code:
#include stdio.h>
#include netdb.h>
#include netinet/in.h>
#include stdlib.h>
#include string.h>
#include sys/socket.h>
#include sys/types.h>
#include unistd.h> // read(), write(), close()
#include ctype.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function to reverse and capitalize a string
void reverse_and_capitalize(char *str)
{
int len = strlen(str);
for (int i = 0; i < len / 2; ++i)
{
char temp = str[i];
str[i] = toupper(str[len - i - 1]);
str[len - i - 1] = toupper(temp);
}
// If the length is odd, make sure the middle character is capitalized
if (len % 2 == 1)
{
str[len / 2] = toupper(str[len / 2]);
}
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
char buffer[101] = {0}; // 100 characters + null terminator
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA *)&servaddr, sizeof(servaddr))) != 0)
{
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA *)&cli, &len);
if (connfd < 0)
{
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
// Read the string sent by the client
int bytes_read = read(connfd, buffer, 100);
if (bytes_read < 0)
{
perror("read");
exit(EXIT_FAILURE);
}
printf("Received string: %s\n", buffer);
// Reverse and capitalize the string
reverse_and_capitalize(buffer);
// Send the modified string back to the client
send(connfd, buffer, strlen(buffer), 0);
printf("Sent reversed and capitalized string: %s\n", buffer);
// After chatting close the socket
close(sockfd);
close(connfd);
}
String UDP Client
Click the button to copy this code:
#include stdio.h>
#include strings.h>
#include string.h>
#include sys/types.h>
#include arpa/inet.h>
#include sys/socket.h>
#include netinet/in.h>
#include unistd.h>
#include stdlib.h>
#define PORT 5000
#define MAX 101
// Driver code
int main()
{
int sockfd, n;
struct sockaddr_in servaddr;
socklen_t addr_len;
char buffer[MAX] = {0};
char message[MAX] = {0};
// clear servaddr
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// create datagram socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
// connect to server
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
printf("\n Error : Connect Failed \n");
exit(0);
}
// Input message from the user
printf("Enter a string (up to 100 characters): ");
fgets(message, MAX, stdin);
message[strcspn(message, "\n")] = 0; // Remove newline character
// Send message to the server
sendto(sockfd, message, strlen(message), 0, (const struct sockaddr *)&servaddr, sizeof(servaddr));
printf("Message sent: %s\n", message);
// Receive modified message from the server
addr_len = sizeof(servaddr);
recvfrom(sockfd, buffer, MAX, 0, (struct sockaddr *)&servaddr, &addr_len);
printf("Received reversed and capitalized string: %s\n", buffer);
// Close the socket
close(sockfd);
return 0;
}
String UDP Server
Click the button to copy this code:
#include stdio.h>
#include strings.h>
#include string.h>
#include sys/types.h>
#include arpa/inet.h>
#include sys/socket.h>
#include netinet/in.h>
#include stdlib.h>
#include ctype.h>
#include unistd.h> // for close()
#define PORT 5000
#define MAX 101
// Function to reverse and capitalize a string
void reverse_and_capitalize(char *str)
{
int len = strlen(str);
for (int i = 0; i < len / 2; ++i)
{
char temp = str[i];
str[i] = toupper(str[len - i - 1]);
str[len - i - 1] = toupper(temp);
}
// If the length is odd, make sure the middle character is capitalized
if (len % 2 == 1)
{
str[len / 2] = toupper(str[len / 2]);
}
}
// Driver code
int main()
{
char buffer[MAX] = {0};
socklen_t addr_len;
int sockfd;
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof(servaddr));
// Create a UDP Socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// Bind server address to socket descriptor
if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("Bind failed");
close(sockfd);
exit(EXIT_FAILURE);
}
while (1)
{
addr_len = sizeof(cliaddr);
// Receive message from client
int bytes_received = recvfrom(sockfd, buffer, MAX - 1, 0, (struct sockaddr *)&cliaddr, &addr_len);
if (bytes_received < 0)
{
perror("Receive failed");
continue; // Optionally break if you want to exit on error
}
buffer[bytes_received] = '\0'; // Null-terminate the received string
printf("Received string: %s (Length: %d)\n", buffer, bytes_received);
// Reverse and capitalize the string
reverse_and_capitalize(buffer);
// Send modified message back to the client
if (sendto(sockfd, buffer, strlen(buffer), 0, (const struct sockaddr *)&cliaddr, addr_len) < 0)
{
perror("Send failed");
}
else
{
printf("Sent reversed and capitalized string: %s\n", buffer);
}
}
close(sockfd);
return 0;
}
Calculator tcp client
Click the button to copy this code:
#include arpa/inet.h> // inet_addr()
#include netdb.h>
#include stdio.h>
#include stdlib.h>
#include string.h>
#include strings.h> // bzero()
#include sys/socket.h>
#include unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
char expression[MAX] = {0};
double result;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0)
{
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// Get expression from user
printf("Enter a mathematical expression (e.g., 5 + 10): ");
fgets(expression, MAX, stdin);
expression[strcspn(expression, "\n")] = 0; // Remove the newline character
// Send expression to the server
write(sockfd, expression, strlen(expression));
// Receive result from the server
read(sockfd, &result, sizeof(result));
printf("Result received from server: %f\n", result);
close(sockfd);
}
Calculator tcp server
Click the button to copy this code:
#include stdio.h>
#include netdb.h>
#include netinet/in.h>
#include stdlib.h>
#include string.h>
#include sys/socket.h>
#include sys/types.h>
#include unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function to evaluate the expression (simple handling)
double evaluate_expression(char *expression)
{
// For simplicity, using system to execute bc (calculator) on the system
// This can be extended to handle more complex operations safely.
char command[MAX];
snprintf(command, sizeof(command), "echo '%s' | bc", expression);
FILE *fp = popen(command, "r");
if (fp == NULL)
{
perror("popen failed");
return -1;
}
char result_str[MAX];
if (fgets(result_str, sizeof(result_str), fp) == NULL)
{
perror("fgets failed");
pclose(fp);
return -1;
}
pclose(fp);
return strtod(result_str, NULL); // Convert the result string to double
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
char buffer[MAX] = {0};
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA *)&servaddr, sizeof(servaddr))) != 0)
{
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0)
{
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA *)&cli, &len);
if (connfd < 0)
{
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
// Receiving expression from client
read(connfd, buffer, sizeof(buffer));
printf("Received expression: %s\n", buffer);
// Evaluate the expression
double result = evaluate_expression(buffer);
// Sending the result back to the client
write(connfd, &result, sizeof(result));
printf("Sent result: %f\n", result);
close(connfd);
close(sockfd);
return 0;
}
UDP Server Calculator
Click the button to copy this code:
// Server code: udp_server.c
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
// Function to evaluate the expression
double evaluate_expression(char *expression) {
char command[BUFFER_SIZE];
snprintf(command, sizeof(command), "echo '%s' | bc", expression);
FILE *fp = popen(command, "r");
if (fp == NULL) {
perror("popen failed");
return -1;
}
char result_str[BUFFER_SIZE];
if (fgets(result_str, sizeof(result_str), fp) == NULL) {
perror("fgets failed");
pclose(fp);
return -1;
}
pclose(fp);
return strtod(result_str, NULL); // Convert the result string to double
}
int main() {
int sockfd;
struct sockaddr_in server_addr, client_addr;
char buffer[BUFFER_SIZE];
socklen_t len;
double result;
// Creating socket file descriptor
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
memset(&server_addr, 0, sizeof(server_addr));
memset(&client_addr, 0, sizeof(client_addr));
// Filling server information
server_addr.sin_family = AF_INET; // IPv4
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// Bind the socket with the server address
if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
close(sockfd);
exit(EXIT_FAILURE);
}
printf("UDP Server listening on port %d\n", PORT);
// Main loop to receive expressions from clients
len = sizeof(client_addr); // Length of client address
while (1) {
// Receive expression from client
int n = recvfrom(sockfd, (char *)buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &len);
buffer[n] = '\0';
printf("Received expression: %s\n", buffer);
// Evaluate the expression
result = evaluate_expression(buffer);
// Send the result back to the client
sendto(sockfd, &result, sizeof(result), 0, (const struct sockaddr *)&client_addr, len);
printf("Sent result: %f\n", result);
}
close(sockfd);
return 0;
}
UDP Client Calculator
Click the button to copy this code:
// Client code: udp_client.c
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int sockfd;
struct sockaddr_in serv_addr;
char expression[BUFFER_SIZE];
double result;
socklen_t addr_len;
// Creating socket file descriptor
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&serv_addr, 0, sizeof(serv_addr));
// Filling server information
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
addr_len = sizeof(serv_addr);
// Get expression from user
printf("Enter a mathematical expression (e.g., 5 + 10): ");
fgets(expression, BUFFER_SIZE, stdin);
expression[strcspn(expression, "\n")] = 0; // Remove the newline character
// Send expression to the server
sendto(sockfd, expression, strlen(expression), 0, (const struct sockaddr *)&serv_addr, addr_len);
printf("Expression sent to server.\n");
// Receive result from the server
recvfrom(sockfd, &result, sizeof(result), 0, (struct sockaddr *)&serv_addr, &addr_len);
printf("Result received from server: %f\n", result);
close(sockfd);
return 0;
}
Stop and wait client
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 500
#define LOG_FILE "client_log.txt"
#define RESUME_FILE "client_resume.txt"
#define FILE_PATH_FILE "client_file_path.txt"
// Function to log transfer details
void log_transfer(const char *message) {
FILE *log_file = fopen(LOG_FILE, "a");
if (log_file == NULL) {
perror("Failed to open log file");
return;
}
fprintf(log_file, "%s\n", message);
fclose(log_file);
}
// Function to save the last sent sequence number for resumption
void save_last_seq(int seq_num) {
FILE *resume_file = fopen(RESUME_FILE, "w");
if (resume_file == NULL) {
perror("Failed to open resume file");
return;
}
fprintf(resume_file, "%d\n", seq_num);
fclose(resume_file);
}
// Function to load the last saved sequence number
int load_last_seq() {
FILE *resume_file = fopen(RESUME_FILE, "r");
if (resume_file == NULL) {
return 0; // Start from the beginning if no resume file exists
}
int seq_num;
fscanf(resume_file, "%d", &seq_num);
fclose(resume_file);
return seq_num;
}
// Function to save the file path for resumption
void save_file_path(const char *file_path) {
FILE *path_file = fopen(FILE_PATH_FILE, "w");
if (path_file == NULL) {
perror("Failed to open file path file");
return;
}
fprintf(path_file, "%s\n", file_path);
fclose(path_file);
}
// Function to load the saved file path
char *load_file_path() {
static char file_path[256];
FILE *path_file = fopen(FILE_PATH_FILE, "r");
if (path_file == NULL) {
return NULL; // No saved path; ask the user for a new one
}
fgets(file_path, sizeof(file_path), path_file);
fclose(path_file);
file_path[strcspn(file_path, "\n")] = '\0'; // Remove newline
return file_path;
}
// Function to extract the file extension from the file path
const char *get_file_extension(const char *file_path) {
const char *dot = strrchr(file_path, '.');
if (!dot || dot == file_path) {
return ""; // No extension found
}
return dot + 1; // Return extension without the dot
}
// Function to send file with Stop-and-Wait and resumption capability
void send_file(FILE *file, int sockfd, struct sockaddr_in *server_addr, const char *file_extension) {
char buffer[BUFFER_SIZE];
int seq_num = load_last_seq(); // Load last saved sequence number
socklen_t addr_len = sizeof(*server_addr);
int packets_sent = 0, timeouts = 0;
char ack[BUFFER_SIZE];
int n;
// Send file extension to server as the first message
sendto(sockfd, file_extension, strlen(file_extension), 0, (const struct sockaddr *)server_addr, addr_len);
log_transfer("File extension sent to server");
// Log start or resume time
log_transfer(seq_num == 0 ? "File transfer started" : "File transfer resumed");
// Move file pointer to the last position if resuming
fseek(file, seq_num * (BUFFER_SIZE - 8), SEEK_SET);
while (1) {
size_t bytes_read = fread(buffer + 8, 1, BUFFER_SIZE - 8, file);
if (bytes_read <= 0) {
break; // End of file
}
// Prepare packet with sequence number
snprintf(buffer, 8, "SEQ%04d", seq_num); // Prefix packet with sequence number
sendto(sockfd, buffer, bytes_read + 8, 0, (const struct sockaddr *)server_addr, addr_len);
packets_sent++;
// Log packet sent and save last sent sequence
char log_entry[128];
snprintf(log_entry, sizeof(log_entry), "Packet %d sent", seq_num);
log_transfer(log_entry);
save_last_seq(seq_num);
// Wait for acknowledgment
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv);
n = recvfrom(sockfd, ack, BUFFER_SIZE, 0, (struct sockaddr *)server_addr, &addr_len);
if (n < 0) {
// Timeout occurred, simulating connection drop
perror("Timeout, simulating connection drop");
timeouts++;
return; // Terminate to simulate disconnection
}
ack[n] = '\0';
// Check if acknowledgment matches sequence number
if (strstr(ack, "ACK") && atoi(ack + 4) == seq_num) {
printf("Received ACK for packet %d\n", seq_num);
seq_num++; // Move to the next packet
} else {
log_transfer("Acknowledgment mismatch, resending packet");
continue;
}
}
// Send end signal
strcpy(buffer, "END");
sendto(sockfd, buffer, strlen(buffer), 0, (const struct sockaddr *)server_addr, addr_len);
log_transfer("File transfer completed");
// Log summary and reset resume file for next transfer
log_transfer("File transfer completed successfully");
remove(RESUME_FILE); // Delete resume file since transfer is complete
}
int main() {
int sockfd;
struct sockaddr_in server_addr;
FILE *file;
char file_path[256];
// Load saved file path if it exists
char *saved_path = load_file_path();
if (saved_path != NULL) {
strcpy(file_path, saved_path);
printf("Resuming transfer for file: %s\n", file_path);
} else {
// Prompt user for file path if no saved path
printf("Enter the file path: ");
scanf("%s", file_path);
save_file_path(file_path); // Save the path for resumption
}
// Extract file extension
const char *file_extension = get_file_extension(file_path);
if (strlen(file_extension) == 0) {
fprintf(stderr, "Error: Unable to determine file extension.\n");
return 1;
}
// Open file to be sent in binary mode
file = fopen(file_path, "rb");
if (file == NULL) {
perror("File open failed");
return 1;
}
// Create UDP socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// Set server address
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
// Start or resume file transfer
send_file(file, sockfd, &server_addr, file_extension);
fclose(file);
close(sockfd);
// Remove saved file path on successful completion
remove(FILE_PATH_FILE);
return 0;
}
Stop and wait Server
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
#define LOG_FILE "server_log.txt"
// Function to log transfer details
void log_transfer(const char *message) {
FILE *log_file = fopen(LOG_FILE, "a");
if (log_file == NULL) {
perror("Failed to open log file");
return;
}
fprintf(log_file, "%s\n", message);
fclose(log_file);
}
int main() {
int sockfd;
struct sockaddr_in server_addr, client_addr;
char buffer[BUFFER_SIZE];
socklen_t addr_len = sizeof(client_addr);
int seq_num = 0;
// Create UDP socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// Set server address
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
// Bind socket to the server address
if (bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Bind failed");
close(sockfd);
exit(EXIT_FAILURE);
}
log_transfer("Server is ready to receive file...");
char file_extension[32] = "";
FILE *file = NULL;
while (1) {
// Receive data
int n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &addr_len);
if (n < 0) {
perror("Receiving data failed");
break;
}
buffer[n] = '\0';
// If file extension not yet received
if (file_extension[0] == '\0') {
strcpy(file_extension, buffer);
char filename[128];
snprintf(filename, sizeof(filename), "received_file.%s", file_extension);
// Open file with the correct extension
file = fopen(filename, "wb");
if (file == NULL) {
perror("File open failed");
close(sockfd);
return 1;
}
char log_entry[128];
snprintf(log_entry, sizeof(log_entry), "Receiving file with extension: %s", file_extension);
log_transfer(log_entry);
continue;
}
// Check for end signal
if (strncmp(buffer, "END", 3) == 0) {
log_transfer("File transfer completed");
printf("File received successfully.\n");
break;
}
// Write received data to file after stripping sequence number
fwrite(buffer + 8, 1, n - 8, file); // Adjust to skip the 8-byte sequence prefix
// Acknowledge received packet
snprintf(buffer, BUFFER_SIZE, "ACK%04d", seq_num++);
sendto(sockfd, buffer, strlen(buffer), 0, (const struct sockaddr *)&client_addr, addr_len);
// Log packet acknowledgment
char log_entry[128];
snprintf(log_entry, sizeof(log_entry), "Packet %d acknowledged", seq_num - 1);
log_transfer(log_entry);
}
if (file) {
fclose(file);
}
close(sockfd);
return 0;
}
Selective Repeat Protocol Sender(client)
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include arpa/inet.h>
#include unistd.h>
#include stdbool.h>
#include "sr_arq.h"
#define PORT 8080
void send_packet(int sockfd, struct sockaddr_in *addr, Packet *packet) {
sendto(sockfd, packet, sizeof(*packet), 0, (struct sockaddr *)addr, sizeof(*addr));
}
int main() {
int sockfd;
struct sockaddr_in server_addr;
socklen_t addr_len = sizeof(server_addr);
Packet window[WINDOW_SIZE] = {0};
bool acked[WINDOW_SIZE] = {false};
char filename[256];
// Ask user for the filename
printf("Enter the filename to send: ");
scanf("%255s", filename);
FILE *file = fopen(filename, "r");
if (!file) {
perror("File open failed");
return EXIT_FAILURE;
}
// Create socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Socket creation failed");
fclose(file);
return EXIT_FAILURE;
}
// Server address setup
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int base = 0, next_seq = 0, n;
char buffer[PACKET_SIZE];
while (1) {
// Fill the window with new packets if possible
while (next_seq < base + WINDOW_SIZE && (n = fread(buffer, 1, PACKET_SIZE, file)) > 0) {
Packet packet = { .seq_num = next_seq, .ack = false, .end = false };
memcpy(packet.data, buffer, n);
window[next_seq % WINDOW_SIZE] = packet;
send_packet(sockfd, &server_addr, &packet);
printf("Sent packet %d\n", next_seq);
next_seq++;
}
// Check for acknowledgments
Packet ack_packet;
if (recvfrom(sockfd, &ack_packet, sizeof(ack_packet), 0, (struct sockaddr *)&server_addr, &addr_len) > 0) {
if (ack_packet.ack) {
printf("Received ACK for packet %d\n", ack_packet.seq_num);
acked[ack_packet.seq_num % WINDOW_SIZE] = true;
}
}
// Slide the window if the base packet is acknowledged
while (acked[base % WINDOW_SIZE]) {
acked[base % WINDOW_SIZE] = false;
base++;
}
if (base >= next_seq) break; // All packets have been acknowledged
}
// Send end of transmission
Packet end_packet = { .seq_num = next_seq, .end = true };
send_packet(sockfd, &server_addr, &end_packet);
printf("Sent end of transmission\n");
close(sockfd);
fclose(file);
return 0;
}
Selective Repeat Protocol Receiver(server)
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include arpa/inet.h>
#include unistd.h>
#include "sr_arq.h"
#define PORT 8080
#define OUTPUT_FILE "output.txt"
int main() {
int sockfd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len = sizeof(client_addr);
Packet window[WINDOW_SIZE] = {0};
bool received[WINDOW_SIZE] = {false};
FILE *file = fopen(OUTPUT_FILE, "w");
if (!file) {
perror("File open failed");
return EXIT_FAILURE;
}
// Create socket
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("Socket creation failed");
fclose(file);
return EXIT_FAILURE;
}
// Server address setup
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// Bind the socket
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Bind failed");
close(sockfd);
fclose(file);
return EXIT_FAILURE;
}
int expected_seq = 0;
printf("Waiting for packets...\n");
while (1) {
Packet packet;
if (recvfrom(sockfd, &packet, sizeof(packet), 0, (struct sockaddr *)&client_addr, &client_len) < 0) {
perror("Receive failed");
break;
}
int seq_num = packet.seq_num;
if (seq_num >= expected_seq && seq_num < expected_seq + WINDOW_SIZE) {
received[seq_num % WINDOW_SIZE] = true;
window[seq_num % WINDOW_SIZE] = packet;
printf("Received packet %d\n", seq_num);
// Send acknowledgment
Packet ack_packet = { .seq_num = seq_num, .ack = true };
sendto(sockfd, &ack_packet, sizeof(ack_packet), 0, (struct sockaddr *)&client_addr, client_len);
printf("Sent ACK for packet %d\n", seq_num);
// Deliver packets to file if in order
while (received[expected_seq % WINDOW_SIZE]) {
fwrite(window[expected_seq % WINDOW_SIZE].data, 1, PACKET_SIZE, file);
received[expected_seq % WINDOW_SIZE] = false;
expected_seq++;
if (window[expected_seq % WINDOW_SIZE].end) {
printf("End of file reached\n");
fclose(file);
close(sockfd);
return 0;
}
}
} else {
printf("Out-of-order or duplicate packet %d\n", seq_num);
}
}
fclose(file);
close(sockfd);
return 0;
}
Selective Repeat Protocol Header
Click the button to copy this code:
#ifndef SR_ARQ_H
#define SR_ARQ_H
#include stdbool.h>
#define PACKET_SIZE 1024
#define WINDOW_SIZE 5
typedef struct {
int seq_num; // Sequence number of the packet
char data[PACKET_SIZE]; // Data payload
bool ack; // Acknowledgment flag
bool end; // End of transmission flag
} Packet;
#endif // SR_ARQ_H
udp client file transfer
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main()
{
int sock_fd;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
FILE *fp;
// Create socket
if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
printf("\nSocket creation error\n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported\n");
return -1;
}
// Request the file
char filename[256];
printf("Enter filename to request: ");
fgets(filename, sizeof(filename), stdin);
filename[strcspn(filename, "\n")] = 0; // Remove newline character
sendto(sock_fd, filename, strlen(filename), 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
fp = fopen("received_file", "wb"); // You can set a specific name if needed
if (fp == NULL)
{
perror("File not found");
return -1;
}
// Receive the file
size_t n;
while ((n = recvfrom(sock_fd, buffer, BUFFER_SIZE, 0, NULL, NULL)) > 0)
{
fwrite(buffer, sizeof(char), n, fp);
// Send acknowledgment
sendto(sock_fd, "ACK", 3, 0, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
}
printf("File received successfully.\n");
fclose(fp);
close(sock_fd);
return 0;
}
udp server file transfer
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s \n", argv[0]);
exit(EXIT_FAILURE);
}
int sock_fd;
struct sockaddr_in address;
char buffer[BUFFER_SIZE] = {0};
FILE *fp;
socklen_t addrlen = sizeof(address);
// Create socket
if ((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Set up address structure
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind the socket
if (bind(sock_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d...\n", PORT);
// Receive request for file
char client_address[INET_ADDRSTRLEN];
int bytes_received = recvfrom(sock_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&address, &addrlen);
buffer[bytes_received] = '\0'; // Null-terminate the received string
printf("Client requested file: %s\n", buffer);
// Open the requested file
fp = fopen(buffer, "rb");
if (fp == NULL)
{
perror("File not found");
return -1;
}
// Send the file
size_t n;
while ((n = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0)
{
sendto(sock_fd, buffer, n, 0, (struct sockaddr *)&address, addrlen);
// Wait for acknowledgment
recvfrom(sock_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&address, &addrlen);
}
printf("File sent successfully.\n");
fclose(fp);
close(sock_fd);
return 0;
}
FIle transfer tcp client
Click the button to copy this code:
#include
#include
#include
#include
#include
#include
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int client_socket;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
char file_name[BUFFER_SIZE];
// Create the socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
printf("Socket creation error\n");
return -1;
}
// Define the server address
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
printf("Invalid address/ Address not supported\n");
return -1;
}
// Connect to the server
if (connect(client_socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("Connection failed\n");
return -1;
}
// Request file name from the user
printf("Enter the file name to request from server: ");
scanf("%s", file_name);
// Send the file name to the server
send(client_socket, file_name, strlen(file_name), 0);
// Open a file to save the received data
FILE *file = fopen("received_file", "wb");
if (file == NULL) {
perror("File open error");
close(client_socket);
return 1;
}
// Receive the file in chunks and write to the file
size_t n;
while ((n = recv(client_socket, buffer, BUFFER_SIZE, 0)) > 0) {
fwrite(buffer, 1, n, file);
}
// Close the file and socket
fclose(file);
close(client_socket);
printf("File received successfully.\n");
return 0;
}#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#include sys/socket.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int client_socket;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
char file_name[BUFFER_SIZE];
// Create the socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
printf("Socket creation error\n");
return -1;
}
// Define the server address
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
printf("Invalid address/ Address not supported\n");
return -1;
}
// Connect to the server
if (connect(client_socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("Connection failed\n");
return -1;
}
// Request file name from the user
printf("Enter the file name to request from server: ");
scanf("%s", file_name);
// Send the file name to the server
send(client_socket, file_name, strlen(file_name), 0);
// Open a file to save the received data
FILE *file = fopen("received_file", "wb");
if (file == NULL) {
perror("File open error");
close(client_socket);
return 1;
}
// Receive the file in chunks and write to the file
size_t n;
while ((n = recv(client_socket, buffer, BUFFER_SIZE, 0)) > 0) {
fwrite(buffer, 1, n, file);
}
// Close the file and socket
fclose(file);
close(client_socket);
printf("File received successfully.\n");
return 0;
}
file transfer tcp server
Click the button to copy this code:
#include stdio.h>
#include stdlib.h>
#include string.h>
#include unistd.h>
#include arpa/inet.h>
#include sys/socket.h>
#include netinet/in.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_socket, new_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t addrlen = sizeof(client_addr);
char buffer[BUFFER_SIZE] = {0};
// Create socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Define the server address
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// Bind the socket to the network address and port
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
close(server_socket);
exit(EXIT_FAILURE);
}
// Start listening for incoming connections
if (listen(server_socket, 3) < 0) {
perror("listen failed");
close(server_socket);
exit(EXIT_FAILURE);
}
printf("Waiting for connections...\n");
// Accept an incoming connection
new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &addrlen);
if (new_socket < 0) {
perror("accept failed");
close(server_socket);
exit(EXIT_FAILURE);
}
// Read the file name from the client
read(new_socket, buffer, BUFFER_SIZE);
printf("File requested: %s\n", buffer);
// Open the requested file
FILE *file = fopen(buffer, "rb");
if (file == NULL) {
perror("File not found");
close(new_socket);
close(server_socket);
return 1;
}
// Send the file to the client in chunks
size_t n;
while ((n = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
send(new_socket, buffer, n, 0);
}
fclose(file);
close(new_socket);
close(server_socket);
printf("File sent successfully.\n");
return 0;
}
full_duplex.c
Click the button to copy this code:
//Standard Libraries
#include stdio.h>
#include stdlib.h>
#include string.h>
//Libraries necessary for networking / socket programming
#include netdb.h>
#include netinet/in.h>
#include sys/socket.h>
#include sys/types.h>
//Miscellaneous imports
#include pthread.h>//Header file for enabling multithreading
#include unistd.h> // read(), write(), close()
//Defining macros
#define MAX 80
#define PORT 8090
#define SA struct sockaddr
// Function designed for receiving messages from the client
void* receive_msg(void* args)
{
int connfd = *(int*)args; // Correct argument passing
char buff[MAX];
int n;
// infinite loop for chat
while(1){
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(connfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s", buff);
// if the message contains "exit", exit the loop
if (strncmp("exit", buff, 4) == 0) {
printf("Client disconnected...\n");
break;
}
}
return NULL;
}
// Function designed for sending messages to the client
void* send_msg(void* args)
{
int connfd = *(int*)args; // Correct argument passing
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// send the buffer to client
write(connfd, buff, sizeof(buff));
// if msg contains "exit" then server exits and chat ends
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
return NULL;
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("Server accepted the client...\n");
pthread_t send_thread, recv_thread;
// Function for chatting between client and server
pthread_create(&send_thread, NULL, send_msg, &connfd); // Create send thread
pthread_create(&recv_thread, NULL, receive_msg, &connfd); // Create receive thread
// Wait for both threads to finish
pthread_join(send_thread, NULL);
pthread_join(recv_thread, NULL);
// After chatting close the socket
close(sockfd);
return 0;
}
full_duplex_client.c
Click the button to copy this code:
// Standard Libraries
#include stdio.h>
#include stdlib.h>
#include string.h>
// Libraries necessary for networking / socket programming
#include netdb.h>
#include netinet/in.h>
#include sys/socket.h>
#include sys/types.h>
// Miscellaneous imports
#include pthread.h> // Header file for enabling multithreading
#include unistd.h> // read(), write(), close()
// Defining macros
#define MAX 80
#define PORT 8090
#define SA struct sockaddr
// Function designed for receiving messages from the server
void *receive_msg(void *args)
{
int sockfd = *(int *)args; // Correct argument passing
char buff[MAX];
int n;
// infinite loop for chat
while (1)
{
bzero(buff, MAX);
// read the message from server and copy it in buffer
read(sockfd, buff, sizeof(buff));
if (strlen(buff) > 0)
{
// print buffer which contains the server contents
printf("From server: %s", buff);
}
// exit if server sends "exit"
if (strncmp("exit", buff, 4) == 0)
{
printf("Server disconnected...\n");
break;
}
}
return NULL;
}
// Function designed for sending messages to the server
void *send_msg(void *args)
{
int sockfd = *(int *)args; // Correct argument passing
char buff[MAX];
int n;
// infinite loop for chat
for (;;)
{
bzero(buff, MAX);
n = 0;
// copy client message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// send the buffer to server
write(sockfd, buff, sizeof(buff));
// if msg contains "exit" then client exits and chat ends
if (strncmp("exit", buff, 4) == 0)
{
printf("Client Exit...\n");
break;
}
}
return NULL;
}
// Driver function
int main()
{
int sockfd;
struct sockaddr_in servaddr;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("Socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT); // Client connects to server's RECV_PORT
// connect the client socket to server socket
if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0)
{
printf("Connection with the server failed...\n");
exit(0);
}
else
printf("Connected to the server..\n");
pthread_t send_thread, recv_thread;
// Create send and receive threads for the client
pthread_create(&send_thread, NULL, send_msg, (void *)&sockfd); // Send thread
pthread_create(&recv_thread, NULL, receive_msg, (void *)&sockfd); // Receive thread
// Wait for both threads to finish
pthread_join(send_thread, NULL);
pthread_join(recv_thread, NULL);
// After chatting, close the socket
close(sockfd);
return 0;
}
multiserver
Click the button to copy this code:
#include stdio.h>
#include netdb.h>
#include netinet/in.h>
#include stdlib.h>
#include string.h>
#include sys/socket.h>
#include sys/types.h>
#include unistd.h> // read(), write(), close()
#include signal.h> // signal()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function to handle communication between client and server.
void func(int connfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
// read the message from client and copy it in buffer
read(connfd, buff, sizeof(buff));
// print buffer which contains the client contents
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
// and send that buffer to client
write(connfd, buff, sizeof(buff));
// if msg contains "exit" then server exit and chat ended.
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
close(connfd);
}
// Signal handler to reap zombie processes
void sigchld_handler(int signum)
{
// Wait for all child processes without blocking
// Reference: https://www.ibm.com/docs/en/zos/2.4.0?topic=functions-waitpid-wait-specific-child-process-end
/*
waitpid() is used to wait for a specific function.
Parameters are (pid_t pid, int *status, int options);
pid: Determines which child process(es) to wait for. Here, pid = -1 means wait for any process
status: Pointer to the variable where the status information of the child process is stored
options: Different options to modify the waitpid() function behaviour. WNOHANG Returns immediately if no child has exited, instead of blocking.
*/
while (waitpid(-1, NULL, WNOHANG) > 0)//checks if any child process has terminated. If any child has exited, the child ID is provided.
;//Loop is called as long as there are child processes that have exited
//This function is used to clean up terminated functions
/*
When a child process exits, it turns into a zombie process.
The system keeps a record of the child process’s termination status until the parent process reads (reaps) that status using wait() or waitpid().
If not reaped, zombie processes accumulate, consuming system resources.
*/
}
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
// Signal handler for SIGCHLD to handle zombie processes.
// Signal is a software generated interrupt (interrupts the process). It is sent by the OS because of various reasons.
// SIGCHLD is generated when a child process is terminated or stopped.
// Reference: https://www.geeksforgeeks.org/signals-c-language/
signal(SIGCHLD, sigchld_handler);//Calls the function sigchld_handler whenever SIGCHLD interrupt is received
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
} else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
// Binding newly created socket to given IP and verification
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
} else
printf("Socket successfully binded..\n");
// Now server is ready to listen and verification
if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
} else
printf("Server listening..\n");
len = sizeof(cli);
// Infinite loop to keep accepting clients
while (1) {
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
continue; // Don't exit, continue to wait for other clients
} else
printf("Server accepted a client...\n");
// Create a child process to handle this client
pid_t pid = fork();
if (pid == 0) {
// Child process
func(connfd); // Handle client communication
exit(0); // Exit child process after handling client
}
}
// Close the listening socket
close(sockfd);
return 0;
}
multiserver_client
Click the button to copy this code:
#include arpa/inet.h> // inet_addr()
#include netdb.h>
#include stdio.h>
#include stdlib.h>
#include string.h>
#include strings.h> // bzero()
#include sys/socket.h>
#include unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
send(sockfd, buff, sizeof(buff), 0);
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
if ((strncmp(buff, "exit", 4)) == 0) {
printf("Client Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
// socket create and verification
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// connect the client socket to server socket
if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr))
!= 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
// function for chat
func(sockfd);
// close the socket
close(sockfd);
}
threads_test.c
Click the button to copy this code:
#include pthread.h>//Header file for enabling multithreading
#include stdio.h>
#include stdlib.h>
#include unistd.h> //Header file for sleep(). man 3 sleep for details.
// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
void* other_thread(void* args)
{
for(int i=1;i<=10;i++)
{
printf("Other thread executed %d times\n",i);
//usleep sleeps for a specified number of microseconds, 1000000 microseconds=1 S
usleep(1000000);
}
}
void* number_printer(void* args)
{
for(int i = 0;i<10;i++){
printf("%d\n",i);
if(i==5){
pthread_t other;
pthread_create(&other, NULL, other_thread, NULL);//Creates a new thread after number 5 is printed, which performs the task defined in the "other_thread" function
pthread_join(other, NULL);//Waits for the "other" thread to end. Then the execution will continue
}
usleep(1500000);;
}
return NULL;
}
void* letter_printer(void* args)
{
for(char a = 'A';a<='Z';a++){
printf("%c\n",a);
usleep(2000000);;
}
return NULL;
}
int main()
{
pthread_t number_thread, letter_thread;//Two thread handles one for the number_printer function and the other for letter_printer function.
printf("Before Threads\n");
pthread_create(&number_thread, NULL, number_printer, NULL);//Creates thread that executes the number_printer function. Assigns this thread to the handle number_thread
pthread_create(&letter_thread, NULL, letter_printer, NULL);//Creates thread that executes the letter_printer function. Assigns this thread to the handle letter_thread
pthread_join(number_thread, NULL);//Waits till the number thread has stopped executing
printf("Reached end of number thread\n");
pthread_join(letter_thread, NULL);//Waits till the letter thread has stopped executing
printf("Reached end of letter thread\n");
printf("After Threads\n");
exit(0);
}
0 Comments
Reply me :