【问题标题】:How to convert IP4 and IP6 addresses to long value in C?如何在 C 中将 IP4 和 IP6 地址转换为长值?
【发布时间】:2012-03-09 08:12:06
【问题描述】:

我需要一个同时适用于 IP4 和 IP6 地址的函数,并且我需要将地址从它的字符串表示 (IP4) 或十六进制表示 (IP6) 转换为它的长值。我目前的代码是:

struct addrinfo *addr;
// This converts an char* ip_address to an addrinfo, so now I know whether 
// it's a IP4 or IP6 address
int result = getaddrinfo(ip_address, NULL, NULL, &addr);
if (result ==0) {
    struct in_addr dst;
    result = inet_pton(addr->ai_family, ip_address, &dst);
    long ip_value = dst->s_addr;
    freeaddrinfo(addr);
    return ip_value;
}

我确实从 dst->s_addr 得到了很长的信息,但我很确定这是不正确的。非常感谢任何有关如何解决此问题的指示!

【问题讨论】:

    标签: c sockets ip ip-address


    【解决方案1】:

    首先,您的dst 不够大,无法容纳IPv6 地址:

    unsigned char buf[sizeof(struct in6_addr)]; /* Since it's larger than in_addr */
    int result = getaddrinfo(ip_address, NULL, NULL, buf);
    

    如果地址是 IPv4,bufin_addr,即 uint32_t

    uint32_t u;
    memcpy(&u, buf, sizeof(u));
    

    如果地址是 IPv6 转换为 long 实际上没有意义。您需要128 位宽的东西或自己滚动。最后一点并不容易,所以问问自己:你确定你需要这个吗?

    【讨论】:

    • 您好,非常感谢您的帮助!当您说我的 inet_pton 调用错误时,您的意思是 getaddrinfo 调用?关于 IP6,是的,它应该是 128 位,我知道我们将需要这个,所以我宁愿现在修复它....我还需要修复 inet_pton 调用吗?
    • @DrDee 对不起,我误读了这个问题。您的inet_pton 电话实际上几乎是正确的,我编辑了我的答案。
    • buf 中的值始终是 140734799738144(我猜这是 struct in6_addr 的大小)。很抱歉一直问,但我如何从这里获得 IP 地址的“长”表示?
    • @DrDee in6_addr 要大得多 (2^128)。除了手工,我不知道有什么方法可以得到 128 位数字的十进制表示。
    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 2018-12-03
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2013-05-09
    相关资源
    最近更新 更多