nserver

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | LICENSE

commit e78e0638aae1e0fde710a3b4a782ea3bd7fde1c7
parent 0c5b08ea58f88252e950ecaf40125a22b79fa83c
Author: rsiddharth <s@ricketyspace.net>
Date:   Sun, 15 Sep 2019 13:51:02 -0400

nserver: Add nsocket.h

Diffstat:
nserver/src/nsocket.c | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
nserver/src/nsocket.h | 8++++++++
2 files changed, 60 insertions(+), 0 deletions(-)

diff --git a/nserver/src/nsocket.c b/nserver/src/nsocket.c @@ -0,0 +1,52 @@ +#include <sys/types.h> +#include <sys/socket.h> +#include <netdb.h> + +#include <dbg.h> +#include <nsocket.h> + +int get_socket() +{ + int sockfd = 0; + int rc = 0; + + struct addrinfo hints; + struct addrinfo *servinfo = NULL; + struct addrinfo *addr = NULL; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + + rc = getaddrinfo(NULL, PORT, &hints, &servinfo); + check(rc == 0, "get_socket: getaddrinfo failed"); + + // Loop through the addresses and find one that works. + sockfd = 0; + addr = servinfo; + do { + sockfd = socket(addr->ai_family, addr->ai_socktype, + addr->ai_protocol); + if (sockfd > 0) { + break; + } + + addr = addr->ai_next; + } while(addr); + check(sockfd > 0, "unable to get socket"); + + // assign name to socket. + rc = bind(sockfd, addr->ai_addr, addr->ai_addrlen); + check(rc == 0, "get_socket: bind failed"); + + // Cleanup. + freeaddrinfo(servinfo); + + return sockfd; + error: + if (servinfo) + freeaddrinfo(servinfo); + + return -1; +} diff --git a/nserver/src/nsocket.h b/nserver/src/nsocket.h @@ -0,0 +1,8 @@ +#ifndef _nsocket_h +#define _nsocket_h + +#define PORT "7899" + +int get_socket(); + +#endif