springboot 获取请求的ip地址
时间: 2023-11-18 21:12:51 浏览: 149
你可以通过以下代码来获取Spring Boot中的请求IP地址:
```java
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public String getIpAddress() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
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` 字段获取,最后再从 `request.getRemoteAddr()` 获取。
阅读全文