spring boot 获取用户ip
时间: 2023-11-17 20:08:34 浏览: 78
可以通过HttpServletRequest对象获取用户IP地址,代码如下:
```java
@Autowired
HttpServletRequest request;
String userIp = request.getRemoteAddr();
```
或者通过代理服务器的方式获取真实IP地址,代码如下:
```java
@Autowired
HttpServletRequest request;
String userIp = request.getHeader("X-Real-IP");
if (userIp == null || userIp.length() == 0 || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getHeader("X-Forwarded-For");
}
if (userIp == null || userIp.length() == 0 || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getHeader("Proxy-Client-IP");
}
if (userIp == null || userIp.length() == 0 || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getHeader("WL-Proxy-Client-IP");
}
if (userIp == null || userIp.length() == 0 || "unknown".equalsIgnoreCase(userIp)) {
userIp = request.getRemoteAddr();
}
```
阅读全文