gethostbyname(), gethostbyname2()

Get a network host entry, given a name


#include <netdb.h>

struct hostent * gethostbyname( const char * name );

struct hostent * gethostbyname2( const char * name,
                                 int af );


The name of the Internet host whose entry you want to find.
(gethostbyname2() only) The address family; one of:
  • AF_INET6



Use the -l socket option to qcc to link against this library.


The gethostbyname() routine gets the network host entry for a given name. It returns a pointer to a structure of type hostent that describes an Internet host. This structure contains either the information obtained from a name server, or broken-out fields from a line in /etc/hosts.

Note: Both gethostbyaddr() and gethostbyname() are marked as obsolete in POSIX 1003.1. You should use getaddrinfo() or getnameinfo() instead.

When using the name server, gethostbyname() searches for the named host in the current domain and in the domain's parents, unless the name ends in a dot.

  • If the name server isn't responding, there's a timeout of 1.5 minutes per name server.
  • If the name doesn't contain a dot, and the environment variable HOSTALIASES contains the name of an alias file, the alias file is first searched for an alias matching the input name. This file has the same form as /etc/hosts.

You can use sethostent() to request the use of a connected TCP socket for queries. If the stayopen flag is nonzero, all queries to the name server use TCP and the connection is retained after each call to gethostbyname() or gethostbyaddr(). If the stayopen flag is zero, queries use UDP datagrams.

The gethostbyname2() function is an evolution of the gethostbyname() function that lets you look up host names in address families other than AF_INET. If you specify an invalid address family, the function returns NULL and sets h_errno to NETDB_INTERNAL.


A pointer to a valid hostent structure, or NULL if an error occurs (h_errno is set).


See herror().


Host database file.
Name-service switch configuration file.

For information about these files, see the Utilities Reference.

Environment variables:

Name of the alias file that gethostbyname() is to search first when the hostname doesn't contain a dot.


gethostbyname() is Standard Unix; removed from POSIX.1-2008. gethostbyname2() is QNX Neutrino

Cancellation point Yes
Interrupt handler No
Signal handler No
Thread No


This function uses static data storage; if you need the data for future use, copy it before any subsequent calls overwrite it.