Backend Development 11 min read

How to Retrieve IP Geolocation in Java Using ip2region

This tutorial explains how to obtain a user's IP address from an HttpServletRequest, interpret the IP using the ip2region offline database, and display the corresponding province or country in a Java backend application, including code examples and Maven integration.

IT Services Circle
IT Services Circle
IT Services Circle
How to Retrieve IP Geolocation in Java Using ip2region

The article explains how to display IP location information in a web application and retrieve the client’s IP address in Java for further geolocation.

It first describes the new IP‑location feature in the Mogu platform, which shows the IP region in posts, comments, and group chats, and then outlines the steps needed to obtain the IP address from an incoming request.

Step 1: Get the client IP address – The IP is extracted from several HTTP headers (X‑Forwarded‑For, Proxy‑Client‑IP, WL‑Proxy‑Client‑IP) and, if none are present, from the remote address of the request. The following utility method demonstrates this logic:

public class IpUtil {
    public static String getIpAddr(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ipAddress = headers.getFirst("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddress().getAddress().getHostAddress();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("Error getting local IP", e);
                }
            }
        }
        if (ipAddress != null && ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.split(",")[0];
        }
        return ipAddress;
    }
}

Step 2: Header meanings – X‑Forwarded‑For records the original client IP across multiple proxies, X‑Real‑IP usually contains the real client IP, Proxy‑Client‑IP is added by Apache HTTP when acting as a proxy, and WL‑Proxy‑Client-IP is added by WebLogic.

Step 3: From online APIs to offline database – The article notes that the previously used Taobao IP service often suffered from downtime and strict QPS limits, prompting a switch to the ip2region offline library, which offers 99.9% accuracy and sub‑millisecond query times.

Step 4: Add ip2region to the project – Include the Maven dependency:

<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>1.7.2</version>
</dependency>

Then create a utility class that loads ip2region.db from the resources folder and performs lookups using one of three algorithms (memory, binary, B‑tree). Example snippet:

static {
    dbPath = createFtlFileByFtlArray() + "ip2region.db";
    try {
        config = new DbConfig();
        searcher = new DbSearcher(config, dbPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String getCityInfo(String ip) {
    if (StringUtils.isEmpty(dbPath)) {
        log.error("Invalid ip2region.db file");
        return null;
    }
    int algorithm = DbSearcher.BTREE_ALGORITHM; // or BINARY_ALGORITHM / MEMORY_ALGORITHM
    try {
        Method method = searcher.getClass().getMethod(
            algorithm == DbSearcher.BTREE_ALGORITHM ? "btreeSearch" :
            algorithm == DbSearcher.BINARY_ALGORITHM ? "binarySearch" : "memorySearch",
            String.class);
        DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
        String region = dataBlock.getRegion();
        return region.replace("|0", "").replace("0|", "");
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

To present a user‑friendly location, wrap the result in getIpPossession , which returns the province for Chinese IPs or the country for foreign IPs.

public static String getIpPossession(String ip) {
    String cityInfo = getCityInfo(ip);
    if (!StringUtils.isEmpty(cityInfo)) {
        cityInfo = cityInfo.replace("|", " ");
        String[] parts = cityInfo.split(" ");
        if ("中国".equals(parts[0]) && parts.length > 1) {
            return parts[1]; // province
        }
        return parts[0]; // country
    }
    return "未知";
}

Running the main method demonstrates successful resolution of both domestic and overseas IP addresses, and the article concludes with a link to the ip2region GitHub repository for further exploration.

GitHub repository: https://github.com/lionsoul2014/ip2region

backendjavamavennetworkingIP Geolocationip2region
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

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.