springboot如何获取请求方ip地址
时间: 2023-12-29 14:49:27 浏览: 83
Spring Boot可以通过HttpServletRequest对象获取请求方IP地址,代码如下:
```
@Autowired
private HttpServletRequest request;
public String getClientIP() {
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;
}
```
此方法通过检查一系列HTTP头来获取请求方的IP地址,包括x-forwarded-for、Proxy-Client-IP和WL-Proxy-Client-IP等。如果这些头都不存在或者值为unknown,则使用request.getRemoteAddr()获取IP地址。
阅读全文