5

我在 TXT 文件中存储了以下 IP 列表(CIDR 格式):<

58.200.0.0/13
202.115.0.0/16
121.48.0.0/15
219.224.128.0/18
...

但是我不知道如何确定我的IP是否属于这个列表。我在 Windows 平台上使用 Qt C++ 框架。

4

3 回答 3

8

First you need to break up each CIDR notation range into a network (the dotted IP address) part, and a number of bits. Use this number of bits to generate the mask. Then, you only need to test if (range & mask) == (your_ip & mask), just as your operating system does:

Some psuedo-C code:

my_ip = inet_addr( my_ip_str )            // Convert your IP string to uint32
range = inet_addr( CIDR.split('/')[0] )   // Convert IP part of CIDR to uint32

num_bits = atoi( CIDR.split('/')[1] )     // Convert bits part of CIDR to int
mask = (1 << num_bits) - 1                // Calc mask

if (my_ip & mask) == (range & mask)
    // in range.

You can probably find a library to help you with this. Boost appears to have an IP4 class which has < and > operators. But you'll still need to do work with the CIDR notation.

Ref:

于 2012-09-11T06:15:20.080 回答
6

浏览 Qt 文档时,我遇到了 QHostAddress::parseSubnet(const QString & subnet),它可以采用 CIDR 样式的 IP 范围,并且是 Qt 4.5 中的新功能。因此我可以编写以下代码来解决它:(假设 myIP 的类型为 QHostAddress)

if(myIP.isInSubnet(QHostAddress::parseSubnet("219.224.128.0/18")) {
    //then the IP belongs to the CIDR IP range 219.224.128.0/18
}

至于更好地理解和洞察问题,@Jonathon Reinhart 的回答真的很有帮助。

于 2012-09-11T19:24:15.940 回答
5

前面的答案已经涵盖了从文本到 IP 地址类的转换。您可以使用QHostAddress::isInSubnet()检查范围。当您的 IP 地址在提供的地址和掩码范围内时,这将返回 true。

例如,这是一个检查 IP 地址是否为zeroconfig(169.254.1.0 到 169.254.254.255)的示例:

bool IsZeroconfig(const QHostAddress &ipAddress)
{
    QPair<QHostAddress, int> rangeZeroconfig = QHostAddress::parseSubnet("169.254.0.0/16");

    if (ipAddress.isInSubnet(rangeZeroconfig))
    {
        QPair<QHostAddress, int> preZeroconfig = QHostAddress::parseSubnet("169.254.1.0/24");
        QPair<QHostAddress, int> postZeroconfig = QHostAddress::parseSubnet("169.254.255.0/24");

        if ((!ipAddress.isInSubnet(preZeroconfig)) && (!ipAddress.isInSubnet(postZeroconfig)))
        {
            return true;
        }
    }

    return false;
}
于 2012-09-11T19:23:35.517 回答