Spring Boot获取客户端的IP地址

前言

在Web应用程序中,获取客户端的IP地址是一项非常常见的需求,例如记录访问日志、过滤恶意IP等。在本文中,我们将介绍如何使用Spring Boot框架获取客户端的IP地址。

方法一:使用ServletRequest对象获取IP地址

Spring Boot应用程序可以使用HttpServletRequest对象获取客户端的IP地址。在Spring Boot中,可以通过注入HttpServletRequest作为一个参数来获取该对象。

@GetMapping("/getIp")
public String getIp(HttpServletRequest request) {
    
    
    String ipAddress = request.getRemoteAddr();
    return "Client IP address: " + ipAddress;
}

上述代码中,我们通过调用 request.getRemoteAddr() 方法获取客户端的IP地址。

方法二:使用ServletRequestAttributes对象获取IP地址

除了使用HttpServletRequest对象外,Spring Boot还提供了另一种获取客户端IP地址的方法。这种方法是使用ServletRequestAttributes对象,在方法中注入该对象即可。代码如下:

@GetMapping("/getIp2")
public String getIp2(ServletRequest request) {
    
    
    String ipAddress = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
    return "Client IP address: " + ipAddress;
}

在上面的代码中,我们通过 RequestContextHolder.currentRequestAttributes() 方法获取当前的HttpServletRequest对象,再通过 getRequest().getRemoteAddr() 方法获取客户端的IP地址。

注意事项

虽然以上两种方法可以获取客户端的IP地址,但需要注意以下几个问题:

  • 如果应用程序部署在反向代理服务器后面,使用上述方法获取的IP地址可能是反向代理服务器的IP地址,而不是客户端真正的IP地址。
  • 有些客户端可能使用了匿名代理服务器,例如TOR等,此时获取到的IP地址不是客户端真正的IP地址。

解决方案:使用X-Forwarded-For头

为了解决上述问题,我们可以使用X-Forwarded-For头。该头字段是一个逗号分隔的IP地址列表,最左边的IP地址是客户端的真实IP地址。以下是使用X-Forwarded-For头获取客户端IP地址的示例代码。

@GetMapping("/getIp3")
public String getIp3(HttpServletRequest request) {
    
    
    String ipAddress = request.getHeader("X-Forwarded-For");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    
    
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    
    
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
    
    
        ipAddress = request.getRemoteAddr();
    }
    return "Client IP address: " + ipAddress.split(",")[0];
}

上述代码中,我们首先使用 request.getHeader("X-Forwarded-For") 方法获取X-Forwarded-For头字段的值,如果获取失败,则尝试使用其他头字段。最后,我们通过逗号对IP地址进行分割,获取最左边的IP地址,即客户端的真实IP地址。

总结

本文介绍了使用Spring Boot框架获取客户端IP地址的三种方法:
1.使用HttpServletRequest对象
2.使用ServletRequestAttributes对象
3.使用X-Forwarded-For头
当我们需要获取客户端的真实IP地址时,应该使用X-Forwarded-For头解决代理服务器和匿名代理服务器的问题。

猜你喜欢

转载自blog.csdn.net/weixin_65950231/article/details/130903477
今日推荐