java怎么获取浏览器ip

1112
2024/9/26 6:31:56
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,您可以通过HttpServletRequest对象来获取浏览器的IP地址。以下是一个简单的方法:

import javax.servlet.http.HttpServletRequest;

public 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.getHeader("HTTP_CLIENT_IP");
    }
    
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
    }
    
    return ipAddress;
}

这个方法首先检查请求头中的"X-Forwarded-For"字段,因为在经过代理服务器时,客户端的真实IP地址可能会被放在这个字段中。如果没有找到有效的IP地址,它会继续检查其他可能包含IP地址的请求头字段。最后,如果所有这些字段都没有找到有效的IP地址,它会使用HttpServletRequest的getRemoteAddr()方法来获取IP地址。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java系统找不到指定的路径