Skip to content

Commit 147b4da

Browse files
committed
Now allocating the requested file data on the heap, hopefully shouldn't have a size limit
1 parent 67b04e8 commit 147b4da

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/main.c

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ void handle_client_request(int client_fd) {
5858
buffer[bytes_received] = '\0'; // Null-terminate the received data
5959
printf("Received request: %s\n", buffer);
6060

61-
// This server will only accept GET requests
61+
// This server will only accept GET requests
6262
// GET /index.html for example
6363
char* file = buffer + 5; // Skip "GET /"
6464
*strchr(file, ' ') = '\0'; // Null-terminate at the first space
@@ -79,14 +79,29 @@ void handle_client_request(int client_fd) {
7979
// Get the file size
8080
off_t file_size = lseek(file_fd, 0, SEEK_END);
8181
lseek(file_fd, 0, SEEK_SET); // Reset the file offset
82+
if (file_size < 0) {
83+
perror("lseek failed");
84+
close(file_fd);
85+
close(client_fd);
86+
return;
87+
}
88+
void* file_data = malloc(file_size); // Allocate memory for the file file_data
89+
if (read(file_fd, file_data, file_size) != file_size) {
90+
perror("File read failed");
91+
free(file_data);
92+
close(file_fd);
93+
close(client_fd);
94+
return;
95+
}
96+
8297
// Create the response header
8398
char response[256];
8499
snprintf(response, sizeof(response), "%s%ld\r\n\r\n", response_header, file_size);
85100
// Send the response header
86101
send(client_fd, response, strlen(response), 0);
87102
// 7. Send the response back to the client
88103
printf("Sending file of size %ld bytes\n", file_size);
89-
sendfile(client_fd, file_fd, NULL, 256); // Send the file to the client
104+
send(client_fd, file_data, file_size, 0); // Send the file to the client
90105
printf("File sent successfully\n");
91106
close(file_fd); // Close the file descriptor
92107
close(client_fd); // Close the client socket

0 commit comments

Comments
 (0)