diff options
author | Johnny Richard <johnny@johnnyrichard.com> | 2022-04-07 14:49:44 +0200 |
---|---|---|
committer | Johnny Richard <johnny@johnnyrichard.com> | 2022-04-07 14:54:39 +0200 |
commit | 1b684971c3b591538c3ba0d3343ec76559f10203 (patch) | |
tree | 575f66a3b7543cc970eceee1ec8ed8319fd4599e /server.c | |
parent | 33e14b74df70ecbfcdb56b71a0ea7d4f1e05b1f4 (diff) |
server.c: Move accept syscall to server_listen function
Diffstat (limited to 'server.c')
-rw-r--r-- | server.c | 64 |
1 files changed, 64 insertions, 0 deletions
@@ -1,11 +1,32 @@ +/* + * Papo IRC Server + * Copyright (C) 2021 Johnny Richard + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ #include "server.h" #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> +#include <string.h> #include <sys/socket.h> #include <unistd.h> +#define BUFFER_SIZE 1024 +#define EXIT_COMMAND "exit" + server_t server_create(uint32_t port) { @@ -39,3 +60,46 @@ server_create(uint32_t port) return (server_t) { .fd = server_fd }; } + +void +server_listen(server_t *server) +{ + struct sockaddr_in client; + socklen_t client_len = sizeof(client); + + server->running = true; + + while (server->running) { + int client_fd = accept(server->fd, (struct sockaddr *) &client, &client_len); + if (client_fd == -1) { + perror("[ERROR] could not accept connection"); + close(server->fd); + exit(EXIT_FAILURE); + } + while (true) { + char client_buf[BUFFER_SIZE]; + memset(client_buf, 0, BUFFER_SIZE); + + if (recv(client_fd, client_buf, BUFFER_SIZE, 0) == -1) { + perror("[ERROR] could not read data from client"); + continue; + } + + if (!strncasecmp(client_buf, EXIT_COMMAND, strlen(EXIT_COMMAND) - 1)) { + puts("[INFO] exiting program. bye bye!"); + close(client_fd); + close(server->fd); + exit(EXIT_SUCCESS); + } + + if (send(client_fd, client_buf, BUFFER_SIZE, 0) == -1) { + perror("[ERROR] could not send data to client"); + continue; + } + } + + close(client_fd); + close(server->fd); + exit(EXIT_SUCCESS); + } +} |