diff options
author | Toni Uhlig <matzeton@googlemail.com> | 2018-04-13 21:23:34 +0200 |
---|---|---|
committer | Toni Uhlig <matzeton@googlemail.com> | 2018-04-13 21:23:34 +0200 |
commit | ecf35293f80bba8b83a0dbf28f097812aa4353cb (patch) | |
tree | 51f8dea80d0fda06e85b2f910f76a9ea872d2fa5 /src/socket.c | |
parent | 0e9015400269e004d8dbe006d47fa9e4556603ec (diff) |
POTD skeleton #3.
Diffstat (limited to 'src/socket.c')
-rw-r--r-- | src/socket.c | 29 |
1 files changed, 25 insertions, 4 deletions
diff --git a/src/socket.c b/src/socket.c index 7edbda2..e7a4e2d 100644 --- a/src/socket.c +++ b/src/socket.c @@ -1,5 +1,6 @@ #include <stdio.h> #include <unistd.h> +#include <string.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> @@ -9,7 +10,7 @@ #include "socket.h" -static int socket_nonblock(psocket *psocket) +static int socket_nonblock(const psocket *psocket) { int flags; @@ -25,10 +26,12 @@ static int socket_nonblock(psocket *psocket) int socket_init_in(psocket *psocket, const char *listen_addr, const char *listen_port, struct addrinfo **results) { - struct addrinfo hints = {0}; + struct addrinfo hints; assert(psocket); assert(listen_addr || listen_port); /* getaddrinfo wants either node or service */ + + memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; /* IPV4 && IPV6 */ hints.ai_socktype = SOCK_STREAM; /* TCP */ hints.ai_flags = AI_PASSIVE; /* all interfaces */ @@ -38,7 +41,7 @@ int socket_init_in(psocket *psocket, const char *listen_addr, int socket_bind_in(psocket *psocket, struct addrinfo *results) { - int fd = -1, rv; + int fd = -1, rv, reuse_enable = 1; struct addrinfo *rp = NULL; assert(psocket && results); @@ -48,7 +51,7 @@ int socket_bind_in(psocket *psocket, struct addrinfo *results) if (fd < 0) continue; rv = bind(fd, rp->ai_addr, rp->ai_addrlen); - if (!rv) + if (!rv) break; close(fd); } @@ -56,6 +59,8 @@ int socket_bind_in(psocket *psocket, struct addrinfo *results) if (!rp) return -1; + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_enable, sizeof(int)) < 0) + return -2; psocket->fd = fd; psocket->addr = *rp; freeaddrinfo(results); @@ -68,3 +73,19 @@ int socket_listen_in(psocket *psocket) return listen(psocket->fd, POTD_BACKLOG); } + +int socket_accept_in(const psocket *psocket, struct sockaddr_in *clientaddr) +{ + int fd; + socklen_t addr_len = {0}; + + assert(psocket && clientaddr); + + fd = accept(psocket->fd, (struct sockaddr*) clientaddr, &addr_len); + if (fd < 0) + return -1; + if (socket_nonblock(psocket)) + return -2; + + return fd; +} |