gpt4 book ai didi

c++ - 如何从 IPv4 映射的 IPv6 地址解析 IPv4 地址?

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:35 30 4
gpt4 key购买 nike

如何从 IPv4 映射的 IPv6 地址获取 IPv4 地址?

例如,我有一个 IP 地址 ::FFFF:129.144.52.38。从中,我需要提取 129.144.52.38。是否有任何用于此目的的 API?

我可以使用以下函数识别 IPv6 或 IPv4 地址族

int getaddrfamily(const char *addr)
{
struct addrinfo hint, *info =0;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
// Uncomment this to disable DNS lookup
//hint.ai_flags = AI_NUMERICHOST;
int ret = getaddrinfo(addr, 0, &hint, &info);
if (ret)
return -1;
int result = info->ai_family;
freeaddrinfo(info);
return result;
}

如果我给出一个 IPv4 映射的 IPv6 地址,那么如何确定它是否是一个映射地址?是否有任何套接字 API 可以从映射的 IPv6 地址中提取 IPv4?

最佳答案

尝试这样的事情:

#ifndef IN6_IS_ADDR_V4MAPPED
#define IN6_IS_ADDR_V4MAPPED(a) \
((((a)->s6_words[0]) == 0) && \
(((a)->s6_words[1]) == 0) && \
(((a)->s6_words[2]) == 0) && \
(((a)->s6_words[3]) == 0) && \
(((a)->s6_words[4]) == 0) && \
(((a)->s6_words[5]) == 0xFFFF))
#endif

unsigned long getIPv4addr(const char *addr)
{
struct addrinfo hint, *info = 0;
unsigned long result = INADDR_NONE;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
// Uncomment this to disable DNS lookup
//hint.ai_flags = AI_NUMERICHOST;
if (getaddrinfo(addr, 0, &hint, &info) == 0)
{
switch (info->ai_family)
{
case AF_INET:
{
struct sockaddr_in *addr = (struct sockaddr_in*)(info->ai_addr);
result = addr->sin_addr.s_addr;
break;
}

case AF_INET6:
{
struct sockaddr_in6 *addr = (struct sockaddr_in6*)(info->ai_addr);
if (IN6_IS_ADDR_V4MAPPED(&addr->sin6_addr))
result = ((in_addr*)(addr->sin6_addr.s6_addr+12))->s_addr;
break;
}
}
freeaddrinfo(info);
}
return result;
}

关于c++ - 如何从 IPv4 映射的 IPv6 地址解析 IPv4 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272656/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com