Search code examples
javapostgresqlmaxmind

How to calculate end IP in the range, based on start IP and network mask length in JAVA


I'm experimenting with the MaxMind GeoIP (Geo lite 2) DB.

In source file GeoLite2-Country-Blocks.csv from (GeoLite2-Country-CSV.zip) from MaxMind site, I have this line:

::ffff:87.197.0.0,112,3057568,3057568,,,,,0,0

I have a starting IPv4 IP address ::ffff:87.197.0.0 and I have the IPv6 network mask length 112, how can I calculate the last IP in the range in JAVA ?

The reason is I'm importing the MaxMind Geo lite 2 database in CSV format into a PostgreSQL database, so I need import start IP address into one DB column and last IP address into another DB column.

thanks.

Ivan


Solution

  • If you are using Postgres, you should use the cidr or inet type. With those types, you can insert the data in the form ::ffff:87.197.0.0/112 (or 87.197.0.0/16 for the non-IPv6 mapped address). Using the network types, you can take advantage of Pg's network functions when doing queries.