Created
December 7, 2016 10:25
-
-
Save pudelkoM/e9e58882657e6925fc261153ce78dcbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#ifndef fatal | |
#define fatal(msg) \ | |
do { fprintf(stderr, "[FATAL]: %s:%i: %s: %s\n", __func__, __LINE__, msg, strerror(errno)); exit(EXIT_FAILURE); } while (0) | |
#endif | |
int create_bound_socket(const sa_family_t domain, const int protocol, const char* ip, const char* port) { | |
struct addrinfo hints = {0}; | |
hints.ai_family = domain; | |
hints.ai_socktype = protocol; | |
if (!ip) | |
hints.ai_flags = AI_PASSIVE; | |
struct addrinfo* result; | |
int status = getaddrinfo(ip, port, &hints, &result); | |
if (status != 0) { | |
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); | |
exit(EXIT_FAILURE); | |
} | |
int socket_fd = -1; | |
struct addrinfo* rp; | |
for (rp = result; rp != NULL; rp = rp->ai_next) { | |
socket_fd = socket(rp->ai_family, rp->ai_socktype | SOCK_NONBLOCK, rp->ai_protocol); | |
if (socket_fd == -1) | |
continue; | |
int reuse = true; | |
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) | |
continue; | |
if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse)) == -1) | |
continue; | |
struct linger linger = {1, 1}; | |
if (setsockopt(socket_fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger)) == -1) | |
continue; | |
if (rp->ai_protocol == SOCK_STREAM) { | |
int keepalive = true; | |
if (setsockopt(socket_fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) == -1) | |
continue; | |
} | |
if (bind(socket_fd, rp->ai_addr, rp->ai_addrlen) == 0) | |
break; /* Success */ | |
close(socket_fd); | |
} | |
if (rp == NULL) { /* No address succeeded */ | |
fatal("Could not bind"); | |
} | |
freeaddrinfo(result); /* No longer needed */ | |
if (protocol == SOCK_STREAM || protocol == SOCK_SEQPACKET) { | |
if (listen(socket_fd, 64) == -1) | |
fatal("listen"); | |
} | |
return socket_fd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment