mini-web-server/main.c

52 lines
1.1 KiB
C

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/sendfile.h>
int main() {
int port = 8080;
int server_soc = socket(AF_INET, SOCK_STREAM, 0);
if (server_soc == -1) {
printf("ERROR: Failed to open socket: %s", strerror(errno));
return -1;
}
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(port),
.sin_addr = 0
};
if (bind(server_soc, (struct sockaddr*)&addr, sizeof(addr))) {
printf("ERROR: Failed to bind: %s", strerror(errno));
return -1;
}
if (listen(server_soc, 10)) {
printf("ERROR: Failed to listen: %s", strerror(errno));
return -1;
}
int client_soc = accept(server_soc, NULL, NULL);
char buffer[256];
int byte_count = recv(client_soc, buffer, sizeof(buffer), 0);
char *filename = buffer + 5;
char *space = strchr(filename, ' ');
space[0] = 0;
int file_fd = open(filename, O_RDONLY);
sendfile(client_soc, file_fd, 0, 256);
close(file_fd);
close(client_soc);
close(server_soc);
return 0;
}