1204 Chapter 59
Unlike their IPv4 counterparts, the IPv6 constant and variable initializers are in
network byte order. But, as shown in the above code, we still must ensure that the
port number is in network byte order.
If IPv4 and IPv6 coexist on a host, they share the same port-number space. This
means that if, for example, an application binds an IPv6 socket to TCP port 2000
(using the IPv6 wildcard address), then an IPv4 TCP socket can’t be bound to the
same port. (The TCP/IP implementation ensures that sockets on other hosts are
able to communicate with this socket, regardless of whether those hosts are run-
ning IPv4 or IPv6.)
The sockaddr_storage structure
With the IPv6 sockets API, the new generic sockaddr_storage structure was intro-
duced. This structure is defined to be large enough to hold any type of socket
address (i.e., any type of socket address structure can be cast and stored in it). In
particular, this structure allows us to transparently store either an IPv4 or an IPv6
socket address, thus removing IP version dependencies from our code. The
sockaddr_storage structure is defined on Linux as follows:
#define __ss_aligntype uint32_t /* On 32-bit architectures */
struct sockaddr_storage {
sa_family_t ss_family;
__ss_aligntype __ss_align; /* Force alignment */
char __ss_padding[SS_PADSIZE]; /* Pad to 128 bytes */
};
59.5 Overview of Host and Service Conversion Functions
Computers represent IP addresses and port numbers in binary. However, humans
find names easier to remember than numbers. Employing symbolic names also
provides a useful level of indirection; users and programs can continue to use the
same name even if the underlying numeric value changes.
A hostname is the symbolic identifier for a system that is connected to a network
(possibly with multiple IP addresses). A service name is the symbolic representation
of a port number.
The following methods are available for representing host addresses and ports:
z A host address can be represented as a binary value, as a symbolic hostname,
or in presentation format (dotted-decimal for IPv4 or hex-string for IPv6).
z A port can be represented as a binary value or as a symbolic service name.
Various library functions are provided for converting between these formats. This
section briefly summarizes these functions. The following sections describe the
modern APIs (inet_ntop(), inet_pton(), getaddrinfo(), getnameinfo(), and so on) in
detail. In Section 59.13, we briefly discuss the obsolete APIs (inet_aton(), inet_ntoa(),
gethostbyname(), getservbyname(), and so on).
Converting IPv4 addresses between binary and human-readable forms
The inet_aton() and inet_ntoa() functions convert an IPv4 address in dotted-decimal
notation to binary and vice versa. We describe these functions primarily because