<< Prev | Beej's Guide to Network Programming (cloned from beej.us) | Next >> |
Hosted at Teoria dei Segnali.it - Blog - Download - Signal Transmission - Internet Application Layer - Wiki - Newsletter |
Get an IP address for a hostname, or vice-versa
#include <sys/socket.h> #include <netdb.h> struct hostent *gethostbyname(const char *name); struct hostent *gethostbyaddr(const char *addr, int len, int type);
These functions map back and forth between host names and IP addresses. After all, you want an IP address to pass to connect(), right? But no one wants to remember an IP address. So you let your users type in things like "www.yahoo.com" instead of "66.94.230.35".
gethostbyname() takes a string like "www.yahoo.com", and
returns a
gethostbyaddr() takes a
So what is this
char *h_name |
The real canonical host name. |
char **h_aliases |
A list of aliases that can be accessed with arrays—the last element is NULL |
int h_addrtype |
The result's address type, which really should be AF_INET for our purposes.. |
int length |
The length of the addresses in bytes, which is 4 for IP (version 4) addresses. |
char **h_addr_list |
A list of IP addresses for this host. Although this
is a |
h_addr |
A commonly defined alias for h_addr_list[0]. If you just want any old IP address for this host (yeah, they can have more than one) just use this field. |
Returns a pointer to a resultant
Instead of the normal perror() and all that stuff you'd normally use for error reporting, these functions have parallel results in the variable h_errno, which can be printed using the functions herror() or hstrerror(). These work just like the classic errno, perror(), and strerror() functions you're used to.
int i; struct hostent *he; struct in_addr **addr_list; struct in_addr addr; // get the addresses of www.yahoo.com: he = gethostbyname("www.yahoo.com"); if (he == NULL) { // do some error checking herror("gethostbyname"); // herror(), NOT perror() exit(1); } // print information about this host: printf("Official name is: %s\n", he->h_name); printf("IP address: %s\n", inet_ntoa(*(struct in_addr*)he->h_addr)); printf("All addresses: "); addr_list = (struct in_addr **)he->h_addr_list; for(i = 0; addr_list[i] != NULL; i++) { printf("%s ", inet_ntoa(*addr_list[i])); } printf("\n"); // get the host name of 66.94.230.32: inet_aton("66.94.230.32", &addr); he = gethostbyaddr(&addr, sizeof(addr), AF_INET); printf("Host name: %s\n", he->h_name);
gethostname(),
errno,
perror(),
strerror(),
<< Prev | Beej's Guide to Network Programming (cloned from beej.us) | Next >> |