Backend Development 12 min read

Retrieving Client IP and Using ip2region for IP Geolocation in Java

This article explains how to obtain a client's IP address from HttpServletRequest in Java, convert it to geographic location using the ip2region library, and demonstrates various query methods, caching strategies, and Maven integration for efficient backend IP geolocation.

Top Architect
Top Architect
Top Architect
Retrieving Client IP and Using ip2region for IP Geolocation in Java

In modern web platforms many services display the user's IP location, so backend developers often need to retrieve the client IP address and map it to a geographic region. The article first shows how to extract the IP from HttpServletRequest by checking common headers and handling local addresses.

A reusable utility class NetworkUtil is provided, which includes methods getIpAddress(HttpServletRequest request) to obtain the real IP and getMacAddress() to fetch the MAC address. The implementation iterates through headers such as x-forwarded-for , Proxy-Client-IP , and falls back to request.getRemoteAddr() , with special handling for localhost.

For IP‑to‑region mapping the open‑source project ip2region (v2.0) is introduced. It offers an offline binary .xdb database with 99.9% accuracy, supports multiple languages, and provides three cache policies: file‑only, vector‑index cache, and full‑memory cache. The data format is country|region|province|city|ISP , and the library can query in microseconds.

Integration steps are shown: Add the Maven dependency org.lionsoul:ip2region:2.6.4 . Use the Searcher class to create a searcher instance (file, vector index, or memory cache) and call search(ip) to obtain the region string. Example code demonstrates creating a searcher, measuring query latency, and handling concurrency (each thread needs its own Searcher instance).

Additional examples cover loading the entire .xdb into memory, caching the vector index, and running a benchmark with the bench command to evaluate performance. The article also includes screenshots of IDE testing and notes on handling large query volumes.

Overall, the guide provides a complete backend solution for extracting client IPs, mapping them to locations with high performance, and configuring ip2region in Java projects.

backendJavaHttpServletRequestIP Geolocationip2region
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.