如何映射IPv4的IPv6地址转换为IPv4(字符串格式)? [英] How to convert IPv4-mapped-IPv6 address to IPv4 (string format)?

查看:1843
本文介绍了如何映射IPv4的IPv6地址转换为IPv4(字符串格式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构sockaddr 包含与IPv4映射的IPv6地址结构 :: FFFF:10.0.0.1 。我想获得一个字符串只IPv4版本(在这种情况下, 10.0.0.1 )的C语言编程。我如何去实现呢?

I have a struct sockaddr structure containing an IPv4-mapped-IPv6 address like ::ffff:10.0.0.1. I want to obtain only the IPv4 version of it in a string (in this case, 10.0.0.1) in C programming language. How do I go about achieving it?

推荐答案

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

As your structure contains an IPV6 address, I'll assume your have a struct sockaddr * pointer (let's name it addrPtr) pointing to a struct sockaddr_in6 structure.

您可以轻松地获得该地址字节。

You can get the address bytes easily.

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

然后加入12指针,因为12第一个字节是不感兴趣(10 0×00 ,然后2 0xFF的 )。只有4最后的母校。

Then add 12 to the pointer because the 12 first bytes are not interesting (10 0x00, then 2 0xff). Only the 4 last ones mater.

bytes += 12;

现在,我们可以使用这些四个字节做任何我们想做的。例如,我们可以将它们存储到一个IPv4的 struct in_addr,这个地址

Now, we can use those four bytes to do whatever we want. For example, we might store them into a IPv4 struct in_addr address.

struct in_addr addr = { *(const in_addr_t *)bytes };

然后,我们可以使用 inet_ntop 得到一个字符串(在&LT宣布; ARPA / inet.h> )。

Then we can get a string using inet_ntop (declared in <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));

这篇关于如何映射IPv4的IPv6地址转换为IPv4(字符串格式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆