springboot怎么获取用户的公网ip地址
时间: 2023-10-03 19:11:14 浏览: 151
可以通过HttpServletRequest对象获取用户的公网ip地址,代码如下:
```java
@RequestMapping("/getIp")
public String getIp(HttpServletRequest request) {
String ip = request.getHeader("X-Real-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
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.getRemoteAddr();
}
return ip;
}
```
上面的代码中,首先尝试从请求头中获取X-Real-IP和X-Forwarded-For字段的值作为ip地址。如果这两个字段都没有,则尝试从其他请求头中获取ip地址。如果还是没有,则使用request.getRemoteAddr()方法获取ip地址。
阅读全文