Back to index

glibc  2.9
bug-erange.c
Go to the documentation of this file.
00001 /* Test case for gethostbyname_r bug when buffer expansion required.  */
00002 
00003 #include <netdb.h>
00004 #include <arpa/inet.h>
00005 #include <errno.h>
00006 #include <string.h>
00007 #include <stdio.h>
00008 #include <stdlib.h>
00009 #include <unistd.h>
00010 
00011 int
00012 main (void)
00013 {
00014   const char *host = "www.gnu.org";
00015 
00016   /* This code approximates the example code in the library manual.  */
00017 
00018   struct hostent hostbuf, *hp;
00019   size_t hstbuflen;
00020   char *tmphstbuf;
00021   int res;
00022   int herr;
00023 
00024   hstbuflen = 16;           /* Make it way small to ensure ERANGE.  */
00025   /* Allocate buffer, remember to free it to avoid memory leakage.  */
00026   tmphstbuf = malloc (hstbuflen);
00027 
00028   while ((res = gethostbyname_r (host, &hostbuf, tmphstbuf, hstbuflen,
00029                                  &hp, &herr)) == ERANGE)
00030     {
00031       /* Enlarge the buffer.  */
00032       hstbuflen *= 2;
00033       tmphstbuf = realloc (tmphstbuf, hstbuflen);
00034     }
00035 
00036   if (res != 0 || hp == NULL)
00037     {
00038       printf ("gethostbyname_r failed: %s (errno: %m)\n", strerror (res));
00039 
00040       if (access ("/etc/resolv.conf", R_OK))
00041        {
00042          puts ("DNS probably not set up");
00043          return 0;
00044        }
00045 
00046       return 1;
00047     }
00048 
00049   printf ("Got: %s %s\n", hp->h_name,
00050          inet_ntoa (*(struct in_addr *) hp->h_addr));
00051   return 0;
00052 }