实现ipv4和ipv6转换

#include
#include
#ifdef _WIN32
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WS2tcpip.h>
#else
#include <arpa/inet.h>
#endif

int inet4_pton(const char* cp, uint32_t& ap) {
uint32_t acc = 0;
uint32_t dots = 0;
uint32_t addr = 0;
uint32_t index = 0;

do {
    char cc = *cp;
    if (cc >= '0' && cc <= '9') {
        acc = acc * 10 + (cc - '0');
    }
    else if (cc == '.' || cc == '\0') {
        if (++dots > 3 && cc == '.') {
            return 0;
        }
        /* Fall through */

        if (acc > 255) {
            return 0;
        }

        addr += (acc << (index * 8));//各平台统一
        //从左往右,低位放
        //addr = addr << 8 | acc; // 这句是精华,每次将当前值左移八位加上后面的值
        ++index;
        acc = 0;
    }
} while (*cp++);

// Normalize the address 
if (dots < 3) {
    addr <<= 8 * (3 - dots);
}

ap = addr;
return 1;

}

void inet4_ntop(uint32_t value, std::string& str)
{
in_addr addr;
addr.s_addr = value;
str = inet_ntoa(addr);
}

int inet6_pton(const char* src, std::uint8_t* dst) {
if (src == nullptr) {
return 0;
}

constexpr  char  xdigits_l[] = "0123456789abcdef";
constexpr  char  xdigits_u[] = "0123456789ABCDEF";
const      char* xdigits = nullptr;
const      char* curtok = nullptr;
constexpr  int  NS_IN6ADDRSZ = 16;
constexpr   int NS_INT16SZ = 2;
std::uint8_t tmp[NS_IN6ADDRSZ] = { 0 };
std::uint8_t* tp = tmp;
std::uint8_t* endp = nullptr;
std::uint8_t* colonp = nullptr;
endp = tp + NS_IN6ADDRSZ;

/* Leading :: requires some special handling. */
if (*src == ':') {
    if (*++src != ':') {
        return 0;
    }
}

int              seen_xdigits = 0;
std::size_t    val = 0;
char  ch = 0;
while ((ch = *src++) != '\0') {
    const char* pch = nullptr;

    if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) {
        pch = strchr((xdigits = xdigits_u), ch);
    }

    if (pch != NULL) {
        val <<= 4;
        val |= (pch - xdigits);
        if (++seen_xdigits > 4) {
            return 0;
        }

        continue;
    }

    if (ch == ':') {
        curtok = src;
        if (!seen_xdigits) {
            if (colonp != nullptr) {
                return 0;
            }

            colonp = tp;
            continue;
        }
        else if (*src == 0) {
            return 0;
        }

        if (tp + NS_INT16SZ > endp) {
            return 0;
        }

        *tp++ = (u_char)(val >> 8) & 0xff;    //放在高位上
        *tp++ = (u_char)val & 0xff; //放在低位上
        seen_xdigits = 0;
        val = 0;
        continue;
    }

    if (ch == '.' && ((tp + 4) <= endp)) {
        uint32_t value = 0;
        if (inet4_pton(curtok, value)) {
            unsigned char* buf = (unsigned char*)&value;
            memcpy(tp, buf, 4);
            tp += 4;
            seen_xdigits = 0;
            break;  /*%< '\\' was seen by inet_pton4(). */
        }
    }

    return 0;
}

if (seen_xdigits) {
    if (tp + NS_INT16SZ > endp) {
        return 0;
    }

    *tp++ = (u_char)(val >> 8) & 0xff;
    *tp++ = (u_char)val & 0xff;
}

if (colonp != NULL) {
    if (tp == endp) {
        return 0;
    }

    const std::size_t n = tp - colonp;
    for (int i = 1; i <= n; i++) {
        endp[-i] = colonp[n - i];
        colonp[n - i] = 0;
    }

    tp = endp;
}

if (tp != endp) {
    return 0;
}

memcpy(dst, tmp, NS_IN6ADDRSZ);

return 1;

}

void inet6_ntop1(const u_char* src, std::string& dst) {
constexpr int NS_IN6ADDRSZ = 16;
constexpr int NS_INT16SZ = 2;
char tmp[100] = { 0 };
struct { int base, len; } best, cur;
std::size_t words[NS_IN6ADDRSZ / NS_INT16SZ] = { 0 };

memset(words, '\0', sizeof words);
for (int i = 0; i < NS_IN6ADDRSZ; i += 2) {
    words[i / 2] = (src[i] << 8) | src[i + 1];
}

best.base = -1;
cur.base = -1;
best.len = 0;
cur.len = 0;
for (int i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
    if (words[i] == 0) {
        if (cur.base == -1) {
            cur.base = i, cur.len = 1;
        }
        else {
            cur.len++;
        }
    }
    else {
        if (cur.base != -1) {
            if (best.base == -1 || cur.len > best.len) {
                best = cur;
            }

            cur.base = -1;
        }
    }
}
if (cur.base != -1) {
    if (best.base == -1 || cur.len > best.len) {
        best = cur;
    }
}
if (best.base != -1 && best.len < 2) {
    best.base = -1;
}

/*
 * Format the result.
 */
char* tp = tmp;
for (int i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
    /* Are we inside the best run of 0x00's? */
    if (best.base != -1 && i >= best.base &&
        i < (best.base + best.len)) {
        if (i == best.base) {
            *tp++ = ':';
        }

        continue;
    }
    /* Are we following an initial run of 0x00s or any real hex? */
    if (i != 0) {
        *tp++ = ':';
    }

    /* Is this address an encapsulated IPv4? */
    if (i == 6 && best.base == 0 &&
        (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
        std::string temp;
        temp.resize(20);
        memcpy(&temp[0], (char*)src + 12, 4);

        uint32_t value = 0;
        uint32_t* ptr = (uint32_t*)temp.data();
        value = *ptr;

        inet4_ntop(value, temp);
        std::size_t len = strlen(temp.c_str());
        memcpy(tp, temp.c_str(), len);
        tp += len;
        break;
    }

    std::stringstream sstream;
    sstream << std::hex << words[i];
    std::size_t len = strlen(sstream.str().c_str());
    memcpy(tp, sstream.str().c_str(), len);
    tp += len;
}
/* Was it a trailing run of 0x00's? */
if (best.base != -1 && (best.base + best.len) == (NS_IN6ADDRSZ / NS_INT16SZ)) {
    *tp++ = ':';
}

*tp++ = '\0';

std::size_t len = strlen(tmp);
dst.resize(len);
memcpy(&dst[0], tmp, len);

}

int main()
{
/ipv4测试*/
std::string addr = “255.198.127.105”;
std::string addr100;
addr100.resize(20);
uint32_t value;
inet4_pton(addr.c_str(), value);
std::cout << value << std::endl;

inet4_ntop(value, addr100);
std::cout << addr100 << std::endl;

///*******ipv6测试*******/
//char* addr1 = _strdup("2000:0000:0000:0000:0001:2345:6789:abcd");
//struct in6_addr ip;
//struct in6_addr ip1;
//std::string str;
//std::string sss;
inet_pton(AF_INET6, addr1, &ip);
//inet6_pton(addr1, (uint8_t*)&ip.u);
//ip1.u = ip.u;
inet6_ntop1(ip.u.Byte, str);

//sss.resize(100);
//inet_ntop(AF_INET6, &ip1, &sss[0], INET6_ADDRSTRLEN);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹平华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值