如何从 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;
}
我是一名优秀的程序员,十分优秀!