Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ IP Address human-readable form

Tags:

c++

c

sockets

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.

like image 266
Kevin Anderson Avatar asked Aug 18 '09 16:08

Kevin Anderson


1 Answers

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: https://beej.us/guide/bgnet/html/multi/syscalls.html

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

like image 121
Tyler McHenry Avatar answered Sep 22 '22 20:09

Tyler McHenry