我有一个struct sockaddr
包含 IPv4 映射 IPv6 地址的结构,例如::ffff:10.0.0.1
。我只想获取字符串中的 IPv4 版本(在本例中,10.0.0.1
)用C语言编程。我该如何实现它?
由于您的结构包含 IPV6 地址,我假设您有一个struct sockaddr *
指针(我们将其命名为addrPtr
)指向一个struct sockaddr_in6
结构。
您可以轻松获取地址字节。
const uint8_t *bytes = ((const struct sockaddr_in6 *)addrPtr)->sin6_addr.s6_addr;
然后将 12 添加到指针,因为前 12 个字节并不有趣(100x00
,然后 20xff
)。只有最后 4 个重要。
bytes += 12;
现在,我们可以使用这四个字节来做我们想做的事情。例如,我们可以将它们存储到 IPv4struct in_addr
地址。
struct in_addr addr = { *(const in_addr_t *)bytes };
然后我们可以使用得到一个字符串inet_ntop
(声明于<arpa/inet.h>
).
char buffer[16]; // 16 characters at max: "xxx.xxx.xxx.xxx" + NULL terminator
const char *string = inet_ntop(AF_INET, &addr, buffer, sizeof(buffer));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)