是否有一个库函数来确定IP地址(IPv4和IPv6)是C / C ++中的私有/本地的? [英] Is there a library function to determine if an IP address (IPv4 and IPv6) is private/local in C/C++?

查看:1139
本文介绍了是否有一个库函数来确定IP地址(IPv4和IPv6)是C / C ++中的私有/本地的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1,给定一个32位整数值,如何精确确定它是否为私有IPv4地址。

1, Given a 32-bit integer value, how to exactly determine if it is private IPv4 address.

2,给定一个128位整数值,以确切地确定它是否是私有IPv6地址。

2, Given a 128-bit integer value, how to exactly determine if it is private IPv6 address.

考虑不同平台上的IP地址的字节顺序,它是容易错误的写每个时间。所以我认为应该有一个库函数为这个,是有?

Consider the byte order of the IP address on different platforms, it is error-prone to write such a common little function every time. So I think there should be a library function for this, is there?

推荐答案

这将让你开始。我没有打扰,包括链接本地地址范围,但这是一个练习,你可以通过修改下面的代码来完成。

This will get you started. I didn't bother including the "link local" address range, but that's an exercise left for you to complete by modifying the code below.

IPV6略有不同。和你的问题是略有畸形,因为大多数系统没有本地的128位类型。 IPv6地址通常包含在嵌入在sockaddr_in6结构中的16字节数组。

IPV6 is slightly different. And your question is slightly malformed since most systems don't have a native 128-bit type. IPv6 addresses are usually contained as an array of 16 bytes embedded in a sockaddr_in6 struct.

完成此示例所需的一切都在此链接

Everything you need to know to finish this example is at this link here.

// assumes ip is in HOST order.  Use ntohl() to convert as approrpriate

bool IsPrivateAddress(uint32_t ip)
{
    uint8_t b1, b2, b3, b4;
    b1 = (uint8_t)(ip >> 24);
    b2 = (uint8_t)((ip >> 16) & 0x0ff);
    b3 = (uint8_t)((ip >> 8) & 0x0ff);
    b3 = (uint8_t)(ip & 0x0ff);

    // 10.x.y.z
    if (b1 == 10)
        return true;

    // 172.16.0.0 - 172.31.255.255
    if ((b1 == 172) && (b2 >= 16) && (b2 <= 31))
        return true;

    // 192.168.0.0 - 192.168.255.255
    if ((b1 == 192) && (b2 == 168))
        return true;

    return false;
}

这篇关于是否有一个库函数来确定IP地址(IPv4和IPv6)是C / C ++中的私有/本地的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆