[英]Is there a function that checks whether a sockaddr* named sptr points to an ipv4 or ipv6 address?
Is there a function that checks whether a sockaddr *
named sptr
points to an ipv4 or ipv6 address?是否有一个函数可以检查名为
sptr
的sockaddr *
是否指向 ipv4 或 ipv6 地址? For example I have the code below, how can I add onto it to get whether the address is ipv4 or ipv6, can I use getaddrinfo()
?例如我有下面的代码,我如何添加它来获取地址是 ipv4 还是 ipv6,我可以使用
getaddrinfo()
吗?
struct sockaddr *sptr;
struct sockaddr_in *ipv4_ptr;
You can test the sa_family
member:您可以测试
sa_family
成员:
switch (sptr->sa_family)
{
case AF_INET:
/* IPv4 */
break;
case AF_INET6:
/* IPv6 */
break;
default:
/* Something else */
}
If the sa_family
member is AF_INET
, that indicates an IPv4 address and the socket address is actually a struct sockaddr_in *
.如果
sa_family
成员是AF_INET
,则表示 IPv4 地址,而套接字地址实际上是struct sockaddr_in *
。 If the sa_family
member is AF_INET6
, that indicates an IPv6 address and the socket address is actually a struct sockaddr_in6
.如果
sa_family
成员是AF_INET6
,则表示 IPv6 地址,而套接字地址实际上是struct sockaddr_in6
。
The structures for AF_INET
and AF_INET6
address families are different, so you have to use different pointer types for them. AF_INET
和AF_INET6
地址族的结构不同,因此必须为它们使用不同的指针类型。 The way to proceed is to use:继续的方法是使用:
struct sockaddr *genptr;
... /* initialize genptr to point to the sockaddr structure */
switch (genptr->sa_family) {
case AF_INET: {
struct sockaddr_in *ipv4ptr = (struct sockaddr_in *)genptr;
/* check IPV4 addresses using ipv4ptr pointer */
} break;
case AF_INET6: {
struct sockaddr_in6 *ipv6ptr = (struct sockaddr_in6 *)genptr;
/* check IPV6 addresses using ipv6ptr pointer */
} break;
default: /* NEITHER IPV4 NOR IPV6, IPX? NETBIOS? X25? */
} /* switch */
although less efficient, you can convert your addresses with the version agnostic inet_ntop(3)
routine, and use some kind of regular expression matching algorithm to partially match addresses.虽然效率较低,但您可以使用与版本无关的
inet_ntop(3)
例程转换您的地址,并使用某种正则表达式匹配算法来部分匹配地址。 inet_ntop
routines get the generic pointer and build the ipv4/ipv6 ascii string for the network addresses in one shot. inet_ntop
例程获取通用指针并inet_ntop
构建网络地址的 ipv4/ipv6 ascii 字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.