Retrieving Geographic information based on IP Address using GeoIP2 Java API

1- What is GeoIP2?

GeoIP2 is an Java open source library. It offers freely GeoLite2 which is a location database coressponding with IP address, and the GeoIP2 API to work with these databases or works with web service to provide location data.

GeoLite2  is a free location database, its data is updated frequently on the first Tuesday of every month
GeoIP2 supports for many different programming languages such as: C #, C, Java, Perl, PHP, Python, ...
There are two way to work with GeoIP2 API:
  1. Download GeoLite2 with location data and use it as a local database. GeoIP2 API will retrieve geographic information from this database.
  2. Use GeoIP2 API to connect to web service which  provide location information via IP address, by this way you need a License_Key (must buy).

2- Download GeoIP2

If you use Maven:
<!-- http://mvnrepository.com/artifact/com.maxmind.geoip2/geoip2 -->

<dependency>
    <groupId>com.maxmind.geoip2</groupId>
    <artifactId>geoip2</artifactId>
    <version>2.3.1</version>
</dependency>
Or download library:

3- Download GeoLite2

Results are as follows:
Extract the two files:

4- Quick Create a Project to work with GeoIP2

Create a new Maven Project.
  • File/New/Other...
Enter:
  • Group Id: org.o7planning
  • Artifact Id: geoip2tutorial
  • Package: org.o7planning.geoip2tutorial
Maven dependency:
  • pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
          http://maven.apache.org/xsd/maven-4.0.0.xsd">
          
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.o7planning</groupId>
  <artifactId>geoip2tutorial</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>geoip2tutorial</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
 
 
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!-- http://mvnrepository.com/artifact/com.maxmind.geoip2/geoip2 -->
    <dependency>
        <groupId>com.maxmind.geoip2</groupId>
        <artifactId>geoip2</artifactId>
        <version>2.3.1</version>
    </dependency>


  </dependencies>
 
</project>

5- GeoIP2 Example

You have already downloaded GeoLite2 database and put in a local folder. This example using GeoIP2 Java API to retrieve geographic information corresponding to a specific IP address.
  • MyConstants.java
package org.o7planning.geoip2tutorial;

public class MyConstants {

   // Country Data.
   public static final String DATABASE_COUNTRY_PATH = "F:/GeoLite2/GeoLite2-Country.mmdb";
   
   // City Data.
   public static final String DATABASE_CITY_PATH = "F:/GeoLite2/GeoLite2-City.mmdb";
   
   
  
   public static final int MY_USER_ID = 42;
   
   public static final String MY_LICENSE_KEY = "license_key";
   
}
  • HelloGeoIP2.java
package org.o7planning.geoip2tutorial;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.Postal;
import com.maxmind.geoip2.record.Subdivision;

public class HelloGeoIP2 {

   public static void main(String[] args) throws IOException, GeoIp2Exception {
       
       // A File object pointing to your GeoLite2 database
       File dbFile = new File(MyConstants.DATABASE_CITY_PATH);

       // This creates the DatabaseReader object,
       // which should be reused across lookups.

       DatabaseReader reader = new DatabaseReader.Builder(dbFile).build();

       // A IP Address
       InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

       
       // Get City info
       CityResponse response = reader.city(ipAddress);

       // Country Info
       Country country = response.getCountry();
       System.out.println("Country IsoCode: "+ country.getIsoCode()); // 'US'
       System.out.println("Country Name: "+ country.getName()); // 'United States'
       System.out.println(country.getNames().get("zh-CN")); // '美国'

       Subdivision subdivision = response.getMostSpecificSubdivision();
       System.out.println("Subdivision Name: " +subdivision.getName()); // 'Minnesota'
       System.out.println("Subdivision IsoCode: "+subdivision.getIsoCode()); // 'MN'

       // City Info.
       City city = response.getCity();
       System.out.println("City Name: "+ city.getName()); // 'Minneapolis'

       // Postal info
       Postal postal = response.getPostal();
       System.out.println(postal.getCode()); // '55455'

       // Geo Location info.
       Location location = response.getLocation();
       
       // Latitude
       System.out.println("Latitude: "+ location.getLatitude()); // 44.9733
       
       // Longitude
       System.out.println("Longitude: "+ location.getLongitude()); // -93.2323

   }

}
Running the example:

6- GeoIP2 Web Service Example

Instead of connecting to a local database to retrieve geographic information corresponding to the IP address, you can use a Web service that provides this data. You need to buy a LICENSE_KEY. The following example guides you how to get geographic information corresponding to the IP address via the web service.
  • HelloGeoIP2Service.java
package org.o7planning.geoip2tutorial;

import java.io.IOException;
import java.net.InetAddress;

import com.maxmind.geoip2.WebServiceClient;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.Country;

public class HelloGeoIP2Service {

    

    public static void main(String[] args) throws IOException, GeoIp2Exception {

        WebServiceClient.Builder builder
              = new WebServiceClient.Builder(MyConstants.MY_USER_ID, MyConstants.MY_LICENSE_KEY);

        WebServiceClient client = builder.build();

        // IP Address
        InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

        // Do the lookup
        CountryResponse response = client.country(ipAddress);

        // Country Info .
        Country country = response.getCountry();
        System.out.println("Country Iso Code: "+ country.getIsoCode()); // 'US'
        System.out.println("Country Name: "+ country.getName()); // 'United States'
        System.out.println(country.getNames().get("zh-CN")); // '美国'
    }
    
}