123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #include <sys/socket.h>
- #include <fcntl.h>
- #define PORT 12345
- #define CHUNK_SIZE 1024
- void handle_error(const char *msg) {
- perror(msg);
- exit(1);
- }
- int main()
- {
- int server_fd, client_fd, file_fd;
- struct sockaddr_in server_addr, client_addr;
- socklen_t client_len;
- char buffer[CHUNK_SIZE];
- char filename[256];
- ssize_t bytes_read, bytes_sent;
- server_fd = socket(AF_INET, SOCK_STREAM, 0);
- if (server_fd < 0)
- {
- handle_error("Socket creation failed");
- }
- memset(&server_addr, 0, sizeof(server_addr));
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = INADDR_ANY;
- server_addr.sin_port = htons(PORT);
- if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
- {
- handle_error("Bind failed");
- }
- if (listen(server_fd, 5) < 0)
- {
- handle_error("Listen failed");
- }
- printf("Server listening on port %d...\n", PORT);
- while (1)
- {
- client_len = sizeof(client_addr);
- client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
- if (client_fd < 0)
- {
- perror("Accept failed");
- continue;
- }
- printf("Client connected\n");
- // Receive the filename request from the client
- memset(filename, 0, sizeof(filename));
- if (recv(client_fd, filename, sizeof(filename), 0) <= 0)
- {
- perror("Failed to receive filename");
- close(client_fd);
- continue;
- }
- // Open the file requested by the client
- file_fd = open(filename, O_RDONLY);
- if (file_fd < 0)
- {
- perror("File not found");
- close(client_fd);
- continue;
- }
- // Send the file in chunks
- while ((bytes_read = read(file_fd, buffer, CHUNK_SIZE)) > 0) {
- bytes_sent = send(client_fd, buffer, bytes_read, 0);
- if (bytes_sent < 0)
- {
- perror("Send failed");
- close(file_fd);
- close(client_fd);
- break;
- }
- }
- if (bytes_read < 0) {
- perror("File read failed");
- } else {
- printf("File sent successfully\n");
- }
- close(file_fd);
- close(client_fd);
- }
- close(server_fd);
- return 0;
- }
|