UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2002-07-25 06:40 PM

HectorLasso
Administrator
From: Colombia
Registered: 2002-06-12
Posts: 353

Re: 3.4 - Why do I sometimes lose a server's address?

6
From Andrew Gierth (andrew@erlenstar.demon.co.uk):

Take a careful look at struct hostent. Notice that almost everything in it is a pointer? All these pointers will refer to statically allocated data.

For example, if you do:

struct hostent *host = gethostbyname(hostname);

then (as you should know) a subsequent call to gethostbyname() will overwrite the structure pointed to by 'host'.

But if you do:

struct hostent myhost;
    struct hostent *hostptr = gethostbyname(hostname);
    if (hostptr) myhost = *host;

to make a copy of the hostent before it gets overwritten, then it still gets clobbered by a subsequent call to gethostbyname(), since although myhost won't get overwritten, all the data it is pointing to will be.

You can get round this by doing a proper 'deep copy' of the hostent structure, but this is tedious. My recommendation would be to extract the needed fields of the hostent and store them in your own way.

Robin Paterson (etmrpat@etm.ericsson.se) has added:

It might be nice if you mention MT safe libraries provide complimentary functions for multithreaded programming. On the solaris machine I'm typing at, we have gethostbyname and gethostbyname_r (_r for reentrant). The main difference is, you provide the storage for the hostent struct so you always have a local copy and not just a pointer to the static copy.

Offline

Board footer

Powered by FluxBB