Java通过GeoLite2-City.mmdb 进行IP信息查询地理定位和经纬度筛选。

引入依赖

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

下载数据文件:https://download.lin2ur.cn/GeoLite2/
在这里插入图片描述

package com.cqcloud.platform.utils;

import java.io.File;
import java.net.InetAddress;
import com.maxmind.geoip2.DatabaseReader
import cn.hutool.core.lang.Console;
import lombok.experimental.UtilityClass;

/**
 * @author weimeilayer@gmail.com ✨
 * @date 💓💕2024年7月4日 🐬🐇 💓💕
 */
@UtilityClass
public class GeoLite2Utils {
    /**
     *
     * @description: 获得国家
     * @param reader GeoLite2 数据库
     * @param ip ip地址
     * @return
     * @throws Exception
     */
    public static String getCountry(DatabaseReader reader, String ip) throws Exception {
        return reader.city(InetAddress.getByName(ip)).getCountry().getNames().get("zh-CN");
    }
 
    /**
     *
     * @description: 获得省份
     * @param reader GeoLite2 数据库
     * @param ip ip地址
     * @return
     * @throws Exception
     */
    public static String getProvince(DatabaseReader reader, String ip) throws Exception {
        return reader.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN");
    }
 
    /**
     *
     * @description: 获得城市
     * @param reader GeoLite2 数据库
     * @param ip ip地址
     * @return
     * @throws Exception
     */
    public static String getCity(DatabaseReader reader, String ip) throws Exception {
        return reader.city(InetAddress.getByName(ip)).getCity().getNames().get("zh-CN");
    }
 
    /**
     *
     * @description: 获得经度
     * @param reader GeoLite2 数据库
     * @param ip ip地址
     * @return
     * @throws Exception
     */
    public static Double getLongitude(DatabaseReader reader, String ip) throws Exception {
        return reader.city(InetAddress.getByName(ip)).getLocation().getLongitude();
    }
 
    /**
     *
     * @description: 获得纬度
     * @param reader GeoLite2 数据库
     * @param ip ip地址
     * @return
     * @throws Exception
     */
    public static Double getLatitude(DatabaseReader reader, String ip) throws Exception {
        return reader.city(InetAddress.getByName(ip)).getLocation().getLatitude();
    }
 
    public static void main(String[] args) throws Exception {
    	long startTime = System.currentTimeMillis();
    	Console.log("--------------------------开始时间{}", startTime);
        // 创建 GeoLite2 数据库
        //Windows环境切换到自己的文件存放路径即可
        File file = new File("D:\\GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(file).build();
        // 访问IP
        String ip = "218.70.71.0";
        String siteAddress = "国家:"+GeoLite2Utils.getCountry(reader, ip) + "\n省份:" + GeoLite2Utils.getProvince(reader, ip) + "\n城市:" + GeoLite2Utils.getCity(reader, ip)+ "\n经度:" + GeoLite2Utils.getLongitude(reader, ip)+ "\n纬度:" + GeoLite2Utils.getLatitude(reader, ip);
        Console.log(siteAddress);
        long endTime = System.currentTimeMillis();
        Console.log("--------------------------结束时间 {} 耗时 {} 毫秒", endTime, endTime - startTime);
    }
}

运行结果

--------------------------开始时间1720080983354
国家:中国
省份:重庆
城市:重庆市
经度:106.5577
纬度:29.5689
--------------------------结束时间 1720080983436 耗时 82

然后作为判断的 创建 GeoIPChecker

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Location;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Objects;
import cn.hutool.core.lang.Console;
/**
 * @author weimeilayer@gmail.com ✨
 * @date 💓💕2024年7月4日 🐬🐇 💓💕
 */
public class GeoIPChecker {

    private static final String ALLOWED_COUNTRY = "China";
    private static final String ALLOWED_PROVINCE = "Chongqing";

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        Console.log("--------------------------开始时间 " + startTime);
        // 创建 GeoLite2 数据库
        File file = new File("D:\\GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(file).build();
        // 获取客户端 IP
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String ip = JakartaServletUtil.getClientIP(request);
        // 查询地理位置信息
        String siteAddress = getGeoLocation(reader, ip);
        Console.log(siteAddress);
        
        // 判断是否在允许范围内
        if (isAllowed(ip, reader)) {
            Console.log("允许访问");
        } else {
            Console.log("不允许访问");
        }
        long endTime = System.currentTimeMillis();
        Console.log("--------------------------结束时间 " + endTime + " 耗时 " + (endTime - startTime) + " 毫秒");
    }

    public static String getGeoLocation(DatabaseReader reader, String ip) throws IOException, GeoIp2Exception {
        InetAddress ipAddress = InetAddress.getByName(ip);
        CityResponse response = reader.city(ipAddress);

        Country country = response.getCountry();
        Subdivision subdivision = response.getMostSpecificSubdivision();
        City city = response.getCity();
        Location location = response.getLocation();

        return "国家:" + country.getName() +
                "\n省份:" + subdivision.getName() +
                "\n城市:" + city.getName() +
                "\n经度:" + location.getLongitude() +
                "\n纬度:" + location.getLatitude();
    }

    public static boolean isAllowed(String ip, DatabaseReader reader) throws IOException, GeoIp2Exception {
        InetAddress ipAddress = InetAddress.getByName(ip);
        CityResponse response = reader.city(ipAddress);

        // 检查国家和省份是否在允许的范围内
        String country = response.getCountry().getName();
        String province = response.getMostSpecificSubdivision().getName();

        // 使用全局变量进行检查
        if (ALLOWED_COUNTRY.equals(country) && ALLOWED_PROVINCE.equals(province)) {
            return true;
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

❀͜͡傀儡师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值