IPv4和IPv6的相互转换

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值