c++ - 如何将 IPv4 映射的 IPv6 地址转换为 IPv4(字符串格式)?

标签 c++ c linux ipv6 ipv4

我有一个 struct sockaddr 结构,其中包含一个 IPv4-mapped-IPv6 地址,如 ::ffff:10.0.0.1。我只想在 C 编程语言的字符串中获取它的 IPv4 版本(在本例中为 10.0.0.1)。我该如何实现它?

最佳答案

由于您的结构包含一个 IPV6 地址,我假设您有一个 struct sockaddr *指针(我们将其命名为 addrPtr )指向一个 struct sockaddr_in6结构。

您可以轻松获取地址字节。

const uint8_t *bytes = ((const struct sockaddr_in6 *)addrPtr)->sin6_addr.s6_addr;

然后将 12 添加到指针,因为前 12 个字节并不重要(10 0x00,然后是 2 0xff)。只有最后 4 个重要。

bytes += 12;

现在,我们可以使用这四个字节来做任何我们想做的事。例如,我们可能会将它们存储到 IPv4 struct 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));

关于c++ - 如何将 IPv4 映射的 IPv6 地址转换为 IPv4(字符串格式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233246/

相关文章:

c++ - 继承是这样吗?

linux - 删除 sudoers 中没有密码的用户

linux - Wine 升级到版本 1.4.1 后 DLL 文件丢失

c - 使用指针从单链表中删除项目

c - 如何解决不为空的递归

c - 如何使用 C 将两个整数组合成一个字符串而不使用 malloc?

linux - "xargs -a file"将文件复制到文件夹

c++ - 在 OpenCL 内核中实现半精度 float 据类型

c++ - 控制台显示字符串结尾字符

c++ - 使用 libgit2 执行 Git Pull