13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 48Return ValueReturns a pointer <strong>to</strong> a resultant struct hostent or success, or NULL on error.Instead of the normal perror() and all that stuff you’d normally use for error reporting, thesefunctions have parallel results in the variable h_errno, which can be printed using the functionsherror() or hstrerror(). These work just like the classic errno, perror(), and strerror()functions you’re used <strong>to</strong>.Exampleint 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 checkingherror("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_n<strong>to</strong>a(*(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_n<strong>to</strong>a(*addr_list[i]));}printf("\n");// get the host name of 66.94.230.32:inet_a<strong>to</strong>n("66.94.230.32", &addr);he = gethostbyaddr(&addr, sizeof(addr), AF_INET);printf("Host name: %s\n", he->h_name);See Alsogethostname(), errno, perror(), strerror(), struct in_addr

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!