client_file_transfer.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #include <sys/socket.h>
  7. #include <fcntl.h>
  8. #define PORT 12345
  9. #define CHUNK_SIZE 1024
  10. void handle_error(const char *msg) {
  11. perror(msg);
  12. exit(1);
  13. }
  14. int main()
  15. {
  16. int client_fd, file_fd;
  17. struct sockaddr_in server_addr;
  18. char buffer[CHUNK_SIZE];
  19. char filename[256];
  20. ssize_t bytes_received, bytes_written;
  21. client_fd = socket(AF_INET, SOCK_STREAM, 0);
  22. if (client_fd < 0)
  23. {
  24. handle_error("Socket creation failed");
  25. }
  26. memset(&server_addr, 0, sizeof(server_addr));
  27. server_addr.sin_family = AF_INET;
  28. server_addr.sin_port = htons(PORT);
  29. if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)
  30. {
  31. handle_error("Invalid address");
  32. }
  33. if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
  34. {
  35. handle_error("Connection failed");
  36. }
  37. // Ask for the filename from the user
  38. printf("Enter the filename you want to request: ");
  39. fgets(filename, sizeof(filename), stdin);
  40. filename[strcspn(filename, "\n")] = 0; // Remove newline character
  41. // Send the filename to the server
  42. if (send(client_fd, filename, strlen(filename), 0) < 0)
  43. {
  44. handle_error("Failed to send filename");
  45. }
  46. // Open a file to write the received data
  47. strcpy(filename, "HelloWorld.txt");
  48. file_fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
  49. if (file_fd < 0)
  50. {
  51. handle_error("File creation failed");
  52. }
  53. // Receive the file in chunks and write to disk
  54. while ((bytes_received = recv(client_fd, buffer, CHUNK_SIZE, 0)) > 0)
  55. {
  56. bytes_written = write(file_fd, buffer, bytes_received);
  57. if (bytes_written < 0)
  58. {
  59. perror("Write to file failed");
  60. break;
  61. }
  62. }
  63. if (bytes_received < 0)
  64. {
  65. perror("Receive failed");
  66. } else {
  67. printf("File received successfully\n");
  68. }
  69. close(file_fd);
  70. close(client_fd);
  71. return 0;
  72. }