怎么获取请求的ip地址,java代码示例
时间: 2024-05-02 08:22:25 浏览: 185
java获取ip地址示例
5星 · 资源好评率100%
获取请求的ip地址可以通过获取HttpServletRequest对象,从中获取remoteAddr属性来实现。以下是一个Java代码示例:
```
import javax.servlet.http.HttpServletRequest;
public class IPUtils {
public static String getClientIpAddress(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;
}
}
```
在使用时,可以通过以下代码获取请求的IP地址:
```
HttpServletRequest request = ...; // 获取HttpServletRequest对象
String ipAddress = IPUtils.getClientIpAddress(request);
```
阅读全文