开发喵星球

SpringBoot实现IP地址归属地查询

一、Ip2region简介

一个离线 IP 数据管理框架和定位库,支持亿级别的数据段,10 微秒级别的查询性能,提供了许多主流编程语言的 xdb 数据管理引擎的实现。

Github 地址:

https://github.com/lionsoul2014/ip2region

Gitee 地址:

https://gitee.com/lionsoul/ip2region

功能特性

标准化的数据格式

每个 IP 数据段的 region 信息都固定了格式: 国家|区域|省份|城市|ISP,只有中国的数据绝大部分精确到了城市,其他国家部分数据只能定位到国家,后前的选项全部是 0。

数据去重和压缩

xdb 格式生成程序会自动去重和压缩部分数据,默认的全部 IP 数据,生成的 ip2region.xdb 数据库是 11MB,随着数据的详细度增加数据库的大小也慢慢增大。

极速查询响应

即使是完全基于 xdb 文件的查询,单次查询响应时间在十微秒级别

IP 数据管理框架

v2.0 格式的 xdb 支持亿级别的 IP 数据段行数, region 信息也可以完全自定义。例如:可以在 region 中追加特定业务需求的数据,例如: GPS 信息/国际统一地域信息编码/邮编等。

二、获取 IP 归属地

引入依赖

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

下载 ip2region.xdb

下载地址:

https://gitee.com/lionsoul/ip2region/blob/master/data/ip2region.xdb

将下载后的 ip2region.xdb 文件复制到 resources/ipdb 文件夹下

目录结构如下
image-20231115195706093

三、编写工具类IpUtil

查询格式

{
    "code": "200",
    "data": {
        "省份": "陕西省",
        "国家": "中国",
        "ip": "36.44.97.145",
        "运营商": "电信",
        "城市": "西安市"
    },
    "status": "success"
}

IpUtil.java

package com.kaifamiao.iptoaddress;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IpUtil {
    private static Searcher searcher;

    public static boolean checkIp(String ipAddress) {
        String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    /**
     * 在服务启动时,将 ip2region 加载到内存中
     */
    @PostConstruct
    private static void initIp2Region() {
        try {
            InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
            byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
            searcher = Searcher.newWithBuffer(bytes);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * * 获取 ip 所属地址     *
     * * @param ip ip
     * * @return
     */
    public static Map<String,Object> getIpRegion(String ip) {
        boolean isIp = checkIp(ip);
        if (isIp) {
            initIp2Region();
            Map<String,Object> resp =new HashMap<>();
            try {

                // searchIpInfo 的数据格式: 国家|区域|省份|城市|ISPxx
                String searchIpInfo = searcher.search(ip);
                String[] splitIpInfo = searchIpInfo.split("\\|");
                if (splitIpInfo.length > 0) {
                    if ("中国".equals(splitIpInfo[0])) {
                        // 国内属地返回省份
                        resp.put("国家",splitIpInfo[0]);
                        resp.put("省份",splitIpInfo[2]);
                        resp.put("城市",splitIpInfo[3]);
                        resp.put("运营商",splitIpInfo[4]);

                        return resp;
                    } else if ("0".equals(splitIpInfo[0])) {
                        if ("内网IP".equals(splitIpInfo[4])) {
                            // 内网 IP
                            resp.put("内网 IP",splitIpInfo[0]);
                            return resp;
                        } else {
                            resp.put("status","ERROR");
                            return resp;
                        }
                    } else {
                        // 国外属地返回国家
                        resp.put("国家",splitIpInfo[0]);
                        return resp;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            resp.put("status","ERROR");
            return resp;
//            return "";
        } else {
            throw new IllegalArgumentException("非法的IP地址");
        }
    }
}

四、编写控制器Controller

获取客户端请求过来的Ip地址

String remoteAddr = request.getRemoteAddr();
        // 如果使用了代理,如Nginx, Apache等,需从以下header中获取真实IP
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");
        String ip = (forwarded != null) ? forwarded.split(",")[0] : (realIp != null) ? realIp : remoteAddr;


package com.kaifamiao.iptoaddress;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Demo {
    @GetMapping("/getIp")
    public Map<String, Object> getIp(HttpServletRequest request) {

        String remoteAddr = request.getRemoteAddr();
        // 如果使用了代理,如Nginx, Apache等,需从以下header中获取真实IP
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");
        String ip = (forwarded != null) ? forwarded.split(",")[0] : (realIp != null) ? realIp : remoteAddr;



        //获取IP地址后,格式化输出

        Map<String, Object> response = new HashMap<>();
        response.put("code", "200");
        response.put("status", "success");

        Map<String, Object> data = IpUtil.getIpRegion(ip);
        data.put("ip", ip);
        response.put("data", data);



        return response;
    }
}

五、使用

a、局域网

image-20231115200422597

b、部署到服务器后访问

image-20231115200540793

c、本机访问

image-20231115200639588
互联网演示地址

http://blog.kaifamiao.com/getIp

六、最后

gitee地址:

https://gitee.com/kaifamiaos/iptoaddress

附:获取客户端请求IP地址

package com.example.demo;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtil {
    private static final String UNKNOWN = "unknown";
    private static final String HEADER_FORWARDED = "x-forwarded-for";
    private static final String HEADER_PROXY = "Proxy-Client-IP";
    private static final String HEADER_WL_PROXY = "WL-Proxy-Client-IP";
    private static final String HEADER_HTTP = "HTTP_CLIENT_IP";
    private static final String HEADER_HTTP_FORWARDED = "HTTP_X_FORWARDED_FOR";
    private static final String LOCAL_IP = "127.0.0.1";
    private static final String LOCAL_HOST = "localhost";
    /**     * 获取 IP 地址     *     * @param request     * @return     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader(HEADER_FORWARDED);
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_PROXY);        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_WL_PROXY);        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_HTTP);        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HEADER_HTTP_FORWARDED);        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();        }        // 本机访问
        if (LOCAL_IP.equalsIgnoreCase(ip) || LOCAL_HOST.equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
            // 根据网卡取本机配置的 IP
            try {
                InetAddress localHost = InetAddress.getLocalHost();
                ip = localHost.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }        // 对于通过多个代理的情况,第一个 IP 为客户端真实 IP,多个 IP 按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 15) {
                ip = ip.substring(0, ip.indexOf(","));
            }        }        return ip;
    }}

   
分类:技术栈 作者:开发喵 发表于:2023-11-15 21:54:51 阅读量:98
<<   >>


powered by kaifamiao