当前位置: 首页 > 工具软件 > request-ip > 使用案例 >

用request获取请求地址Ip

宇文学博
2023-12-01

public String getIpAddr(HttpServletRequest request) throws Exception {
    String ipAddress = null;
    String[] header = {"x-forwarded-for","Proxy-Client-IP","WL-Proxy-Client-IP"};
    for (int i = 0; i < header.length; i++) {
        ipAddress = request.getHeader(header[i]);
        if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
            continue;
        } else {
            break;
        }
    }
    if (StringUtils.isEmpty(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            // 根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }
    }
    // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    // "***.***.***.***".length() = 15
    if (!StringUtils.isEmpty(ipAddress) && ipAddress.length() > 15) {
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
    } else if (StringUtils.isEmpty(ipAddress)) {
        throw new Exception("获取ip异常");
    }
    return ipAddress;
}
 类似资料: