您的位置:首页 > 其它

IPv4/IPv6

2009-04-17 15:34 288 查看
IPv4 onlyIPv4 & IPv6Description
inet_addrinterpret character strings that represent numbers expressed in the IPv4 standard `.' notation, returning numbers suitable for use as IPv4 addresses.
inet_atoninet_ntop字符串地址转为IP地址
inet_ntoainet_ptonIP地址转为字符串地址
gethostbynamegetipnodebyname由名字获得IP地址
gethostbyaddrgetipnodebyaddrIP地址获得名字
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: