C-Webserver/src/server.c
2025-03-13 13:11:35 +01:00

60 lines
1.7 KiB
C

#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "../include/server.h"
// This code has been borrowed from this github repo https://bruinsslot.jp/post/simple-http-webserver-in-c/ and modified by me.
#define PORT 3090
#define BUFFER_SIZE 1024
void serve(struct setup s) {
char buffer[BUFFER_SIZE];
for (;;) {
// Accept incoming connections
int newsockfd = accept(s.sockfd, (struct sockaddr *)&s.host_addr, (socklen_t *)&s.host_addrlen);
if (newsockfd < 0) {
perror("webserver (accept)");
continue;
}
printf("connection accepted\n");
// Get client address
int sockn = getsockname(newsockfd, (struct sockaddr *)&s.client_addr, (socklen_t *)&s.client_addrlen);
if (sockn < 0) {
perror("webserver (getsockname)");
continue;
}
// Read from the socket
int valread = read(newsockfd, buffer, BUFFER_SIZE);
if (valread < 0) {
perror("webserver (read)");
continue;
}
// Read the request
char method[BUFFER_SIZE], uri[BUFFER_SIZE], version[BUFFER_SIZE];
sscanf(buffer, "%s %s %s", method, uri, version);
printf("[%s:%u] %s %s %s\n", inet_ntoa(s.client_addr.sin_addr), ntohs(s.client_addr.sin_port), method, version, uri);
// Write to the socket
int valwrite = write(newsockfd, s.response, strlen(s.response));
if (valwrite < 0) {
perror("webserver (write)");
continue;
}
close(newsockfd);
}
}