#include #include #include #include #include #include #include #define PORT 12345 #define CHUNK_SIZE 1024 void handle_error(const char *msg) { perror(msg); exit(1); } int main() { int client_fd, file_fd; struct sockaddr_in server_addr; char buffer[CHUNK_SIZE]; char filename[256]; ssize_t bytes_received, bytes_written; client_fd = socket(AF_INET, SOCK_STREAM, 0); if (client_fd < 0) { handle_error("Socket creation failed"); } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) { handle_error("Invalid address"); } if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { handle_error("Connection failed"); } // Ask for the filename from the user printf("Enter the filename you want to request: "); fgets(filename, sizeof(filename), stdin); filename[strcspn(filename, "\n")] = 0; // Remove newline character // Send the filename to the server if (send(client_fd, filename, strlen(filename), 0) < 0) { handle_error("Failed to send filename"); } // Open a file to write the received data strcpy(filename, "HelloWorld.txt"); file_fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (file_fd < 0) { handle_error("File creation failed"); } // Receive the file in chunks and write to disk while ((bytes_received = recv(client_fd, buffer, CHUNK_SIZE, 0)) > 0) { bytes_written = write(file_fd, buffer, bytes_received); if (bytes_written < 0) { perror("Write to file failed"); break; } } if (bytes_received < 0) { perror("Receive failed"); } else { printf("File received successfully\n"); } close(file_fd); close(client_fd); return 0; }