#ifndef _WIN32
typedef struct in_addr IN_ADDR;
typedef struct in6_addr IN6_ADDR;
#endif
static int Ipv4MapToIpv6(const char* ipv4, char* ipv6)
{
if (!ipv4) {
ipv6[0] = ':';
ipv6[1] = ':';
return 0;
}
if (strchr(ipv4, ':')) {
strcpy(ipv6, ipv4);
return 0;
}
IN_ADDR inIpv4;
inIpv4.s_addr = inet_addr(ipv4);
IN6_ADDR inIpv6;
memset(&inIpv6, 0, sizeof(inIpv6));
uint8_t* p = (uint8_t*)&inIpv6;
p[10] = 0xff;
p[11] = 0xff;
memcpy(&p[12], &inIpv4.s_addr, 4);
inet_ntop(AF_INET6, &inIpv6, ipv6, INET6_ADDRSTRLEN);
return 0;
}
static int Ipv6MapToIpv4(const char* ipv6, char* ipv4)
{
if (!ipv6) {
strcpy(ipv4, "0.0.0.0");
return 0;
}
if (strchr(ipv6, ':')) {
} else {
strcpy(ipv4, ipv6);
return 0;
}
IN6_ADDR inIpv6;
inet_pton(AF_INET6, ipv6, &inIpv6);
const static uint8_t ipv4MappedPrefix[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
if (0 == memcmp(&inIpv6, ipv4MappedPrefix, 12)) {
// ipv4 mapped address
uint32_t ipv4Addr = *(uint32_t*)(&inIpv6.s6_addr[12]);
inet_ntop(AF_INET, &ipv4Addr, ipv4, INET_ADDRSTRLEN);
return 0;
}
return -1;
}
IPv4和IPv6的相互转换
于 2023-11-24 09:11:16 首次发布