Skip to content
Visual explainer 3h 30m to learn 4 steps

Sockets API, addresses & byte order

Resolve hosts with getaddrinfo and convert addresses and byte order correctly.

By Invicly Tech, , in Linux System Programming. About 12 minutes to read.

Topic 32 of 42

In short

A socket is a descriptor for a network endpoint, created with socket and then bound, connected or set to listen. Addresses are described by structs such as sockaddr_in and sockaddr_in6, and multi-byte numbers on the wire use big-endian network byte order. getaddrinfo resolves names and fills those structs for IPv4 and IPv6 alike.

Explained simply

A socket is a phone line for programs. On Linux it is just a file descriptor, a small number like 3 or 4, so you use it with read, write and close like a file. The difference is that the other end is another program, often on another computer.

To reach a program you need two things: an IP address (which computer) and a port (which program on that computer). Port 443 is usually HTTPS, port 22 is SSH. The pair of address and port is one endpoint.

Computers store numbers in different byte orders. Most PCs and phones put the smallest byte first, but network protocols put the biggest byte first. So before you put a port number into an address struct, you convert it with htons, which means host to network short.

Names like example.com must be turned into addresses first. The function getaddrinfo does that for you, and it returns both IPv4 and IPv6 addresses in ready-to-use structs, so the same code works on both kinds of network.

Press Play on a diagram to walk through it one step at a time.

FlowSocket call order
  1. 1
    socket

    Create an endpoint, such as AF_INET6 and SOCK_STREAM.

  2. 2
    bind

    Server attaches to a local address and port.

  3. 3
    listen

    Server marks it passive with a backlog queue.

  4. 4
    accept or connect

    Server takes a connection; client connects.

  5. 5
    send and recv

    Exchange bytes on the connected socket.

  6. 6
    close

    Release the descriptor and end the connection.

FlowFrom a name to a connected socket
  1. 1
    getaddrinfo

    example.com + 443 becomes a list of addresses

  2. 2
    Pick next result

    IPv6 first on most systems, then IPv4

  3. 3
    socket

    With ai_family, ai_socktype, ai_protocol

  4. 4
    connect

    Fails? close it and try the next result

  5. 5
    freeaddrinfo

    Release the list once connected

In depth

socket(), bind(), listen(), accept(): what each one does

socket(domain, type, protocol) creates an endpoint and returns a descriptor. The domain picks the address family: AF_INET for IPv4, AF_INET6 for IPv6, AF_UNIX for local sockets. The type picks the behaviour: SOCK_STREAM for a reliable byte stream (TCP), SOCK_DGRAM for datagrams (UDP). Protocol 0 means the default for that pair. You can add SOCK_CLOEXEC or SOCK_NONBLOCK to the type to set those flags in one call.

A server then calls bind to attach the socket to a local address and port, and listen to turn it into a passive socket. listen creates a queue of finished connections waiting for the program; its size is the backlog, capped by net.core.somaxconn (4096 on kernels since 5.4). accept takes the next connection from that queue and returns a brand new descriptor for it. A client skips bind and listen and calls connect; the kernel picks a free local port for it automatically.

Mapsocket(domain, type, protocol)
socket()
  • domain
    • AF_INET: IPv4
    • AF_INET6: IPv6
    • AF_UNIX: same machine
  • type
    • SOCK_STREAM: TCP byte stream
    • SOCK_DGRAM: UDP datagrams
    • | SOCK_NONBLOCK, | SOCK_CLOEXEC
  • protocol
    • 0: default for domain and type
  • returns
    • A file descriptor, or -1 and errno

Address structs and why everything is cast

The socket functions were designed to work with any address family, so they take a pointer to a generic struct sockaddr plus a length. Real addresses live in family-specific structs. sockaddr_in holds an IPv4 address: sin_family, sin_port and sin_addr. sockaddr_in6 holds an IPv6 address: sin6_family, sin6_port, sin6_addr and a few more fields. You fill the specific one and cast its address to struct sockaddr * when calling bind, connect or sendto.

When you receive an address, for example from accept or recvfrom, you often do not know the family in advance. Use struct sockaddr_storage, which is large enough and aligned for any family, then check ss_family. Always pass the length in a socklen_t variable; accept and recvfrom update it to the real size.

To convert between text and binary addresses, use inet_pton (text to binary) and inet_ntop (binary to text). INET_ADDRSTRLEN (16) and INET6_ADDRSTRLEN (46) are the buffer sizes for the text forms.

  • sockaddr_storage fits IPv4, IPv6 and Unix addresses
  • inet_pton(AF_INET6, "::1", &a.sin6_addr) returns 1 on success
  • inet_ntoa and gethostbyname are old IPv4-only APIs; avoid them

Byte order with htons and friends

x86-64 and almost all ARM systems are little-endian: the lowest byte of a number is stored first. Network protocols use big-endian, called network byte order. The port and address fields inside sockaddr_in and sockaddr_in6 must be in network order, because the kernel copies them into packet headers as they are.

htons converts a 16-bit value (ports) from host to network order, and htonl a 32-bit value (IPv4 addresses such as INADDR_ANY). ntohs and ntohl convert back when you read a port or address out of a struct. On a big-endian machine they do nothing, so always calling them keeps the code portable.

Forgetting htons is a classic bug. Port 8080 is 0x1F90. On a little-endian machine without htons, the bytes go out reversed as 0x901F, and your server ends up listening on port 36895 instead. The same rule applies to your own binary protocols: pick big-endian for integers on the wire and convert on both sides.

ComparePort 8080 (0x1F90) in memory
Host order on x86-64
  • Little-endian
  • Bytes stored as 90 1F
  • Fine for arithmetic
  • Wrong inside sockaddr_in
Network order
  • Big-endian
  • Bytes stored as 1F 90
  • What htons(8080) produces
  • What sin_port must hold

getaddrinfo in depth

getaddrinfo(node, service, &hints, &res) turns a host name and a service (a port number or a name like "https") into a linked list of struct addrinfo, each holding a ready-made address plus the family, socket type and protocol to pass straight to socket. hints says what you want: ai_family AF_UNSPEC for both IPv4 and IPv6, ai_socktype SOCK_STREAM or SOCK_DGRAM, and flags.

Useful flags: AI_PASSIVE with node NULL gives the wildcard address for a server to bind. AI_NUMERICHOST refuses DNS and only parses a literal address. AI_ADDRCONFIG returns IPv6 results only if the machine has an IPv6 address configured, and the same for IPv4.

Errors are not reported in errno. getaddrinfo returns an EAI_ code; print it with gai_strerror (only EAI_SYSTEM means look at errno). Free the list with freeaddrinfo. Remember that it may block for seconds while DNS answers, so never call it inside an event loop thread. getnameinfo does the reverse: address to text.

  • Server: hints.ai_flags = AI_PASSIVE; getaddrinfo(NULL, "8080", ...)
  • Client: AF_UNSPEC and try each result in order
  • Order of results follows RFC 6724, tunable in /etc/gai.conf

Serving IPv4 and IPv6 from one socket

A server can listen on both protocols in two ways. The simple way is one dual-stack socket: create an AF_INET6 socket, set the IPV6_V6ONLY option to 0, and bind to :: (any IPv6 address). It then also accepts IPv4 clients, which show up as IPv4-mapped addresses like ::ffff:192.0.2.10. On Linux the default comes from net.ipv6.bindv6only, which is 0 on most systems, but setting the option explicitly makes the code independent of that setting.

The other way is two sockets: one AF_INET bound to 0.0.0.0 and one AF_INET6 bound to :: with IPV6_V6ONLY set to 1, both watched with poll or epoll. This is what you need if the two should behave differently, and on systems where IPv6 is disabled the IPv6 socket simply fails while IPv4 keeps working.

On the client side, try every getaddrinfo result in order. Browsers go further with Happy Eyeballs (RFC 8305): they start IPv6 and IPv4 attempts almost in parallel and keep the first that connects.

Learn it in 4 short steps

About 55m each. Track them with a timer in your plan.

  1. 1
    Describe the socket, bind, listen, accept calls~55m
  2. 2
    Resolve names with getaddrinfo~55m
  3. 3
    Convert byte order with htons and ntohs~55m
  4. 4
    Support IPv4 and IPv6 together~55m

Key points

  • Use getaddrinfo instead of hand-filling sockaddr structs or calling gethostbyname.
  • Convert ports with htons and ntohs, and text addresses with inet_pton and inet_ntop.
  • Loop over all getaddrinfo results until one connects.
  • Binding ports below 1024 needs root or CAP_NET_BIND_SERVICE.

Key terms

Tap a card to flip it. 0/6 known

Examples

c
#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void) {
  struct addrinfo hints = { .ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM }, *res, *r;
  int err = getaddrinfo("example.com", "80", &hints, &res), fd = -1;
  if (err) { fprintf(stderr, "%s\n", gai_strerror(err)); return 1; }
  for (r = res; r; r = r->ai_next) {
    fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
    if (fd >= 0 && connect(fd, r->ai_addr, r->ai_addrlen) == 0) break;
    if (fd >= 0) close(fd); fd = -1;
  }
  freeaddrinfo(res); puts(fd >= 0 ? "connected" : "failed"); return fd < 0;
}

Protocol-independent client connect, the pattern from Beej's guide.

A listening socket for IPv4 and IPv6

We want one function that opens a TCP server socket on a given port for both protocols. Step 1: ask getaddrinfo for an AF_INET6 passive address, so node NULL becomes ::. Step 2: create the socket from the result fields. Step 3: turn IPV6_V6ONLY off so IPv4 clients are accepted too, and set SO_REUSEADDR for quick restarts. Step 4: bind and listen, closing the socket on any error. Step 5: free the list in every case. It needs netdb.h, netinet/in.h, sys/socket.h, stdio.h and unistd.h.

c
int listen_on(const char *port) {
  struct addrinfo hints = { .ai_family = AF_INET6, .ai_socktype = SOCK_STREAM, .ai_flags = AI_PASSIVE }, *res;
  int err = getaddrinfo(NULL, port, &hints, &res);
  if (err) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err)); return -1; }
  int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol), off = 0, one = 1;
  if (fd >= 0) {
    setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof off);   /* accept IPv4 too */
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
    if (bind(fd, res->ai_addr, res->ai_addrlen) < 0 || listen(fd, 128) < 0) {
      perror("bind/listen"); close(fd); fd = -1; }
  } else perror("socket");
  freeaddrinfo(res);
  return fd;
}

Print who connected, whatever the family

After accept we want to log the client's address. Step 1: receive the address into a sockaddr_storage, which fits both IPv4 and IPv6, and pass its size in a socklen_t. Step 2: call getnameinfo with NI_NUMERICHOST and NI_NUMERICSERV so it only formats numbers and never waits for DNS. Step 3: print the result. Connect once with nc -6 ::1 8080 and once with nc -4 127.0.0.1 8080: on the dual-stack socket above, the IPv4 client appears as ::ffff:127.0.0.1.

c
struct sockaddr_storage ss; socklen_t len = sizeof ss;
int c = accept(lfd, (struct sockaddr *)&ss, &len);
if (c < 0) { perror("accept"); continue; }
char host[NI_MAXHOST], serv[NI_MAXSERV];
int err = getnameinfo((struct sockaddr *)&ss, len, host, sizeof host,
                      serv, sizeof serv, NI_NUMERICHOST | NI_NUMERICSERV);
if (err) fprintf(stderr, "getnameinfo: %s\n", gai_strerror(err));
else printf("client %s port %s\n", host, serv);   /* e.g. ::ffff:127.0.0.1 port 51514 */

Quick reference

  • socket(AF_INET6, SOCK_STREAM | SOCK_CLOEXEC, 0) returns a descriptor or -1
  • htons for ports, htonl for IPv4 addresses; ntohs and ntohl to read them back
  • getaddrinfo errors: print gai_strerror(err), not perror
  • AI_PASSIVE + NULL host = wildcard address for a server bind
  • sockaddr_storage holds any address type; check ss_family
  • IPV6_V6ONLY = 0 on an AF_INET6 socket accepts IPv4 as ::ffff:a.b.c.d
  • Ports below 1024 need root or CAP_NET_BIND_SERVICE
  • ss -ltnp shows listening TCP sockets and the owning process

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A server sets sin_port = 8080 without htons on an x86-64 machine. Which port does it actually listen on?

Question 2

2getaddrinfo returns a non-zero value. How do you get a readable message?

Question 3

3Which struct should you use to receive an address from accept when the client may be IPv4 or IPv6?

Question 4

4What does accept return?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print the value 8080 and htons(8080) in hex, and print the two bytes of each in memory order.

  2. Exercise 2medium

    Write a tiny lookup tool: ./lookup example.com prints every address getaddrinfo returns, with IPv4 or IPv6 in front.

  3. Exercise 3hard

    Use listen_on from the example in a server that accepts clients and logs their addresses. For IPv4-mapped clients, print the plain IPv4 address instead of ::ffff:a.b.c.d.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between 0.0.0.0 and 127.0.0.1 when binding?
0.0.0.0 (or :: for IPv6) accepts connections on every network interface. 127.0.0.1 (or ::1) only accepts connections from the same machine, which is safer for admin or debug ports.
Why do I need root to bind port 80?
Ports below 1024 are privileged on Linux. Grant just that right with setcap cap_net_bind_service=+ep ./server, or AmbientCapabilities=CAP_NET_BIND_SERVICE in a systemd unit, instead of running as root.
Is gethostbyname still OK to use?
No. It is obsolete, IPv4-only and not thread-safe. getaddrinfo replaces it and handles IPv4 and IPv6 the same way.
Does htons do anything on ARM?
Most ARM Linux systems run little-endian, so yes, it swaps the bytes just like on x86. On a big-endian machine it does nothing, which is why you always call it.

Go deeper

ShareXLinkedInWhatsApp