使用免费IP数据库离线查询IP归属地

发布于:2025-03-10 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、准备工作

1.下载免费IP数据库
  • 首先,访问 MaxMind官网(https://www.maxmind.com/en/home
  • 如果你还没有MaxMind账号,可以通过此链接地址(https://www.maxmind.com/en/geolite2/signup)进行账号注册,注册号,您将收到一封重置密码的邮件,完成密码重置后,即可登录。
  • 登录后,通过此链接(https://www.maxmind.com/en/accounts/*******/geoip/downloads )进入数据库下载界面,注意:链接中的*******因账号而异可通过下方页面处获得

2.获取数据库文件
  • 在下载界面,可以找到GeoLite2 City或GeoLite2 Country数据库文件。根据您的需求下载相应的数据库文件。

二、编码工作

1.Maven引入jar包
  • 在Maven项目中,打开pom.xml文件,并添加geoip2与db依赖。以下是一个示例配置(版本号可根据开发环境进行调整,以下示例基于JDK 1.8)

        <dependency>
            <groupId>com.maxmind.geoip2</groupId>
            <artifactId>geoip2</artifactId>
            <version>2.17.0</version><!-- 请根据实际需要调整版本号 -->
        </dependency>
        <dependency>
            <groupId>com.maxmind.db</groupId>
            <artifactId>maxmind-db</artifactId>
            <version>2.1.0</version><!-- 请根据实际需要调整版本号 -->
        </dependency>

2.代码实现
package cn.demo.utils;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.Country;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.*;

public class GeoLiteUtil {
    // 替换为您实际下载的数据库文件路径
    private static final String DB_COUNTRY_PATH = "path/to/GeoLite2-Country.mmdb";
    private static final String DB_CITY_PATH = "path/to/GeoLite2-City.mmdb";

    public static void main(String[] args) {
        // 替换为需要查询的实际IP地址
        System.out.println(getIPPlace("8.8.8.8"));
    }

    public static String getIPPlace(String ip) {
        DatabaseReader reader = null;
        DatabaseReader readerCity = null;
        try {
            File database = new File(DATABASE_COUNTRY_PATH);
            reader = new DatabaseReader.Builder(database).build();
            readerCity = new DatabaseReader.Builder(new File(DATABASE_CITY_PATH)).build();
            InetAddress ipAddress = InetAddress.getByName(ip);
            // 查询国家
            CountryResponse response = reader.country(ipAddress);
            Country country = response.getCountry();
            String countryName = country.getName();
            // 查询城市
            CityResponse cityResponse = readerCity.city(ipAddress);
            String cityName = cityResponse.getCity().getName();
            return countryName + " " + cityName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (readerCity != null) {
                try {
                    readerCity.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}