Unix Socket Programming Question:

How do I convert a string into an internet address?

Tweet Share WhatsApp

Answer:

If you are reading a host's address from the command line, you may not know if you have an aaa.bbb.ccc.ddd style address, or a host.domain.com style address. What I do with these, is first try to use it as a aaa.bbb.ccc.ddd type address, and if that fails, then do a name lookup on it. Here is an example:

/* Converts ascii text to in_addr struct.
/* NULL is returned if the
address can not be found. */
struct in_addr *atoaddr(char *address) {
struct hostent *host;
static struct in_addr saddr;

/* First try it as aaa.bbb.ccc.ddd. */
saddr.s_addr = inet_addr(address);
if (saddr.s_addr != -1) {
return &saddr;
}
host = gethostbyname(address);
if (host != NULL) {
return (struct in_addr *) *host->h_addr_list;
}
return NULL;
}

Download Unix Socket Programming PDF Read All 62 Unix Socket Programming Questions
Previous QuestionNext Question
Why does connect() succeed even before my server did an accept()?What are socket exceptions? What is out-of-band data?