IPv4 only | IPv4 & IPv6 | Description |
inet_addr | interpret character strings that represent numbers expressed in the IPv4 standard `.' notation, returning numbers suitable for use as IPv4 addresses. | |
inet_aton | inet_ntop | 字符串地址转为IP地址 |
inet_ntoa | inet_pton | IP地址转为字符串地址 |
gethostbyname | getipnodebyname | 由名字获得IP地址 |
gethostbyaddr | getipnodebyaddr | IP地址获得名字 |
getaddrinfo | 获得全部地址信息 | |
getnameinfo | 获得全部名字信息 |
char *inet_ntoa(struct in_addr in);
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
These functions are deprecated because they don't handle IPv6! Use inet_ntop() or inet_pton() instead!
struct hostent *gethostbyname(const char *name);
struct hostent *gethostbyaddr(const char *addr, int len, int type);
These two functions are superseded by getaddrinfo() and getnameinfo()! In particular, gethostbyname() doesn't work well with IPv6. (though, gethostbyaddr(...) can work with IPv6.)
// Follow code section are how gethostbyaddr(...) used with both IPv4 and IPv6.
struct hostent *he;
struct in_addr ipv4addr;
struct in6_addr ipv6addr;
inet_pton(AF_INET, "192.0.2.34", &ipv4addr);
he = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
printf("Host name: %s/n", he->h_name);
inet_pton(AF_INET6, "2001:db8:63b3:1::beef", &ipv6addr);
he = gethostbyaddr(&ipv6addr, sizeof ipv6addr, AF_INET6);
printf("Host name: %s/n", he->h_name);
// Code example of getipnodebyname(...) and getipnodebyaddr(...)
struct in6_addr in6;
int error_num;
struct hostent *hp;
/* argv[1] can be a pointer to a hostname or literal IP address */
hp = getipnodebyname(argv[1], AF_INET6, AI_DEFAULT, &error_num);
inet_pton(AF_INET6, argv[1], &in6);
hp = getipnodebyaddr (&in6, sizeof(in6), AF_INET6, &error_num);
如上表格所示,IP V4专用函数在IP V6环境下已经不能使用,他们一般有一个对应的IP V4/V6通用函数,但是在使用通用函数的时候需要一个协议类型参数(AF_INET/AF_INET6)。另外还增加了两个功能强大的函数getaddrinfo( )和getnameinfo( ),几乎可以完成所有的地址和名字转化的功能。
Reference to Beej's Guide to Network Programming.