Because this question still lacks a complete answer, I decided to post it here.
Store the range's start and end IP address as an integer and when querying, use $lte
and $gte
MongoDB operators to find the match. Also, create indexes on the start
and end
fields so the performance is good even with a bigger amount of documents to search through.
Let's perform one example with an IP range starting with 2.0.0.0
and ending with 8.255.255.255
. Two IP addresses are going to be tested: a) 4.5.6.7
, b) 60.70.80.90
:
You need to convert all IPs to integers.
- Range start
2.0.0.0
= 33554432
- Range end
8.255.255.255
= 150994943
- Testing IP a
4.5.6.7
= 67438087
- Testing IP b
60.70.80.90
= 1011241050
For storing the IP range in the database you can create a MongoDB document like the one below this paragraph. If you'd like to enlist just one IP, both the start
and the end
fields will need to have the same value.
{ "start": 33554432, "end": 150994943 }
Then perform a find query using $lte
and $gte
operators which will get the integer value of the IP to be tested.
// this will result in one match because 67438087 = 4.5.6.7
db.collection.find({
start: { $lte: 67438087 },
end: { $gte: 67438087 },
})
// this will end up with no result because 1011241050 = 60.70.80.90
db.collection.find({
start: { $lte: 1011241050 },
end: { $gte: 1011241050 },
})