gethostbyname(), gethostbyname2()

Get a network host entry, given a name

Synopsis:

#include <netdb.h>

struct hostent * gethostbyname( const char * name );

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

Arguments:

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

Library:

libsocket

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

Description:

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.


Note:
  • 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.

Returns:

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

Errors:

See herror().

Files:

/etc/hosts
Host database file.
/etc/nsswitch.conf
Name-service switch configuration file.

For information about these files, see the Utilities Reference.

Environment variables:

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

Classification:

gethostbyname() is POSIX 1003.1 OBS; gethostbyname2() is QNX Neutrino

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread No

Caveats:

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

See also:

endhostent(), getaddrinfo(), gethostbyaddr(), gethostbyname_r(), gethostent(), getnameinfo(), herror(), hostent, sethostent()

/etc/hosts, /etc/nsswitch.conf in the Utilities Reference