Question

I have following IP list (in CIDR format) stored in a TXT file:<

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

But I don't know how can I determine whether my IP belongs to this list. I use the Qt C++ framework on Windows platform.

Was it helpful?

Solution

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:

OTHER TIPS

Walking through the Qt Documentation, I came across QHostAddress::parseSubnet(const QString & subnet), which can take a CIDR-style IP range and is new in Qt 4.5. Thus I could write the following code to solve it: (assume myIP is of type 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
}

As for better understanding and insights into the problem, @Jonathon Reinhart 's answer is really helpful.

The previous answers have already covered conversion from text to IP address class. You can check the range by using QHostAddress::isInSubnet(). This returns true when your IP address is within the address and mask provided.

For instance, here is an example which checks if an IP address is zeroconfig (169.254.1.0 to 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top