host name to IP address

There's a piece in a C program I'm writing (Linux) that simply needs to take a host name and return an IP address (e.g., take 'mail.gnu.org' and return 199.232.76.166). I've gotten a successful status from getaddrinfo, but don't see any of the fields in the result structure that has what I'm looking for, and similar for the structure returned by gethostbyname. I'm wondering if I need to use a function like 'inet_addr' on one of those values to get what I'm looking for. Thank you.

That's right. inet_ntoa actually.

gethostbyname(), gethostbyaddr()

Google is your friend.

I tried this:

struct in_addr host_addr
.
.
.
.

host_addr.s_addr = inet_addr(cat_str);
printf("IP address ==> %s\n", inet_ntoa(host_addr));

All I get is a series of 255.255.255.255 for each of the hosts I try ('cat_str' being something like 'mail.gnu.org'). Maybe I need to pass 'cat_str' into 'gethostbyname' and take the 'host_aliases' out of that and pass it into inet_addr. I guess I'm having a little trouble with the terminology being used by these man pages and making sure I know which form of the address they are referring to.

There may be a more direct way, but you can get the IP address via ping.

ping -c 1 hostname.com

ShawnMilo

Did you try the example code at the other end of that link?

inet_addr wants an IP address as a string ("dotted decimal notation", in the parlance), not a host name. Also, you should check its return status, to figure out if something went wrong.

Post the C program because without the source it is not possible to figure out why the fields of the structure are not being filled. My guess would be that you have declared a pointer to that structure but not an object of that type. In any case it would be nice to see the code.

I found a code snippet while via a web search:

struct hostent *hp;
.
.
.

hp = gethostbyname (cat_str);
.
.
.

for (i=0 ......
printf( . . . . . inet_ntoa(*(struct in_addr *)hp->h_addr_list[i]));

First of all make sure your have a working DNS server address. DNS server is responsible for converting domain name to a IP Address. Without a DNS server your codes output will be incorrect. Try to ping the name and see the DNS entry is correct.

example:
ping mail.gnu.org
ping www.gmail.com

---------------
Ram Das