server_file_transfer.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 server_fd, client_fd, file_fd;
  17. struct sockaddr_in server_addr, client_addr;
  18. socklen_t client_len;
  19. char buffer[CHUNK_SIZE];
  20. char filename[256];
  21. ssize_t bytes_read, bytes_sent;
  22. server_fd = socket(AF_INET, SOCK_STREAM, 0);
  23. if (server_fd < 0)
  24. {
  25. handle_error("Socket creation failed");
  26. }
  27. memset(&server_addr, 0, sizeof(server_addr));
  28. server_addr.sin_family = AF_INET;
  29. server_addr.sin_addr.s_addr = INADDR_ANY;
  30. server_addr.sin_port = htons(PORT);
  31. if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
  32. {
  33. handle_error("Bind failed");
  34. }
  35. if (listen(server_fd, 5) < 0)
  36. {
  37. handle_error("Listen failed");
  38. }
  39. printf("Server listening on port %d...\n", PORT);
  40. while (1)
  41. {
  42. client_len = sizeof(client_addr);
  43. client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
  44. if (client_fd < 0)
  45. {
  46. perror("Accept failed");
  47. continue;
  48. }
  49. printf("Client connected\n");
  50. // Receive the filename request from the client
  51. memset(filename, 0, sizeof(filename));
  52. if (recv(client_fd, filename, sizeof(filename), 0) <= 0)
  53. {
  54. perror("Failed to receive filename");
  55. close(client_fd);
  56. continue;
  57. }
  58. // Open the file requested by the client
  59. file_fd = open(filename, O_RDONLY);
  60. if (file_fd < 0)
  61. {
  62. perror("File not found");
  63. close(client_fd);
  64. continue;
  65. }
  66. // Send the file in chunks
  67. while ((bytes_read = read(file_fd, buffer, CHUNK_SIZE)) > 0) {
  68. bytes_sent = send(client_fd, buffer, bytes_read, 0);
  69. if (bytes_sent < 0)
  70. {
  71. perror("Send failed");
  72. close(file_fd);
  73. close(client_fd);
  74. break;
  75. }
  76. }
  77. if (bytes_read < 0) {
  78. perror("File read failed");
  79. } else {
  80. printf("File sent successfully\n");
  81. }
  82. close(file_fd);
  83. close(client_fd);
  84. }
  85. close(server_fd);
  86. return 0;
  87. }