diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..589e6c1 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,4 @@ +*.o +compile_flags.txt +server + diff --git a/backend/Makefile b/backend/Makefile new file mode 100644 index 0000000..1e1df18 --- /dev/null +++ b/backend/Makefile @@ -0,0 +1,19 @@ + +CFLAGS = -std=c17 -Wall -Wextra -Wpedantic -Wconversion + +HEADERS = $(wildcard *.h) + +all: compile_flags.txt server + +server: main.o + gcc $^ -o $@ + +%.o: %.c $(HEADERS) + gcc $< -c -o $@ $(CFLAGS) + +clean: + rm -rf *.o server client + +compile_flags.txt: + echo -xc $(CFLAGS) | sed 's/\s\+/\n/g' > compile_flags.txt + diff --git a/backend/main.c b/backend/main.c new file mode 100644 index 0000000..96c0d26 --- /dev/null +++ b/backend/main.c @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +#include + +const uint16_t port = 8000; + +int main(void) +{ + printf("starting server...\n"); + int server_socket = socket(AF_INET, SOCK_STREAM, 0); + if (server_socket < 0) { + printf("error: could not open socket\n"); + return 1; + } + struct sockaddr_in server; + server.sin_addr.s_addr = inet_addr("127.0.0.1"); + server.sin_family = AF_INET; + server.sin_port = htons(port); + if (bind(server_socket, (struct sockaddr*)&server, sizeof(server)) > 0) { + printf("error: could not bind socket\n"); + return 1; + } + if (listen(server_socket, SOMAXCONN) < 0) { + printf("error: could not listen on server"); + return 1; + } + printf("listening on port %d\n", port); + + while (true) { + struct sockaddr_in client; + socklen_t client_size; + printf("waiting for client...\n"); + int client_socket = accept(server_socket, (struct sockaddr*)&client, &client_size); + if (client_socket < 0) { + printf("error: could not accept connection\n"); + continue; + } + printf("client connected\n"); + while (true) { + uint8_t buffer[8192] = { 0 }; + ssize_t read_size = recv(client_socket, buffer, 8192, 0); + if (read_size < 0) { + printf("error: could not recieve\n"); + break; + } else if (read_size == 0) { + printf("client disconnected\n"); + break; + } + printf("recieved:\n%s\n", buffer); + uint8_t send_buffer[] + = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "hej med " + "dig

fuck c hashtag

\r\n" + "\r\n"; + ssize_t written = write(client_socket, send_buffer, sizeof(send_buffer)); + if (written < 0) { + printf("error: could not write\n"); + continue; + } + printf("disconnecting client\n"); + close(client_socket); + } + } + + return 0; +}