前言

  • 很多时候,项目里需要展示用户的IP属地信息,所以这篇文章就记录一下如何在Java Spring boot项目里获取请求的IP属地

步骤

在pom文件中引入下列依赖

1
2
3
4
5
6
<!--   该依赖可以根据ip地址获取该ip相关的信息     -->
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-ip2region</artifactId>
<version>2.5.6</version>
</dependency>

IpUtil工具类

  • 该工具类对HttpServletRequest解析,得到ip地址字符串
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    public class IpUtil {
    /**
    * 获取客户端ip
    *
    * @param request
    * @return
    */
    public static String getIp(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");

    if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
    // 多次反向代理后会有多个ip值,第一个ip才是真实ip
    if (ip.indexOf(",") != -1) {
    ip = ip.split(",")[0];
    }
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("X-Real-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getRemoteAddr();
    }
    return ip;
    }
    }

    在Controller层编写接口,获取请求的IP属地

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @RestController
    @RequestMapping("/part/util")
    @Api(tags = "工具类", value = "UtilController")
    public class UtilController {
    @Autowired
    private Ip2regionSearcher ip2regionSearcher; // 核心处理类

    @ApiOperation(value = "获取ip属地")
    @GetMapping("/ipCity")
    public String getipCity(HttpServletRequest request) {
    String ip = IpUtil.getIp(request);
    IpInfo ipInfo = ip2regionSearcher.memorySearch(ip);
    String city = ipInfo.getCity();
    return city;
    }
    }

    测试接口

  • 这里我的请求是内网ip,所以返回的结果是“内网ip”,有点像废话hhh。

IpInfo类中的方法

IpInfo

简单介绍一下几个常见的方法

ipInfo.getCountry(); // 国家中文名称
ipInfo.getProvince(); // 中国省份中文名称
ipInfo.getAddress(); // 详细地址
ipInfo.getIsp(); // 互联网服务提供商
ipInfo.isOverseas(); // 是否是国外
ipInfo.getLat(); // 纬度
ipInfo.getLng(); // 经度