tags:

views:

266

answers:

2

In C/C++, you can use the regular gethostbyname() call to turn a dotted-IP address string ("127.0.0.1" in the case of localhost) into a structure suitable for standard socket calls.

Now how do you translate it back? I know I can do some bit-shifting to get exactly which bit sets I want and just print those out, but is there any "standard" function to do this for me? It's for output into log files, so that I "really" know who/what I'm connecting to, and thus a human-readable dotted-address is a lot better than the raw hex.

Thanks.

+2  A: 

I'd use inet_ntop.

Chris Jester-Young
+10  A: 

First of all, in new code you should generally prefer using getaddrinfo() to gethostbyname(), which is old and clunky and is tough to use to support both IPv4 and IPv6. See here: http://beej.us/guide/bgnet/output/html/multipage/syscalls.html

Secondly, the function that does what you want is called inet_ntop.

Tyler McHenry
I marked this as right, but found out it didn't work under windows, but did find that the right function call there is inet_ntoa which does nearly the same thing. It doesn't support IPv6 according to beej, but it's in the normal winsock.h for win32 users.
Kevin