Unix Socket Programming Question:
Download Questions PDF

Why do I sometimes lose a servers address when using more than one server?

Answer:

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.

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.

Download Unix Socket Programming Interview Questions And Answers PDF

Previous QuestionNext Question
How can my client work through a firewall/proxy server?system choose one for me on the connect() call? Should I bind() a port number in my client program, or let the?