java 怎么获取请求IP地址,代码示例
时间: 2023-08-04 10:35:47 浏览: 84
在 Java 中,可以通过 HttpServletRequest 对象的 getRemoteAddr() 方法来获取请求的 IP 地址。具体的代码示例如下:
```java
import javax.servlet.http.HttpServletRequest;
public class GetIPAddress {
public static String getIPAddress(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;
}
}
```
此代码中,我们先通过 request.getHeader() 方法获取 "X-Forwarded-For"、"Proxy-Client-IP" 和 "WL-Proxy-Client-IP" 这三个请求头中的 IP 地址,如果获取不到,则通过 request.getRemoteAddr() 方法获取客户端的 IP 地址。最后返回获取到的 IP 地址。
阅读全文