Explore our IP Address Database Downloads for instant access to our IP address insights

Learn more
a year ago by IPinfo Team 8 min read

Complete guide on using IPinfo’s API and data downloads in Java

How to: IP geolocation and more in Java

In today's digital landscape, extracting IP address meta-information, such as the geographic origins of online activities, identifying anonymous IP addresses, and retrieving network-level metadata from IP, has a wide range of applications. Whether it's to enhance user experience, bolster cybersecurity measures, or add sales and marketing intelligence data, IPinfo's IP data unlocks a new dimension of insight.

In this blog post, we will dive into the seamless integration of IPinfo's powerful API and data download services with the Java programming language. Discover how leveraging IPinfo's data in your Java project can empower you with accurate and reliable IP information.

Using our Java Client Library for using the API

If you like to use our API in the Java ecosystem, we highly recommend you check our official Java client library.

https://github.com/ipinfo/java

Even though you can get IP data from our API endpoint by making HTTP calls to the API, the IPinfo official Java library comes with a few bells and whistles, which makes using our API more effective. Such features include:

1. Installing the IPinfo API Client library

You can install the IPinfo API library using Maven. Simply add the following code to your pom.xml file:

<dependency>
    <groupId>io.ipinfo</groupId>
    <artifactId>ipinfo-api</artifactId>
    <version>2.2</version>
    <scope>compile</scope>
</dependency>

2. Getting started with the library

You should, at this point, copy your IPinfo access token from your profile dashboard. Then, you can initiate your Java codebase. In your /src/main/java/com/mycompany/app create a file called [Main.java](<http://Main.java>) and write the following code:

package com.mycompany.app;

import io.ipinfo.api.IPinfo;
import io.ipinfo.api.errors.RateLimitedException;
import io.ipinfo.api.model.IPResponse;

public class Main {
    public static void main(String... args) {
        // Add your token here
        // <https://ipinfo.io/account/token>
        IPinfo ipInfo = new IPinfo.Builder()
                .setToken("YOUR_TOKEN")
                .build();
        try {
            // Lookup an IP address
            IPResponse response = ipInfo.lookupIP("8.8.8.8");

            // Print out the response object
            System.out.println(response);
        } catch (RateLimitedException ex) {
            // Handle rate limits here.
            System.out.println("API rate limit reached.");
        }
    }
}

Here, we are first importing the necessary classes from the io.ipinfo.api package that we installed. Then, in the Main class, we create an instance of the IPinfo class using the builder pattern. The ipinfo instance is initialized with the IPinfo access token. We use the lookupIP method of the ipinfo instance to perform an IP address lookup of the IP address 8.8.8.8. We wrap the IP lookup process in a try-catch statement to catch rate limit errors.

The output response object looks like this:

IPResponse{ip='8.8.8.8', hostname='dns.google', anycast=true, city='Mountain View', region='California', country='US', loc='37.4056,-122.0775', org='AS15169 Google LLC', postal='94043', timezone='America/Los_Angeles', asn=null, company=null, carrier=null, privacy=null, abuse=null, domains=null}

3. Extracting specific information from the IPResponse object

From the IPResponse object, we can extract specific information by calling the following methods:

IPResponse Methods Example Usage Example Output
getIp response.getIp() 8.8.8.8
getHostname response.getHostname() dns.google
getAnycast response.getAnycast() true
getCity response.getCity() Mountain View
getRegion response.getRegion() California
getCountryCode response.getCountryCode() US
getCountryName response.getCountryName() null
getLocation response.getLocation() 37.4056,-122.0775
getLatitude response.getLatitude() 37.4056
getLongitude response.getLongitude() -122.0775
getOrg response.getOrg() AS15169 Google LLC
getPostal response.getPostal() 94043
getTimezone response.getTimezone() America/Los_Angeles

If your IPinfo token tier has access to our paid tier, you can get additional information from the IPResponse instance. Such as:

IP to Privacy Detection

To get the anonymous IP-related information from the IPResponse object, use the getPrivacy

method. The getPrivacy method will return an output like the following:

Privacy{vpn=true, proxy=false, tor=false, relay=false, hosting=false, service=}

To get individual information from the Privacy object, call the following methods:

getPrivacy Methods Example Usage Example Output
getVpn response.getPrivacy().getVpn() false
getProxy response.getPrivacy().getProxy() false
getTor response.getPrivacy().getTor() false
getRelay response.getPrivacy().getRelay() true
getHosting response.getPrivacy().getHosting() true
getService response.getPrivacy().getService() Apple Private Relay

ASN data

The getAsn method of the IPResponse object will return the ASN information of the IP addresses. The getAsn method returns the following object:

ASN{asn='AS54113', name='Fastly, Inc.', domain='fastly.com', route='146.75.196.0/24', type='hosting'}

From the getAsn method, you can extract individual information with the following methods:

getAsn Methods Example Usage Example Output
getAsn response.getAsn().getAsn() AS54113
getName response.getAsn().getName() Fastly, Inc.
getDomain response.getAsn().getDomain() http://fastly.com/
getRoute response.getAsn().getRoute() 146.75.196.0/24
getType response.getAsn().getType() hosting

IP to Company Data

The getCompany returns the organization-related information of the IP address in the following way:

Company{name='FASTLY', domain='fastly.com', type='hosting'}

You can extract individual organization related information using the following methods:

getCompany Methods Example Usage Example Output
getName response.getCompany().getName() FASTLY
getDomain response.getCompany().getDomain() http://fastly.com/
getType response.getCompany().getType() hosting

IP to Mobile Carrier

If the IP you looked up is a mobile carrier IP, you can get carrier-related information as well with the getCarrier Method.

Carrier{name='SaudiNet', mcc='420', mnc='01'}
getCarrier Methods Example Usage Example Output
getName response.getCarrier().getName() SaudiNet
getMcc response.getCarrier().getMcc() 420
getMnc response.getCarrier().getMnc() 01

4. Exploring the other features of the IPinfo package

Aside from IP lookup, the IPinfo Java package comes with lots of useful features. Here are some of the highlights:

  • Lookup ASN information with the LookupASN function
  • Bulk or batch lookup IP addresses with the getBatchIps command
  • Bulk lookup ASN information with the getBatchAsns function
  • Map the geolocation of IP addresses from a list of IP addresses with getMap function. The function is powered by IPinfo's Map tool
  • By setting up country JSON files, get geolocation insights such as country name, currency, flag, EU country detection and more.

The package is also thread-safe and has support for data caching.

Going beyond Java, IPinfo has other official libraries for working with the API solution. Check out some of our other blogs:

Now, moving on to using the Java programming language to work without IPinfo’s IP data downloads.

Using our data downloads in the MMDB format

We are going to look into how to use IPinfo’s MMDB data downloads in the Java programming language. The MMDB file format is a binary file format that facilitates efficient and fast IP lookups. If you would like to know which file format fits your needs, check out our blog: https://ipinfo.io/blog/ipinfo-database-formats/

1. Installing the MMDB reader library

As the MMDB file format is a binary file, you need to use a third-party package MMDB Reader library for Java, first to work with it. Please install the MMDB reader library and not the API client library from MaxMind.

Installation via Maven

To install the library via Maven, add the following code to the Java project’s pom.xml file.

<dependency>
    <groupId>com.maxmind.db</groupId>
    <artifactId>maxmind-db</artifactId>
    <version>3.0.0</version>
</dependency>

Installation via Gradle

You can install the MMDB reader library via Gradle as well. Add the following code snippet to your build.gradle file:

repositories {
    mavenCentral()
}
dependencies {
    compile 'com.maxmind.db:maxmind-db:3.0.0'
}

You can use whatever installation method you like. But in this post, we will use Maven.

After you have added the code snippet to your pom.xml file, run:

mvn clean install

In some instances, this command is maven clean install.

2. Downloading the database

You can download the MMDB database in a number of different ways. You can use curl or you can download the database from your account dashboard.

Feel free to check our community post on downloading our IP database: https://community.ipinfo.io/t/downloading-the-ipinfo-database-data-downloads/1745

We are going to use the free IP to the ASN database for this article. I am using the curl tool to download the db and put it in the Java project’s static directory.

curl -L <https://ipinfo.io/data/free/asn.mmdb?token=><YOUR_TOKEN> -o asn.mmdb

3. Standard Code / Usage

Please note that IPinfo’s data downloads are flat, tabular and have an un-nested data structure. This means that you don’t have to do any kind of deep object indexing to get your data. IP metadata is available on the first and only layer of the data structure.

We will add boilerplate codes for all our data downloads format below. But for now, we will focus on the free IP to ASN database. The free IP to ASN database provides the following data from IP lookups:

  • ASN
  • Name
  • Domain

Using that information, we can create the [Lookup.java](<http://Lookup.java>) in the /src/main/java/com/mycompany/app directory:

package com.mycompany.app;

import com.maxmind.db.MaxMindDbConstructor;
import com.maxmind.db.MaxMindDbParameter;
import com.maxmind.db.Reader;

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

public class Lookup {
    public static void main(String[] args) throws IOException {
        File database = new File("static/asn.mmdb");
        try (Reader reader = new Reader(database)) {
            InetAddress address = InetAddress.getByName("8.8.8.8");

            // get() returns just the data for the associated record
            LookupResult result = reader.get(address, LookupResult.class);
            System.out.println(result.asn); // Output → AS15169
            System.out.println(result.name); // Output → Google LLC
            System.out.println(result.domain); // Output → google.com

        }
    }

    public static class LookupResult {
        private final String asn;
        private final String name;
        private final String domain;

        @MaxMindDbConstructor
        public LookupResult(
            @MaxMindDbParameter(name = "asn") String asn,
            @MaxMindDbParameter(name = "name") String name,
            @MaxMindDbParameter(name = "domain") String domain
        ){
            this.asn = asn;
            this.name = name;
            this.domain = domain;
        }
    }
}

Then you can run the following command to run the [Lookup.java](<http://Lookup.java>) file

mvn exec:java -q -Dexec.mainClass="com.mycompany.app.Lookup"

This will result in the following output:

AS15169
Google LLC
google.com

Please note that if you use an MMDB sample database or a database that does not include all the ranges, such as our IP to Privacy Detection database, you will receive a null response. You can learn about the caveat of using a sample MMDB database from this article.

4. Code / Usage with Boolean data

Our IP to Privacy database provides data in a Boolean format for flagging the type of anonymous IP addresses. For example: If we flagged an IP to be a VPN we will return true or else we will return an empty string, "".

We can account for that by using the following code:

package com.mycompany.app;

import com.maxmind.db.MaxMindDbConstructor;
import com.maxmind.db.MaxMindDbParameter;
import com.maxmind.db.Reader;

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

public class Lookup {
    public static void main(String[] args) throws IOException {
        File database = new File("static/standard_privacy.mmdb");
        try (Reader reader = new Reader(database)) {
            InetAddress address = InetAddress.getByName("94.102.51.15");

            // get() returns just the data for the associated record
            LookupResult result = reader.get(address, LookupResult.class);
            // I am using string formatting, which is not necessary here
            System.out.println(String.format("VPN: %s", result.vpn));
            System.out.println(String.format("Proxy: %s", result.proxy));
            System.out.println(String.format("TOR: %s", result.tor));
            System.out.println(String.format("Relay: %s", result.relay));
            System.out.println(String.format("Hosting: %s", result.hosting));
            System.out.println(String.format("Service: %s", result.service));
        }
    }

    public static class LookupResult {
        private final boolean vpn;
        private final boolean proxy;
        private final boolean tor;
        private final boolean relay;
        private final boolean hosting;
        private final String service;

        @MaxMindDbConstructor
        public LookupResult(
            @MaxMindDbParameter(name = "vpn") String vpn,
            @MaxMindDbParameter(name = "proxy") String proxy,
            @MaxMindDbParameter(name = "tor") String tor,
            @MaxMindDbParameter(name = "relay") String relay,
            @MaxMindDbParameter(name = "hosting") String hosting,
            @MaxMindDbParameter(name = "service") String service

        ){
            this.vpn = vpn.equals("true");
            this.proxy = proxy.equals("true");
            this.tor = tor.equals("true");
            this.relay = relay.equals("true");
            this.hosting = hosting.equals("true");
            this.service = service;
        }
    }
}

This will result in the following output:

VPN: true
Proxy: false
TOR: true
Relay: false
Hosting: true
Service: FreeVPN

Incorporating IPinfo's robust data into your Java projects not only enriches your applications with precise geolocation data but also fortifies your cybersecurity measures. Seamlessly retrieving IP insights from the API and data downloads, empowers you to make informed decisions, from optimizing user experiences to reinforcing access controls. Uf

Join IPinfo's community, where you can freely ask questions, share insights, and continue harnessing the potential of IP intelligence. Check our paid plans to get access to more data types (from Privacy to Detection to Hosted Domains) as well as higher request amounts.

About the author

IPinfo Team

IPinfo Team

Internet Data Expert