cposixgethostbynamegethostbyaddr

When would multiple calls to gethostbyname be unsafe?


From gethostbyname(3) - Linux manual

The functions gethostbyname() and gethostbyaddr() may return pointers
to static data, which may be overwritten by later calls.  Copying the
struct hostent does not suffice, since it contains pointers; a deep
copy is required.

I've written programs that make multiple calls to gethostbyname and haven't had anything break because of overwriting of static data.

Could I ask for an example when multiple calls to gethostbyname would overwrite this static data?


Solution

  • It will be a problem when you do something like this:

    struct hostent *google = gethostbyname("www.google.com");
    struct hostent *youtube = gethostbyname("www.youtube.com");
    
    printf("Official name of host for www.google.com: %s\n", google->h_name);
    printf("Official name of host for www.youtube.com: %s\n", youtube->h_name);
    
    printf("same? %s\n", google == youtube ? "yes" : "no");
    

    The output will be

    Official name of host for www.google.com: youtube-ui.l.google.com
    Official name of host for www.youtube.com: youtube-ui.l.google.com
    same? yes
    

    which is wrong, as the official host name of www.google.com is www.google.com and not youtube-ui.l.google.com. The problem is that google and youtube point at the same location (as you can see from the same? yes output), so the information about www.google.com is lost when you execute gethostbyname again.

    If you however do

    struct hostent *google = gethostbyname("www.google.com");
    printf("Official name of host for www.google.com: %s\n", google->h_name);
    
    struct hostent *youtube = gethostbyname("www.youtube.com");
    printf("Official name of host for www.youtube.com: %s\n", youtube->h_name);
    

    then the output will be

    Official name of host for www.google.com: www.google.com
    Official name of host for www.youtube.com: youtube-ui.l.google.com
    

    So as long as you process the hostent pointer of the first gethostbyname call before you do the second call, you will be fine.