Guides
Last Updated Feb 27, 2024

Mastering Geolocation in Java: A Comprehensive Guide

Kadar Ali

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
IP Geolocation API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
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 java.net 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 java.net package?

The java.net 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(“1.2.3.4”);
InetAddress ipAddress = InetAddress.getByName(“www.google.com”);

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
API
IP Geolocation API
call
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
  • HTTP_X_FORWARDED_FOR
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED
  • HTTP_VIA
  • REMOTE_ADDR

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 'https://api.ipify.org?format=json'

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.

URL https://geoip.maxmind.com/geoip/v2.1/city/{ip_address}

Example


curl https://geoip.maxmind.com/geoip/v2.1/city/85.25.43.84

URL https://geoip.maxmind.com/geoip/v2.1/country/{ip_address}

Example


curl https://geoip.maxmind.com/geoip/v2.1/country/85.25.43.84

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:


   <dependency>
        <groupId>com.maxmind.geoip2</groupId>
        <artifactId>geoip2</artifactId>
        <version>4.2.0</version>
    </dependency>

Gradle

Add the following to your build.gradle file:


repositories {
    mavenCentral()
}
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("128.101.101.101");
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
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.

URL https://ipgeolocation.abstractapi.com/v1/api_key=YOUR_UNIQUE_API_KEY&ip_address=IP_ADDRESS

Example


curl https://ipgeolocation.abstractapi.com/v1/api_key=YOUR_UNIQUE_API_KEY&ip_address=166.171.248.255

Sample response


{
"ip_address": "166.171.248.255",
"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,
"security": 
{
"is_vpn": false
},
"timezone": 
{
"name": "America/Los_Angeles",
"abbreviation": "PDT",
"gmt_offset": -7,
"current_time": "06:37:41",
"is_dst": true
},
"flag": 
{
"emoji": "??",
"unicode": "U+1F1FA U+1F1F8",
"png": "https://static.abstractapi.com/country-flags/US_flag.png",
"svg": "https://static.abstractapi.com/country-flags/US_flag.svg"
},
"currency": 
{
"currency_name": "USD",
"currency_code": "USD"
},
"connection": 
{
"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.

GeoLocationController.java

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;

@AllArgsConstructor
@RestController
public class GeoLocationController {
   private final GeoLocationService geoLocationService;
   @GetMapping("/geo-location")
   public ResponseEntity<GeoLocation> getLocation(HttpServletRequest request) {
       return ResponseEntity.ok()
            .body(geoLocationService.getGeoLocation(request.getRemoteAddr()));
   }
}

GeoLocationService.java

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;

@AllArgsConstructor
@Service
public class GeoLocationService {
   private final RestTemplate restTemplate;
   public GeoLocation getGeoLocation(String remoteAddr) {
       ResponseEntity<GeoLocation> responseEntity = restTemplate.getForEntity("https://ipgeolocation.abstractapi.com/v1/?api_key=<apikey>&ip_address=" + remoteAddr, GeoLocation.class);
       return responseEntity.getBody();
   }
}

GeoLocation.java

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;

@Data
public class GeoLocation {
   @JsonProperty("ip_address")
   private String ipAddress;
   private String city;
   private String region;
   private String country;
   @JsonProperty("postal_code")
   private String postalCode;
   private String continent;
   @JsonProperty("country_code")
   private String countryCode;
   @JsonProperty("region_iso_code")
   private String regionIsoCode;
   @JsonProperty("continent_code")
   private String continentCode;
   @JsonProperty("city_geoname_id")
   private int cityGeoNameId;
   @JsonProperty("region_geoname_id")
   private int regionGeoNameId;
   @JsonProperty("country_geoname_id")
   private int countryGeoNameId;
   @JsonProperty("continent_geoname_id")
   private int continentGeoNameId;
   @JsonProperty("country_is_eu")
   private boolean countryIsEU;
   private double longitude;
   private double latitude;
   private TimeZone timezone;
   private Flag flag;
   private Currency currency;
   private Connection connection;
}

@Data
class TimeZone {
   private String name;
   private String abbreviation;
   @JsonProperty("gmt_offset")
   private int gmtOffset;
   @JsonProperty("current_time")
   private String currentTime;
   @JsonProperty("is_dst")
   private boolean isDst;
}

@Data
class Flag {
   private String emoji;
   private String unicode;
   private String png;
   private String svg;
}

@Data
class Currency {
   @JsonProperty("currency_name")
   private String currencyName;
   @JsonProperty("currency_code")
   private String currencyCode;
}

@Data
class Connection {
   @JsonProperty("autonomous_system_number")
   private String autonomousSystemNumber;
   @JsonProperty("autonomous_system_organization")
   private String autonomousSystemOrganization;
   @JsonProperty("connection_type")
   private String connectionType;
   @JsonProperty("isp_name")
   private String ispName;
   @JsonProperty("organization_name")
   private String organizationName;
}

Testing


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": "https://static.abstractapi.com/country-flags/FR_flag.png",
    "svg": "https://static.abstractapi.com/country-flags/FR_flag.svg"
  },
  "currency": {
    "currency_name": "Euros",
    "currency_code": "EUR"
  },
  "connection": {
    "autonomous_system_number": "29066",
    "autonomous_system_organization": "velia.net Internetdienste GmbH",
    "connection_type": "Corporate",
    "isp_name": "Host Europe GmbH",
    "organization_name": "HEG Mass"
  },
  "ip_address": "85.25.43.84",
  "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!

FAQs

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

Java's InetAddress class, which is part of the java.net 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 java.net package in enabling real-time geolocation tracking in Java applications?

The java.net 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.

4.9/5 stars (10 votes)

Kadar Ali
Kadar Ali is a seasoned Senior Java / Microservices Developer based in Texas, boasting over 15 years of experience in the tech industry. Specializing in Java, Java EE, Spring Framework/Boot, and microservices, Kadar has a proven track record in designing and maintaining robust enterprise applications. He is well-versed in Domain Driven Design, Clean/Hexagonal Architecture, and possesses certifications in Java and AWS. Kadar excels in leveraging cloud technologies across AWS and Azure, implementing gof design patterns, and building applications with event-driven architectures using Kafka, ActiveMQ, and RabbitMQ. His expertise extends to deploying microservices on cloud platforms like EKS and AKS, making him a valuable asset in any development project.
Get your free
IP Geolocation API
API
key now
Ready to elevate your geolocation capabilities? Start experimenting with the Abstract API today and unlock precise, real-time location data for your Java applications!
get started for free

Related Articles

Get your free
API
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