java gets the city based on IP GeoLite2-City.mmdb

This article can solve the problem of not being able to obtain the IP location. It provides a variety of methods for reference only:

1. Selection

1.1 Implementation method

Java can implement IP address resolution and province and city information query, but it requires the help of some external data sources or databases to achieve this. Commonly used methods include the following:

1.1.1 Local file analysis

You can obtain the province, city, and other information corresponding to the IP address by downloading the latest IP address segment data file and then parsing the file in the program. However, this method requires manual maintenance of IP library files, and the update and query speed may be slow, making it unsuitable for high-concurrency or large-scale application scenarios.

1.1.2 Database query

The IP address segment data can be stored in the database, and then the corresponding province, city, and other information can be queried based on the IP address requested by the user. Commonly used databases include MySQL, Oracle, SQL Server, etc. This method can improve query efficiency and accuracy, and support more flexible query methods, but it requires consideration of database design and optimization issues.

1.1.3 Third-party API proxy

Use a third-party IP query API proxy to implement pure Java IP address resolution and province and city information query. For example, by calling third-party services such as Baidu Map API and Amap API to obtain the location information corresponding to the IP address. This method can avoid the trouble of building an IP database by yourself, and can also ensure the accuracy and real-timeness of query results, but issues such as API usage frequency and cost need to be considered.

1.2 Common IP location library

1.2.1 Ip2region Ip2region

Quickly implement IP address resolution – Nuggets

Ip2region: Ip2region is a Java-based IP address location library that provides fast and accurate IP query services. It divides global IP addresses into multi-level regions, and can obtain corresponding provincial and municipal information, operators and other detailed information based on IP addresses.

Reference: Connection

1.2.2 GeoLite2

GeoLite2: A free IP address library developed and maintained by MaxMind, providing high-precision IP address positioning services. You can query the location information corresponding to the IP address by downloading the database file or using the API.

MaxMind GeoIP2 Java API

GeoLite2 Java obtains city, latitude and longitude based on IP | Yan Zhao Blog

java gets the city based on ip_mob64ca12d4a164’s technology blog_51CTO blog

1.2.3 IP2Location

IP2Location: A commercial IP address library that provides global IP address location services and supports IPv4/IPv6 address resolution. Available via subscription service or by purchasing database files.

1.2.4 ipapi

ipapi: A cloud IP address query API that provides efficient and accurate IP address location services. Supports return data in JSON/XML format, and can choose different packages and service plans according to user needs.

1.2.5 QQWry

QQWry: One of the most widely used IP address libraries in China, it provides mapping of IP addresses to provinces, cities, counties, operators and other information. IP address location can be achieved by downloading the latest version of the dat file or using the API.

1.2.6 Others

There are many other positioning libraries in China, such as Taobao, Sina, Sohu and other IP libraries. Friends who are interested can learn about it themselves.

1.3 Selection

1.3.1 Based on the following considerations, I finally chose GeoLite2

GeoLite2-City.mmdb download link 1

GeoLite2-City.mmdb download link 2

GeoLite2-City.mmdb download link 3

import javax.servlet.http.HttpServletRequest;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
/**
 * @description:
 * @author:LAN
 */
public class Ttest {

    public String getUserIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    public CityResponse getInfo(String ip) throws IOException, GeoIp2Exception {
        File database = new File("C:\Users\\lenovo\Desktop\test\\GeoLite2-City.mmdb"); // GeoLite2 database file path
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        InetAddress ipAddress = InetAddress.getByName(ip);
        CityResponse response = reader.city(ipAddress);
        return response;
    }

    public String getCityInfo(String ipAddress) {
        CityResponse cityResponse;
        try {
            cityResponse = getInfo(ipAddress);
            String cityName = cityResponse.getCity().getName(); // 'English city'
            String countryName = cityResponse.getCountry().getName(); // 'English country'
            String countryNameZ = cityResponse.getCountry().getNames().get("zh-CN"); // 'Country'
            String subdivisionNameZ = cityResponse.getLeastSpecificSubdivision().getNames().get("zh-CN"); // 'Province'
            String cityNameZ = cityResponse.getCity().getNames().get("zh-CN"); // 'city'
            System.out.println("Country: " + countryNameZ + ", Your current province: " + subdivisionNameZ + ", Your current city: " + cityNameZ);
            return "Your current city: " + cityName + ", country: " + countryName;
        } catch (IOException | GeoIp2Exception e) {
            return "Failed to obtain city information:" + e.getMessage();
        }
    }

    public String getCityInfo(HttpServletRequest request) {
        String ipAddress = getUserIpAddress(request);
        CityResponse cityResponse;
        String cityName =null;
        String countryName =null;
        try {
            cityResponse = getInfo(ipAddress);
            cityResponse.getCity().getName();
             cityResponse.getCountry().getName();
        } catch (IOException e) {
            return "Failed to obtain city information:" + e.getMessage();
        } catch (GeoIp2Exception e) {
            e.printStackTrace();
        }
        return "Your current city: " + cityName + ", country: " + countryName;
    }


    public static void main(String[] args) {
        Ttest t=new Ttest();
        System.out.println(t.getCityInfo("111.18.134.223"));
    }
1.3 .1 Extraction via network connection ipshudi
import cn.hutool.http.HttpRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author:LAN
 */
public class tttttest {

    public static void main(String[] args) {
        String html = HttpRequest.get("https://www.ipshudi.com/111.18.134.223.htm").execute().body();
        String pattern= "<a.*? rel="nofollow" target="_blank">(.*?)</a>";
        Pattern regex = Pattern.compile(pattern);
        Matcher matcher = regex.matcher(html);
        while (matcher.find()) {
            System.out.println("matcher.group(0) " + matcher.group(0));//Get group 0 - the entire match
            System.out.println("matcher.group(1) " + matcher.group(1));//Get the first group to match the corresponding median value in the first bracket
        }
        System.out.println("*****");
    }
}

https://qifu-api.baidubce.com/ip/geo/v1/district?ip=#{ip} &type=0

https://ip.cn/api/index?ip=#{IP} &type=0

http://whois.pconline.com.cn/?ip=#{IP}

https://www.ipshudi.com/#{IP}.htm

Obtain the geographical location through IP, obtain the location through mobile phone number_Get the city based on IP – CSDN Blog