Skip to content

Instantly share code, notes, and snippets.

@mildsunrise
Last active September 16, 2017 23:40
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 mildsunrise/e0ea7f0bb6d281e8289e to your computer and use it in GitHub Desktop.
Save mildsunrise/e0ea7f0bb6d281e8289e to your computer and use it in GitHub Desktop.
Modern way to bind a socket to a port

Simple function that takes a socket type and a port, and returns a new socket of that type, bound to that port on the wildcard address (on either IPv4 or IPv6).

This is the modern way to create a socket that will accept connections from other hosts. You use it like that:

int my_socket = bound_socket(SOCK_DGRAM, 8080);
if (my_socket == -1) {
  // Failed to get (or bind) socket
}

Note: if it doesn't compile, you may need to define the feature flags for getaddrinfo or change the standard.

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int bound_socket(int socktype, uint16_t port) {
char port_str [8];
struct addrinfo hints;
struct addrinfo *result, *rp;
/* Get the possible bind addresses */
memset(&hints, 0x00, sizeof (struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = socktype;
hints.ai_flags = AI_PASSIVE;
sprintf(port_str, "%u", port);
if (getaddrinfo(NULL, port_str, &hints, &result))
return -1;
/* Try to bind to each address until one works */
for (rp = result; rp != NULL; rp = rp->ai_next) {
int sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) continue;
if (bind(sock, rp->ai_addr, rp->ai_addrlen) == 0) {
freeaddrinfo(result);
return sock;
}
close(sock);
}
/* Couldn't bind */
freeaddrinfo(result);
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment