The getnameinfo(3) function is defined for protocol-independent address-to-nodename translation. It combines the functionality of gethostbyaddr(3) and getservbyport(3) and is the inverse of getaddrinfo(3). The sa argument is a pointer to a generic socket address structure (of type sockaddr_in or sockaddr_in6) of size salen that holds the input IP address and port number. The arguments host and serv are pointers to buffers (of size hostlen and servlen repectively) to hold the return values.
The caller can specify that no hostname (or no service name) is required by providing a NULL host (or serv) argument or a zero hostlen (or servlen) parameter. However, at least one of hostname or service name must be requested.
The flags argument modifies the behaviour of getnameinfo(3) as follows:
If set, return only the hostname part of the FQDN for local hosts.
If set, then the numeric form of the hostname is returned. (When not set, this will still happen in case the node's name cannot be looked up.)
If set, then a error is returned if the hostname cannot be looked up.
If set, then the service address is returned in numeric form, for example by its port number.
The name could not be resolved at this time. Try again later.
The flags parameter has an invalid value.
A non-recoverable error occurred.
The address family was not recognized, or the address length was invalid for the specified family.
Out of memory.
The name does not resolve for the supplied parameters. NI_NAMEREQD is set and the host's name cannot be located, or neither hostname nor service name were requested.
In order to assist the programmer in choosing reasonable sizes for the supplied buffers, defines the constants
The following code tries to get the numeric hostname and service name, for a given socket address. Note that there is no hardcoded reference to a particular address family.
The following version checks if the socket address has a reverse address mapping.
struct sockaddr sa; / input */ char hbuf[NI_MAXHOST?;
R. Gilligan, S. Thomson, J. Bound and W. Stevens, Basic Socket Interface Extensions for IPv6, RFC 2553, March 1999.
Tatsuya Jinmei and Atsushi Onoe, An Extension of Format for IPv6 Scoped Addresses, internet draft, work in progress. ftp://ftp.ietf.org/internet-drafts/draft-ietf-ipngwg-scopedaddr-format-02.txt