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: