gtpc1m3p | Transmission Control Protocol/Internet Protocol |
The gethostbyname function returns information about a host specified by a host name.
Format
#include <netdb.h> struct hostent *gethostbyname(char *name);
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:
Error Return
A NULL pointer indicates an error. The value of h_errno indicates the specific error.
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