C Programming/POSIX Reference/netdb.h/getaddrinfo

The   and  functions are part of the POSIX standard application programming interface (API) for converting domain name system (DNS) hostnames and IP addresses between their human-readable text representations and structured binary formats for the operating system's networking API.

getaddrinfo and getnameinfo are inverse functions of each other.

This set of functions is fully network protocol agnostic and supports both IPv4 and IPv6. It is the recommended interface for name resolution in building protocol independent applications and for transitioning legacy IPv4 code to the IPv6 Internet.

struct addrinfo
The C data structure used to represent addresses and hostnames within the networking API is the following:

In recent operating systems the type of ai_addrlen has been changed from size_t to socklen_t. Most socket functions, such as accept and getpeername, require a socklen_t* parameter and programmers often pass the address to the ai_addrlen element of the addrinfo structure. If the types are incompatible, e.g., on a big-endian 64-bit Solaris 9 system where size_t is 8 bytes and socklen_t is 4 bytes, then run-time errors may result.

getaddrinfo
getaddrinfo converts human-readable text strings representing hostnames or IP addresses into a dynamically allocated linked list of struct addrinfo structures. An application can deallocate these linked lists with the freeaddrinfo function. The function prototypes for these functions are specified as follows:

getnameinfo
getnameinfo converts the internal binary representation of an IP address in the form of a struct sockaddr pointer into text strings consisting of the hostname or, if the address cannot be resolved into a name, a textual IP address representation, as well as the service port name or number. The function prototype is specified as follows:

Example
The following example uses getaddrinfo to resolve the domain name www.example.com into its list of addresses and then calls <tt>getnameinfo</tt> on each result to return the canonical name for the address. In general, this will produce the original hostname, unless the particular address has multiple names, in which case the canonical name is returned. In this example, the domain name will be printed three times, once for each of the three results obtained.

External link

 * RFC 3493, Basic Socket Interface Extensions for IPv6