Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)
3.6 inet_aton , inet_addr , and inet_ntoa Functions
We will describe two groups of address conversion functions in this section and the next . They convert Internet addresses between ASCII strings (what humans prefer to use) and network byte ordered binary values (values that are stored in socket address structures).
The first of these, inet_aton , converts the C character string pointed to by strptr into its 32-bit binary network byte ordered value, which is stored through the pointer addrptr . If successful, 1 is returned; otherwise , 0 is returned. An undocumented feature of inet_aton is that if addrptr is a null pointer, the function still performs its validation of the input string but does not store any result. inet_addr does the same conversion, returning the 32-bit binary network byte ordered value as the return value. The problem with this function is that all 2 32 possible binary values are valid IP addresses (0.0.0.0 through 255.255.255.255), but the function returns the constant INADDR_NONE (typically 32 one-bits) on an error. This means the dotted-decimal string 255.255.255.255 (the IPv4 limited broadcast address, Section 20.2) cannot be handled by this function since its binary value appears to indicate failure of the function. A potential problem with inet_addr is that some man pages state that it returns “1 on an error, instead of INADDR_NONE . This can lead to problems, depending on the C compiler, when comparing the return value of the function (an unsigned value) to a negative constant. Today, inet_addr is deprecated and any new code should use inet_aton instead. Better still is to use the newer functions described in the next section, which handle both IPv4 and IPv6. The inet_ntoa function converts a 32-bit binary network byte ordered IPv4 address into its corresponding dotted-decimal string. The string pointed to by the return value of the function resides in static memory. This means the function is not reentrant, which we will discuss in Section 11.18. Finally, notice that this function takes a structure as its argument, not a pointer to a structure. Functions that take actual structures as arguments are rare. It is more common to pass a pointer to the structure. |