IPv4/IPv6

本文介绍了一系列用于处理IP地址的函数,包括从字符串转换为IP地址的函数如inet_pton,从IP地址转换为字符串的函数如inet_ntop,以及获取主机名和地址信息的函数getaddrinfo和getnameinfo等。这些函数适用于IPv4和IPv6环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

IPv4 onlyIPv4 & IPv6Description
inet_addr interpret 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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值