bug-erange.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* Test case for gethostbyname_r bug when buffer expansion required. */
  2. #include <netdb.h>
  3. #include <arpa/inet.h>
  4. #include <errno.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. int
  10. main (void)
  11. {
  12. const char *host = "www.gnu.org";
  13. /* This code approximates the example code in the library manual. */
  14. struct hostent hostbuf, *hp;
  15. size_t hstbuflen;
  16. char *tmphstbuf;
  17. int res;
  18. int herr;
  19. hstbuflen = 16; /* Make it way small to ensure ERANGE. */
  20. /* Allocate buffer, remember to free it to avoid memory leakage. */
  21. tmphstbuf = malloc (hstbuflen);
  22. while ((res = gethostbyname_r (host, &hostbuf, tmphstbuf, hstbuflen,
  23. &hp, &herr)) == ERANGE)
  24. {
  25. /* Enlarge the buffer. */
  26. hstbuflen *= 2;
  27. tmphstbuf = realloc (tmphstbuf, hstbuflen);
  28. }
  29. if (res != 0 || hp == NULL)
  30. {
  31. printf ("gethostbyname_r failed: %s (errno: %m)\n", strerror (res));
  32. if (access ("/etc/resolv.conf", R_OK))
  33. {
  34. puts ("DNS probably not set up");
  35. return 0;
  36. }
  37. return 1;
  38. }
  39. printf ("Got: %s %s\n", hp->h_name,
  40. inet_ntoa (*(struct in_addr *) hp->h_addr));
  41. return 0;
  42. }