springboot 获取请求的ip地址
时间: 2023-11-18 20:20:37 浏览: 88
springboot获取URL请求参数的多种方式
可以通过HttpServletRequest对象获取请求的IP地址。具体实现可以参考以下代码:
```
@RequestMapping("/get/ip")
@ResponseBody
public String getIp(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 ipAddress;
}
```
这段代码会先从请求头中获取"X-Forwarded-For"字段的值,如果没有则会尝试获取"Proxy-Client-IP"和"WL-Proxy-Client-IP"字段的值,最后如果都没有获取到,则会返回请求的远程IP地址。
阅读全文