From 6447ae983129ba6747aa7743e5c19c8e775d17bc Mon Sep 17 00:00:00 2001 From: Rokas Puzonas Date: Thu, 7 Dec 2023 00:10:28 +0200 Subject: [PATCH] complete tutorial from video --- README.md | 5 +++++ index.html | 1 + main.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 index.html create mode 100644 main.c diff --git a/README.md b/README.md index 3f0f844..511c83b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,9 @@ # Minimal Web Server +``` +gcc -o main main.c +./main +``` + Original tutorial: https://www.youtube.com/watch?v=2HrYIl6GpYg diff --git a/index.html b/index.html new file mode 100644 index 0000000..1574e1b --- /dev/null +++ b/index.html @@ -0,0 +1 @@ +

Hello, World!

diff --git a/main.c b/main.c new file mode 100644 index 0000000..e410891 --- /dev/null +++ b/main.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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; +}