What you will learn
- The family of address structures and how they relate.
- Why every socket call takes a
struct sockaddr *plus a length. - How to hold “either IPv4 or IPv6” safely with
sockaddr_storage. - What each field of
struct addrinfomeans.
The problem these structs solve
bind(), connect(), accept() and sendto() must work with IPv4, IPv6, Unix-domain paths and more. C has no inheritance, so the API uses a trick: a generic header struct, several specific structs that all start with the same family field, and a length argument so the kernel knows how many bytes to read.
first field rest of the struct
sockaddr sa_family | sa_data[14] (generic, rarely filled directly)
sockaddr_in sin_family | port | IPv4 address | padding (16 bytes)
sockaddr_in6 sin6_family | port | flowinfo | IPv6 address | scope (28 bytes)
sockaddr_storage ss_family | big enough for any of them (128 bytes)
The kernel reads the family field first, then interprets the rest accordingly. That’s why you can fill a sockaddr_in and pass (struct sockaddr *)&addr.
struct sockaddr_in (IPv4)
struct sockaddr_in {
sa_family_t sin_family; /* AF_INET */
in_port_t sin_port; /* port, network byte order */
struct in_addr sin_addr; /* IPv4 address, network byte order */
unsigned char sin_zero[8]; /* padding: keep it zeroed */
};
struct in_addr {
uint32_t s_addr; /* the 4 address bytes */
};
Filling one by hand looks like this. memset first so padding (and, on BSD/macOS, an extra sin_len field) are zero:
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(5050);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
connect(fd, (struct sockaddr *)&addr, sizeof addr);
addr.sin_addr.s_addr = htonl(INADDR_ANY); means “every local IPv4 address”, used by servers. INADDR_LOOPBACK is 127.0.0.1.
struct sockaddr_in6 (IPv6)
struct sockaddr_in6 {
sa_family_t sin6_family; /* AF_INET6 */
in_port_t sin6_port; /* network byte order */
uint32_t sin6_flowinfo; /* flow label, usually 0 */
struct in6_addr sin6_addr; /* 16 address bytes */
uint32_t sin6_scope_id; /* interface index for link-local addresses */
};
For “any address” use the global in6addr_any (or the initializer IN6ADDR_ANY_INIT); for loopback use in6addr_loopback.
struct sockaddr_storage: room for anything
When you don’t know in advance whether a peer is IPv4 or IPv6, for example in accept() or recvfrom(), declare a sockaddr_storage. It is guaranteed large enough and suitably aligned for every address family. After the call, check ss_family and cast:
struct sockaddr_storage peer;
socklen_t len = sizeof peer; /* in: buffer size, out: actual size */
int client = accept(listener, (struct sockaddr *)&peer, &len);
if (peer.ss_family == AF_INET) {
struct sockaddr_in *v4 = (struct sockaddr_in *)&peer;
printf("IPv4 client, port %u\n", ntohs(v4->sin_port));
} else if (peer.ss_family == AF_INET6) {
struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)&peer;
printf("IPv6 client, port %u\n", ntohs(v6->sin6_port));
}
Note that the length argument is value-result: you pass in the buffer size and the kernel writes back the real size. Re-initialise it before every call in a loop.
A handy helper used by many programs returns a pointer to the raw address bytes regardless of family, ready for inet_ntop():
const void *addr_bytes(const struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
return &((const struct sockaddr_in *)sa)->sin_addr;
return &((const struct sockaddr_in6 *)sa)->sin6_addr;
}
struct addrinfo: the modern starting point
You will rarely fill sockaddr_in by hand. Instead you call getaddrinfo() (next lesson), which returns a linked list of these:
struct addrinfo {
int ai_flags; /* AI_PASSIVE, AI_CANONNAME, ... (hints only) */
int ai_family; /* AF_INET, AF_INET6 or AF_UNSPEC */
int ai_socktype; /* SOCK_STREAM or SOCK_DGRAM */
int ai_protocol; /* usually 0 or IPPROTO_TCP/UDP */
socklen_t ai_addrlen; /* size of *ai_addr */
struct sockaddr *ai_addr; /* ready-to-use address, network byte order */
char *ai_canonname; /* official host name if AI_CANONNAME was set */
struct addrinfo *ai_next; /* next result, or NULL */
};
Each entry carries everything you need for the next three calls, in the right form:
socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
connect(fd, ai->ai_addr, ai->ai_addrlen); /* or bind() */
That is the whole point of addrinfo: your code never needs to know whether it is talking IPv4 or IPv6.
AF_ and PF_
You may see PF_INET in some code where we use AF_INET. “PF” meant protocol family (for socket()) and “AF” address family (for structs). The split never materialised and on every current system they have the same value. Use AF_ everywhere.
Key takeaways
- All socket address structs begin with a family field; the kernel uses it plus the length you pass to interpret the rest.
- Zero structures with
memsetbefore filling them; port and address fields are in network byte order. - Use
sockaddr_storagewhen the peer’s family is unknown, then branch onss_family. struct addrinfobundles family, socket type, protocol and a ready-made address, so code stays IP-version agnostic.
Exercises
- Print
sizeofforsockaddr,sockaddr_in,sockaddr_in6andsockaddr_storageon your machine. - Write
void print_sockaddr(const struct sockaddr *sa)that printsaddress:portfor IPv4 and[address]:portfor IPv6. - Fill a
sockaddr_in6for::1port 9000 by hand and connect to a test server (for examplenc -l -6 9000).
Quiz
- Why is it safe to pass
(struct sockaddr *)&my_sockaddr_in6toconnect()? - In
accept(fd, addr, &len), what islenbefore and after the call? - Which struct should you declare to receive the sender’s address in
recvfrom()when IPv4 and IPv6 are both possible?
Show answers
- Every address struct starts with the family field, and you also pass the real length, so the kernel knows to read it as an IPv6 address of 28 bytes.
- Before: the size of your buffer. After: the actual size of the address the kernel stored.
struct sockaddr_storage.