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.
How do I identify an unknown device on my network? To see all of the devices connected to your network, type arp -a in a Command Prompt window. This will show you the allocated IP addresses and the MAC addresses of all connected devices.
How do I find a device by IP address? In Windows, go to All Programs -> Accessories. Then right-click on Command Prompt. Choose Run As Administrator and type in nslookup %ipaddress% putting an IP address instead of %ipaddress%.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With