Last updated
February 27, 2024

Mastering Geolocation in Java: A Comprehensive Guide

Kadar Ali

Table of Contents:

Get your free
IP Geolocation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Key Takeaways

  • Understanding Geolocation: Learn how geolocation works using GPS, cell towers, and ISPs to pinpoint locations for various applications.
  • Java and Geolocation: Discover the package's role in developing networking applications and handling IP addresses for geolocation.
  • Server vs. Client IP Detection: Insights into locating a user's IP address on both the server and client sides, highlighting methods and challenges.
  • MaxMind and Abstract API Usage: A guide on implementing MaxMind services and the Abstract API for accurate geolocation and user tracking in Java.
  • Securing API Keys: Best practices for securing your geolocation service API keys within Java applications.
  • Practical Application: Step-by-step instructions on integrating geolocation services into Java applications, including code snippets and configuration tips.

What is Geolocation?

Geolocation involves pinpointing a person or device through methods such as GPS, cell phone towers, and internet service providers. This technique is vital for various services and serves numerous purposes.

What are the use cases for Geolocation?

  • Compliance: Allow service access only in authorized locations. Follow regulations, sanctions, and location-specific restrictions.
  • Fraud Prevention: Detect and prevent fraudulent activities by tracking user locations.
  • Content Strategy: Provide tailored content according to user locations. Limit access to content restricted in specific areas.

This article offers an overview of IP-based geo-location and presents Java-based solutions.

What is the package?

The package in JDK provides a rich collection of classes and interfaces essential for developing networking applications. When representing an IP address, developers can choose between the base class, InetAddress, or its extensions - Inet4Address and Inet6Address.

InetAddress ipAddress = InetAddress.getByName(“”);
InetAddress ipAddress = InetAddress.getByName(“”);

An InetAddress can be generated by inputting either an IP address or a hostname. It leverages the system's DNS to resolve the IP address.

Let’s send your first free
IP Geolocation
See why the best developers build on Abstract
Get your free api

How to determine a user's IP address

The user's IP address can be located either on the client side or server side, each with its own set of advantages and disadvantages.

How to locate a user's IP address on the server side

There are various methods available on the server side to retrieve the user's IP address. One common approach is utilizing the getRemoteAddr method within the HttpServletRequest object.

String ipAddress = httpServletRequest.getRemoteAddr();

This could lead to inaccurate outcomes depending on various scenarios, such as when the user faces a corporate proxy or when the request is directed through an API gateway, load balancer, or forward proxy. It is important to account for specific HTTP Headers to precisely determine the client’s IP address.

  • X-Forwarded-For
  • Proxy-Client-IP
  • WL-Proxy-Client-IP

How can you locate a user's IP address from the client side?

Locating the client's IP address on the server side can be quite complex. This is due to the request not directly reaching the server but traversing different hops depending on the circumstances.

curl ''

Use the ipify API in a browser to get the user's IP address on the client side. You can send it in the request body or as a custom HTTP header to the server. This is one of the easiest ways to get the client's IP address accurately.

Guide on finding user location with IP address using MaxMind services.

We can determine a user's geographic location by utilizing MaxMind services. These services offer fast response times and reliable web access to pinpoint a user's location based on their IP address. Additionally, MaxMind provides a Java API along with a complimentary database.

How to use MaxMind’s web services

To utilize the API endpoints, we must register our client application and obtain the API credentials from MaxMind. MaxMind offers API endpoints for both interactive and batch operations.







How to use MaxMind’s Java API and Database

Maven Dependency

We recommend installing this package with Maven. To do this, add the dependency to your pom.xml:



Add the following to your build.gradle file:

repositories {
dependencies {
compile 'com.maxmind.geoip2:geoip2:4.2.0'

// A File object pointing to your GeoIP2 or GeoLite2 database
File database = new File("/path/to/GeoIP2-City.mmdb");
// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("");
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response =;
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'US'
System.out.println(country.getName()); // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'
City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'
Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'
Location location = response.getLocation();
System.out.println(location.getLatitude()); // 44.9733
System.out.println(location.getLongitude()); // -93.2323

MaxMind offers both free and paid options, tailored to your needs in terms of accuracy, usage, and request volume.

The best alternative: How to get a user's IP address using Abstract's IP Geolocation API

Abstract's IP Geolocation API offers a simple yet remarkable way to retrieve geographical information about a user based on their IP address.




Sample response

"ip_address": "",
"city": "San Jose",
"city_geoname_id": 5392171,
"region": "California",
"region_iso_code": "CA",
"region_geoname_id": 5332921,
"postal_code": "95141",
"country": "United States",
"country_code": "US",
"country_geoname_id": 6252001,
"country_is_eu": false,
"continent": "North America",
"continent_code": "NA",
"continent_geoname_id": 6255149,
"longitude": -121.7714,
"latitude": 37.1835,
"is_vpn": false
"name": "America/Los_Angeles",
"abbreviation": "PDT",
"gmt_offset": -7,
"current_time": "06:37:41",
"is_dst": true
"emoji": "??",
"unicode": "U+1F1FA U+1F1F8",
"png": "",
"svg": ""
"currency_name": "USD",
"currency_code": "USD"
"autonomous_system_number": 20057,
"autonomous_system_organization": "ATT-MOBILITY-LLC-AS20057",
"connection_type": "Cellular",
"isp_name": "AT&T Mobility LLC",
"organization_name": "Service Provider Corporation"

Abstract's IP Geolocation API offers extensive user information on geolocation, supplying valuable details for various use cases and purposes.

Sample Spring Project

In this example Spring Boot project, we will utilize Abstract's IP Gelocation API to fetch a user's location details based on their IP address.

We will utilize a Rest Controller to expose a rest endpoint for retrieving geo-location data based on the user’s IP address. This controller interfaces with an adapter service class.

package com.example.abstractapiexample;

import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class GeoLocationController {
private final GeoLocationService geoLocationService;
public ResponseEntity getLocation(HttpServletRequest request) {
return ResponseEntity.ok()

Then, we will use a Service/Adapter class to call the REST API through RestTemplate. This is done by providing our consumer API key along with the user's IP address.

package com.example.abstractapiexample;

import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

public class GeoLocationService {
private final RestTemplate restTemplate;
public GeoLocation getGeoLocation(String remoteAddr) {
ResponseEntity responseEntity = restTemplate.getForEntity("" + remoteAddr, GeoLocation.class);
return responseEntity.getBody();

Now let's create a DTO object named GeoLocation to translate the JSON response from the API into a Java object.

package com.example.abstractapiexample;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

public class GeoLocation {
private String ipAddress;
private String city;
private String region;
private String country;
private String postalCode;
private String continent;
private String countryCode;
private String regionIsoCode;
private String continentCode;
private int cityGeoNameId;
private int regionGeoNameId;
private int countryGeoNameId;
private int continentGeoNameId;
private boolean countryIsEU;
private double longitude;
private double latitude;
private TimeZone timezone;
private Flag flag;
private Currency currency;
private Connection connection;

class TimeZone {
private String name;
private String abbreviation;
private int gmtOffset;
private String currentTime;
private boolean isDst;

class Flag {
private String emoji;
private String unicode;
private String png;
private String svg;

class Currency {
private String currencyName;
private String currencyCode;

class Connection {
private String autonomousSystemNumber;
private String autonomousSystemOrganization;
private String connectionType;
private String ispName;
private String organizationName;


curl http://localhost:8080/geo-location

Sample Response

"city": "Strasbourg",
"region": "Grand Est",
"country": "France",
"continent": "Europe",
"longitude": 7.7418,
"latitude": 48.5855,
"timezone": {
"name": "Europe/Paris",
"abbreviation": "CET",
"gmt_offset": 1,
"current_time": "05:43:10",
"is_dst": false
"flag": {
"emoji": "🇫🇷",
"unicode": "U+1F1EB U+1F1F7",
"png": "",
"svg": ""
"currency": {
"currency_name": "Euros",
"currency_code": "EUR"
"connection": {
"autonomous_system_number": "29066",
"autonomous_system_organization": " Internetdienste GmbH",
"connection_type": "Corporate",
"isp_name": "Host Europe GmbH",
"organization_name": "HEG Mass"
"ip_address": "",
"postal_code": "60313",
"country_code": "FR",
"region_iso_code": "GES",
"continent_code": "EU",
"city_geoname_id": 2973783,
"region_geoname_id": 11071622,
"country_geoname_id": 3017382,
"continent_geoname_id": 6255148,
"country_is_eu": true

The Abstract IP Geolocation API offers valuable insights when given a user's IP address, including:

  • Geo-location details such as city, state, country, and zip code.
  • Timezone specifics like timezone name and GMT offset.
  • Security indicators to detect VPN usage.
  • Currency data including currency code.
  • Flag details with CDN-hosted flag images.
  • Connection insights covering the user's service provider and connection type.

Sign up and try the API for free!


How can I handle IPv6 addresses in Java for geolocation purposes?

Java's InetAddress class, which is part of the package, supports both IPv4 and IPv6 addresses. When dealing with geolocation, ensure your application can parse and handle IPv6 addresses, as they are becoming increasingly common. Use the Inet6Address class for IPv6-specific operations. Additionally, when using external geolocation services, verify their support for IPv6 addresses to ensure accurate location data.

What are the best practices for securing API keys used in geolocation services in a Java application?

Secure your API keys by storing them outside of your source code, such as in environment variables or secure configuration files. Use access control mechanisms to limit who can view or access these keys. Additionally, if your geolocation service provider supports it, restrict the API key usage to specific IP addresses or domains that match your application's deployment environment. Always use HTTPS to encrypt requests to geolocation services to prevent API key exposure.

How can I improve the accuracy of geolocation results in my Java application?

To improve geolocation accuracy, consider using a combination of IP-based geolocation and other location-determining methods such as GPS (for mobile devices) or HTML5 Geolocation API (for web applications). Additionally, using a high-quality, up-to-date geolocation database or service can significantly enhance accuracy. For critical applications, consider implementing a fallback mechanism, such as prompting the user to confirm or correct their detected location.

Can Java applications perform reverse geocoding with IP addresses, and how?

Yes, Java applications can perform reverse geocoding by using a geolocation service that converts IP addresses into human-readable location information, such as city, region, and country names. This process typically involves sending a request to a geolocation API, passing the IP address as a parameter, and receiving location information in response. Implement this by integrating a geolocation API client in your Java application, using libraries like geoip2 for MaxMind or similar services.

How do I handle location-based content restrictions in Java web applications?

Implement location-based content restrictions by first determining the user's geolocation using their IP address. Once the location is identified, compare it to a list of regions where the content is restricted. If the user's location matches any restricted regions, you can programmatically redirect them to an alternative page or display a message indicating that the content is not available in their region. This can be achieved through server-side Java code, using frameworks like Spring MVC or servlets for web application development.

What is the role of the package in enabling real-time geolocation tracking in Java applications?

The package provides the foundational classes for networking in Java, including classes for working with IP addresses and making network requests. For real-time geolocation tracking, this package enables Java applications to communicate with external geolocation APIs, retrieve IP addresses, and handle network communications. By using classes such as InetAddress for IP address manipulation and URL or HttpURLConnection for API requests, developers can integrate real-time geolocation tracking into their Java applications.

Kadar Ali
Get your free
IP Geolocation
key now
This is some text inside of a div block.
get started for free

Related Articles

Get your free
key now
IP Geolocation
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required