gethostbyaddr()

Get a network host entry, given an Internet address

Synopsis:

#include <netdb.h>

struct hostent * gethostbyaddr( const void * addr,
                                socklen_t len,
                                int type );

Arguments:

addr
A pointer to the binary-format (i.e. not NULL-terminated) address in network byte order.
len
The length, in bytes, of addr.
type
The type of address. Currently, this must be AF_INET.

Library:

libsocket

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

Description:

The gethostbyaddr() function searches for information associated with a host, which has the address pointed to by addr within the address family specified by type, opening a connection to the database if necessary.


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

This function 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.

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 will use TCP and the connection will be retained after each call to gethostbyaddr() or gethostbyname(). If the stayopen flag is zero, queries use UDP datagrams.

Returns:

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

Errors:

See herror().

Examples:

Use the gethostbyaddr() function to find a host:

struct sockaddr_in  client;
struct hostent* host;

int sock, fd, len;

…

len = sizeof( client );

fd  = accept( sock, (struct sockaddr*)&client, &len );

if( fd == -1 ) {
    perror( "accept" );
    exit( 1 );
}

host = gethostbyaddr( (const void*)&client.sin_addr, 
                      sizeof(struct in_addr), 
                      AF_INET );

printf( "Connection from %s: (%s)\n",
        host ? host->h_name : "<unknown>",
        inet_ntoa( client.sin_addr ) );

…

Files:

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

Classification:

POSIX 1003.1 OBS

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. Currently, only the Internet address format is understood.

See also:

endhostent(), gethostbyname(), gethostbyaddr_r(), gethostent(), herror(), hostent, sethostent()

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