Manual Page Search Parameters

GETNAMEINFO(3) Library Functions Manual GETNAMEINFO(3)

socket address structure to hostname and service name

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>


The getnameinfo() function is used to convert a sockaddr structure to a pair of host name and service strings. It is a replacement for and provides more flexibility than the gethostbyaddr(3) and getservbyport(3) functions and is the converse of the getaddrinfo(3) function.

The sockaddr structure sa should point to either a sockaddr_in or sockaddr_in6 structure (for IPv4 or IPv6 respectively) that is salen bytes long.


The flags argument is formed by OR'ing the following values:

The service name is returned as a digit string representing the port number.
Specifies that the service being looked up is a datagram service, and causes getservbyport(3) to be called with a second argument of “udp” instead of its default of “tcp”. This is required for the few ports (512-514) that have different services for UDP and TCP.

This implementation allows numeric IPv6 address notation with scope identifier, as documented in RFC 4007. IPv6 link-local address will appear as a string like “fe80::1%ne0”. Refer to getaddrinfo(3) for more information.


struct sockaddr *sa;	/* input */
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];



struct sockaddr *sa;	/* input */
char hbuf[NI_MAXHOST];

	errx(1, "could not resolve hostname");


Craig Metz, Protocol Independence Using the Sockets API, Proceedings of the Freenix Track: 2000 USENIX Annual Technical Conference, June 2000.

The getnameinfo() function is defined by the IEEE Std 1003.1g-2000 (“POSIX.1g”) draft specification and documented in RFC 3493.


S. Deering, B. Haberman, T. Jinmei, E. Nordmark, and B. Zill, IPv6 Scoped Address Architecture, RFC 4007, March 2005.




struct sockaddr *sa;
char addr[NI_MAXHOST];
struct addrinfo hints, *res;
int error;

error = getnameinfo(sa, sa->sa_len, addr, sizeof(addr),
if (error == 0) {
	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
	hints.ai_flags = AI_NUMERICHOST;
		/* malicious PTR record */
		printf("bogus PTR record\n");
		return -1;
} else {
	/* addr is numeric string */

The implementation of getnameinfo() is not thread-safe.

OpenBSD intentionally uses a different NI_MAXHOST value from what RFC 2553 suggests, to avoid buffer length handling mistakes.

August 23, 2014 OpenBSD-current