Skip to content

Instantly share code, notes, and snippets.

@momori256

momori256/sock.c Secret

Created February 24, 2023 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save momori256/04e81bbdb08a5a73500d3ebecb8c06dc to your computer and use it in GitHub Desktop.
Save momori256/04e81bbdb08a5a73500d3ebecb8c06dc to your computer and use it in GitHub Desktop.
sock.c:sock_create
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