简体   繁体   中英

C++ IP Address human-readable form

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.

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 .

我会用inet_ntop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM