函式原型: #include <arpa/inet.h> const char *inet_ntop(int af, const void *src, char *dst, socklen_t size); //"network to printable"
int inet_pton(int af, const char *src, void *dst);
一个使用例子:
char str[INET6_ADDRSTRLEN]; if(inet_ntop(AF_INET6, &sin6_addr, str, INET6_ADDRSTRLEN) == NULL){ perror("inet ntop/n"); printf("error "); } syslog(LOG_ERR, "sin6_addr=%s ", str); printf("sin6_addr=%s ", str);
推荐阅读:
Beej's Guide to Network Programming
English:
https://beej.us/guide/bgnet/html/multi/inet_ntopman.html
繁体中文,目录清晰:
http://beej-zhtw.netdpi.net/09-man-manual/9-14-inet_ntop-inet_pton
// IPv6 demo of inet_ntop() and inet_pton() // (basically the same except with a bunch of 6s thrown around) struct sockaddr_in6 sa; char str[INET6_ADDRSTRLEN]; // store this IP address in sa: inet_pton(AF_INET6, "2001:db8:8714:3a90::12", &(sa.sin6_addr)); // now get it back and print it inet_ntop(AF_INET6, &(sa.sin6_addr), str, INET6_ADDRSTRLEN); printf("%s ", str); // prints "2001:db8:8714:3a90::12"
// Helper function you can use: //Convert a struct sockaddr address to a string, IPv4 and IPv6: char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen) { switch(sa->sa_family) { case AF_INET: inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), s, maxlen); break; case AF_INET6: inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s, maxlen); break; default: strncpy(s, "Unknown AF", maxlen); return NULL; } return s; }
参考:
网络编程中常见地址结构与转换(IPv4/IPv6)
https://www.cnblogs.com/sunada2005/archive/2013/08/06/3240724.html
Linux网络编程IPv4和IPv6的inet_addr、inet_aton、inet_pton等函数小结
https://blog.csdn.net/ithomer/article/details/6100734
一个例子很清晰:
https://gist.github.com/q2hide/244bf94d3b72cc17d9ca