-
-
Save momori256/04e81bbdb08a5a73500d3ebecb8c06dc to your computer and use it in GitHub Desktop.
sock.c:sock_create
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
int sock_create(const char* const port, int backlog) { | |
typedef struct addrinfo addrinfo; | |
addrinfo hints = {0}; | |
{ | |
hints.ai_family = AF_INET; // IPv4. | |
hints.ai_socktype = SOCK_STREAM; // TCP. | |
hints.ai_flags = AI_PASSIVE; // Server. | |
} | |
addrinfo* head; | |
{ | |
const int result = getaddrinfo(NULL, port, &hints, &head); | |
if (result) { | |
fprintf(stderr, "getaddrinfo. err[%s]\n", gai_strerror(result)); | |
exit(1); | |
} | |
} | |
int sfd = 0; | |
for (addrinfo* p = head; p != NULL; p = p->ai_next) { | |
sfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); | |
if (sfd == -1) { | |
continue; | |
} | |
int val = 1; | |
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) == -1) { | |
error("setsockopt"); | |
} | |
if (bind(sfd, p->ai_addr, p->ai_addrlen) == -1) { | |
close(sfd); | |
continue; | |
} | |
break; | |
} | |
freeaddrinfo(head); | |
if (!sfd) { | |
error("socket, bind"); | |
} | |
if (listen(sfd, backlog) == -1) { | |
error("listen"); | |
} | |
return sfd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment