Java后端怎么获取访问ip地址
时间: 2024-05-02 16:22:09 浏览: 111
Java后端可以通过HttpServletRequest对象的getRemoteAddr()方法来获取访问者的IP地址,示例代码如下:
```java
import javax.servlet.http.HttpServletRequest;
public class IPUtil {
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
```
在上面的代码中,我们先从请求头中获取X-Forwarded-For、Proxy-Client-IP、WL-Proxy-Client-IP、HTTP_CLIENT_IP、HTTP_X_FORWARDED_FOR等字段的值,如果这些字段都为空或unknown,则通过HttpServletRequest对象的getRemoteAddr()方法获取访问者的IP地址。
阅读全文