diff options
author | Johnny Richard <johnny@johnnyrichard.com> | 2022-04-07 14:36:21 +0200 |
---|---|---|
committer | Johnny Richard <johnny@johnnyrichard.com> | 2022-04-07 14:36:21 +0200 |
commit | 33e14b74df70ecbfcdb56b71a0ea7d4f1e05b1f4 (patch) | |
tree | 46b8d456a6eda31b90ec1b2282bc696e03bd7f86 /server.c | |
parent | b3b3d2f7a9365a1c9c4ccdf9ffa8f0bcf83f1080 (diff) |
server.c: Create server struct
Diffstat (limited to 'server.c')
-rw-r--r-- | server.c | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/server.c b/server.c new file mode 100644 index 0000000..d7edb04 --- /dev/null +++ b/server.c @@ -0,0 +1,41 @@ +#include "server.h" + +#include <netinet/in.h> +#include <stdio.h> +#include <stdlib.h> +#include <sys/socket.h> +#include <unistd.h> + +server_t +server_create(uint32_t port) +{ + int server_fd = socket(AF_INET, SOCK_STREAM, 0); + if (server_fd == -1) { + perror("[ERROR] unable to create a socket"); + exit(EXIT_FAILURE); + } + + struct sockaddr_in server; + server.sin_addr.s_addr = htonl(INADDR_ANY); + server.sin_family = AF_INET; + server.sin_port = htons(port); + + int opt_val = 1; + setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt_val, sizeof(opt_val)); + + if (bind(server_fd, (struct sockaddr *) &server, sizeof(server)) == -1) { + perror("[ERROR] could not bind"); + close(server_fd); + exit(EXIT_FAILURE); + } + + if (listen(server_fd, SOMAXCONN) == -1) { + perror("[ERROR] could not listen"); + close(server_fd); + exit(EXIT_FAILURE); + } + + printf("[INFO] server listening at port (%d)\n", port); + + return (server_t) { .fd = server_fd }; +} |