1218 Chapter 59
We can use the string returned by gai_strerror() as part of an error message dis-
played by an application.
59.10.4 The getnameinfo() Function
The getnameinfo() function is the converse of getaddrinfo(). Given a socket address
structure (either IPv4 or IPv6), it returns strings containing the corresponding host
and service name, or numeric equivalents if the names can’t be resolved.
The addr argument is a pointer to the socket address structure that is to be con-
verted. The length of that structure is given in addrlen. Typically, the values for addr
and addrlen are obtained from a call to accept(), recvfrom(), getsockname(), or
getpeername().
The resulting host and service names are returned as null-terminated strings in
the buffers pointed to by host and service. These buffers must be allocated by the caller,
and their sizes must be passed in hostlen and servlen. The <netdb.h> header file
defines two constants to assist in sizing these buffers. NI_MAXHOST indicates the maxi-
mum size, in bytes, for a returned hostname string. It is defined as 1025. NI_MAXSERV
indicates the maximum size, in bytes, for a returned service name string. It is
defined as 32. These two constants are not specified in SUSv3, but they are defined
on all UNIX implementations that provide getnameinfo(). (Since glibc 2.8, we must
define one of the feature text macros _BSD_SOURCE, _SVID_SOURCE, or _GNU_SOURCE to
obtain the definitions of NI_MAXHOST and NI_MAXSERV.)
If we are not interested in obtaining the hostname, we can specify host as NULL
and hostlen as 0. Similarly, if we don’t need the service name, we can specify service
as NULL and servlen as 0. However, at least one of host and service must be non-NULL
(and the corresponding length argument must be nonzero).
The final argument, flags, is a bit mask that controls the behavior of getnameinfo().
The following constants may be ORed together to form this bit mask:
NI_DGRAM
By default, getnameinfo() returns the name corresponding to a stream socket
(i.e., TCP) service. Normally, this doesn’t matter, because, as noted in
Section 59.9, the service names are usually the same for corresponding
#include <netdb.h>
const char *gai_strerror(int errcode);
Returns pointer to string containing error message
#include <sys/socket.h>
#include <netdb.h>
int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, char *host,
size_t hostlen, char *service, size_t servlen, int flags);
Returns 0 on success, or nonzero on error