java ipv6转换成ipv4,如何映射IPv4的IPv6地址转换为IPv4(字符串格式)?

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?

解决方案

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;

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;

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 };

Then we can get a string using inet_ntop (declared in ).

char buffer[16]; // 16 characters at max: "xxx.xxx.xxx.xxx" + NULL terminator

const char *string = inet_ntop(AF_INET, &addr, buffer, sizeof(buffer));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值