Store and Compare IP address in MongoDB – A study

Hi Guys,

I would like to share an issue and possible solutions for the issue related to store and compare IP address in MongoDB.

The Requirement

Client have its own master IP Address list marked as GOOD and BAD ip address, in master list it may have plain IP address (i.e. or in CIDR notation (i.e. The actual task is to store the master data and compare it with user specific data.

User Specific Data: Here we are using netstat command to get network connections (foreign address: both incoming and outgoing) on which the computer is connected.

CIDR Notation: CIDR means Classless Inter-Domain Routing. It used for subnetting and in simple term it used to define range. For example if we use so it contains 256 ip addresses starting from to

Initially i have decided to generate range of CIDR and store it into MongoDB, the hurdle not came is client have choice to add many ip address with cidr so we ends up with billions of ip address(It returns 2147483648 ip addresses if our ip is and it take time to compare multiple address.


The one solution which i applied here to compare user’s ip address with master list is i have converted a first address and last address which i got from CIDR notation to long and did mathematical operation to check whether particular ip address lies between range or not.

I have used below mongo structure and java code to convert ip to long.

Mongo Structure:

Java Code to convert ip address to Long:

Now we can easily execute a query to check whether particular ip is in range or not using code below.

Where mongoTemplate is instance of

CustomNetwork is class having fields status, start and end.

Share current post by copy:
Hope it may help somewhere.

Thanks, Yogesh P