add backend

This commit is contained in:
Simon 2023-02-09 10:25:15 +01:00
parent 489e16eea3
commit 19fc5a2791
3 changed files with 95 additions and 0 deletions

4
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
*.o
compile_flags.txt
server

19
backend/Makefile Normal file
View File

@ -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

72
backend/main.c Normal file
View File

@ -0,0 +1,72 @@
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
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"
"<!DOCTYPE><html><head><meta charset=\"utf-8\"><title>hej med "
"dig</title></head><body><h1>fuck c hashtag</h1></body></html>\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;
}