hostent3.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "unp.h"
  2. void pr_ipv4(char **);
  3. int
  4. main(int argc, char **argv)
  5. {
  6. char *ptr, **pptr;
  7. struct hostent *hptr;
  8. while (--argc > 0) {
  9. ptr = *++argv;
  10. if ( (hptr = gethostbyname(ptr)) == NULL) {
  11. err_msg("gethostbyname error for host: %s: %s",
  12. ptr, hstrerror(h_errno));
  13. continue;
  14. }
  15. printf("official host name: %s\n", hptr->h_name);
  16. for (pptr = hptr->h_aliases; *pptr != NULL; pptr++)
  17. printf(" alias: %s\n", *pptr);
  18. switch (hptr->h_addrtype) {
  19. case AF_INET:
  20. pr_ipv4(hptr->h_addr_list);
  21. break;
  22. default:
  23. err_ret("unknown address type");
  24. break;
  25. }
  26. }
  27. exit(0);
  28. }
  29. /*
  30. * Print the array of IPv4 addresses that is returned.
  31. * Also call gethostbyaddr_r() for each IP address and print the name.
  32. */
  33. /* begin pr_ipv4 */
  34. void
  35. pr_ipv4(char **listptr)
  36. {
  37. struct in_addr inaddr;
  38. struct hostent *hptr, hent;
  39. char buf[8192];
  40. int h_errno;
  41. for ( ; *listptr != NULL; listptr++) {
  42. inaddr = *((struct in_addr *) (*listptr));
  43. printf(" IPv4 address: %s", Inet_ntoa(inaddr));
  44. if ( (hptr = gethostbyaddr_r((char *) &inaddr, sizeof(struct in_addr),
  45. AF_INET, &hent,
  46. buf, sizeof(buf), &h_errno)) == NULL)
  47. printf(" (gethostbyaddr failed: %s)\n", hstrerror(h_errno));
  48. else if (hptr->h_name != NULL)
  49. printf(" name = %s\n", hptr->h_name);
  50. else
  51. printf(" (no hostname returned by gethostbyaddr)\n");
  52. }
  53. }
  54. /* end pr_ipv4 */