Socket Addresses in a IPv6 World

Socket addresses are tuples that you use when you want to specify where a socket should listen (bind) or connect to. In IPv4 they are simply a pair composed by an address and a port but in IPv6 they also include a scope id. The reason for this extra field is the link-local addresses, which are not guaranteed to be unique beyond a single network segment, so an id is required to specify the segment where the address applies.

To properly support IPv6 your application should take into account that with IPv6, socket addresses are not a simple (address, port) pair but a 4-tuple composed by (address, port, flow info, scope id).

Even in IPv6, most of the time, you will get away with setting only the first two fields, i.e., (address, port) because most commonly used addresses have global scope. However, sooner or later, a more adventurous user will try to listen on – or connect to – some link local-address, which will be something looking like fe80::1%lo0 (yes, this is a valid IPv6 address) and things will break.

Fortunately the solution is quite simple. Instead of building the socket address youself, (which you should not be doing most of the time, anyway) just let getaddrinfo do it for you. Given an address it can correctly compute the family and the socket address. If it is a link-local IPv6 address it will also compute the right scope id.