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

IhaveastructsockaddrstructurecontaininganIPv4-mapped-IPv6addresslike::ffff:10.0.0.1.IwanttoobtainonlytheIPv4versionofitinastring(inthiscase,10.0.0.1)inCprogramminglangu…

大家好,又见面了,我是你们的朋友全栈君。

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/128408.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号