Lab 6 - cs22b2002
Lab 6 - cs22b2002
Assignment
CS22B2043
B.RITESH
KUMAR
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include
<arpa/inet.h>
if (fp == NULL) {
printf("File not found. Creating a new
file...\n"); fp = fopen(filename, "w");
if (fp == NULL) {
perror("Error creating new file");
exit(1);
}
fprintf(fp, "This is a newly created file that is being sent
to the client.\n");
fclose(fp);
fp = fopen(filename, "r");
}
char buffer[BUFFER_SIZE] =
{0}; int bytes_received;
printf("Receiving file from client and saving as %s:\n", filename);
int main() {
int server_fd, new_socket;
struct sockaddr_in
address; int addrlen =
sizeof(address);
char buffer[BUFFER_SIZE] =
{0}; char
filename[BUFFER_SIZE]; char
operation[10];
// Creating socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0))
== 0) { perror("Socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (strcmp(operation, "REǪUEST") == 0) {
// Receive file request from the client
recv(new_socket, buffer,
BUFFER_SIZE, 0); printf("Client
requested file: %s\n", buffer);
strcpy(filename, buffer);
close(new_socket);
close(server_fd);
return 0;
}
Client code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include
<arpa/inet.h>
fp = fopen(filename,
"w"); if (fp == NULL) {
perror("Error opening file");
exit(1);
}
int main() {
int sock = 0;
struct sockaddr_in
serv_addr; char
filename[BUFFER_SIZE];
int choice;
// Creating socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Socket creation error");
exit(EXIT_FAILURE);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
if (choice == 1) {
// Request a file from the server
printf("Enter the filename to request from the
server: "); if (scanf("%s", filename) != 1) {
fprintf(stderr, "Error reading filename\n");
exit(EXIT_FAILURE);
}
send(sock, "REǪUEST", sizeof("REǪUEST"), 0); // Notify server
for download
send(sock, filename, sizeof(filename), 0); // Send filename to
the server
} else if (choice == 2) {
// Send a file to the server
printf("Enter the filename to send to the
server: "); if (scanf("%s", filename) != 1) {
fprintf(stderr, "Error reading filename\n");
exit(EXIT_FAILURE);
}
send(sock, "UPLOAD", sizeof("UPLOAD"), 0); // Notify server for
upload send(sock, filename, sizeof(filename), 0); // Send
filename to the
server
close(sock
); return 0;
}
Server to client
Output at server
Output at client
Client to server
Server output
Client output