gtpc1m3pTransmission Control Protocol/Internet Protocol

gethostbyname -- Get IP Address Information by Host Name

The gethostbyname function returns information about a host specified by a host name.

Format

#include  <netdb.h>
struct hostent *gethostbyname(char *name);

name
The name of the host being queried.

Normal Return

This function returns a pointer to a hostent structure for the host name specified on the call. The netdb.h header file defines the hostent structure, which contains the following elements:

Element
Description

h_name
Official name of the host.

h_aliases
Zero-terminated array of alternative names for the host.

h_addrtype
Type of address being returned, always set to AF_INET.

h_length
Length of the address in bytes.

h_addr
Pointer to the network address of the host in network byte order.
Note:
Subsequent gethostbyname calls overwrite the data in the hostent structure.

Error Return

A NULL pointer indicates an error. The value of h_errno indicates the specific error.

Note:
Unless otherwise stated in the description, the following error codes can be returned for either TCP/IP offload support or TCP/IP native stack support.

Value
Description

HOST_NOT_FOUND
The host name specified by the name parameter was not found.

TRY_AGAIN
The local server did not receive a response from an authorized server. Try again later.

NO_RECOVERY
An irrecoverable error has occurred.

NO_DATA
The host name is a valid name, but there is no corresponding Internet Protocol (IP) address.

Programming Considerations

The gethostbyname function tries to resolve the host name through a name server if one is present.

Examples

The following example obtains the IP address associated with a given host name.

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

·
·
·
struct sockaddr whereto; struct hostent *hp; struct sockaddr_in *to; char *target; char *hostname; memset(&whereto, 0, sizeof(struct sockaddr)); to = (struct sockaddr_in *)&whereto; to->sin_family = AF_INET; to->sin_addr.s_addr = inet_addr(target); if (to->sin_addr.s_addr != -1) hostname = target; else { hp = gethostbyname(target); if (!hp) printf("unknown host %s\n", target); else { to->sin_family = hp->h_addrtype; memcpy(&(to->sin_addr.s_addr), hp->h_addr, hp->h_length); hostname = hp->h_name; printf("gethostbyname was successful\n"); } }

Related Information

gethostbyaddr -- Get Host Information for IP Address.