IP2Location: A Free IP Database — Java Client and BIN File Downloads

This post uses the IP2Location LITE database and queries it by reading the BIN file directly. The code is a trimmed-down version of the official sample, published to Maven Central.

This post uses the IP2Location LITE database and queries it by reading the BIN file directly. The code is a trimmed-down version of the official sample, published to Maven Central.

Downloading the IP2Location BIN File

The database BIN file is updated once a month.

Download the BIN file here:

https://github.com/renfei/ip2location/releases

Or clone any of these repos and unzip it yourself:

Adding the Maven Dependency

Java 8 is required.

<dependency>
    <groupId>net.renfei</groupId>
    <artifactId>ip2location</artifactId>
    <version>1.0.2</version>
</dependency>

Compared with the official client, I removed the IP2LocationWebService along with every other third-party dependency. That keeps it lightweight and avoids version conflicts.

Usage Example

public static void main(String[] args) {
    IP2Location loc = new IP2Location();
    try {
        String ip = "8.8.8.8";
        String binfile = "/usr/data/IP2LOCATION-LITE-DB11.BIN";
        loc.Open(binfile, true);
        IPResult rec = loc.IPQuery(ip);
        if ("OK".equals(rec.getStatus())) {
            System.out.println(rec);
        } else if ("EMPTY_IP_ADDRESS".equals(rec.getStatus())) {
            System.out.println("IP address cannot be blank.");
        } else if ("INVALID_IP_ADDRESS".equals(rec.getStatus())) {
            System.out.println("Invalid IP address.");
        } else if ("MISSING_FILE".equals(rec.getStatus())) {
            System.out.println("Invalid database path.");
        } else if ("IPV6_NOT_SUPPORTED".equals(rec.getStatus())) {
            System.out.println("This BIN does not contain IPv6 data.");
        } else {
            System.out.println("Unknown error." + rec.getStatus());
        }
        System.out.println("Java Component: " + rec.getVersion());
    } catch (Exception e) {
        System.out.println(e);
        e.printStackTrace(System.out);
    } finally {
        loc.Close();
    }
}

Point binfile at a different file to query IPv6 instead of IPv4, so you can instantiate two IP2Location objects — one for IPv4 and one for IPv6.

You can see it running on my site here: https://blog.renfei.net/kitbox/ip