spring cloud gateway 获取请求真实ip

https://www.csdn.net/

public static String getIpAddress(ServerHttpRequest request) {
    HttpHeaders headers = request.getHeaders();
    String ip = headers.getFirst("x-forwarded-for");
    if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
        // 多次反向代理后会有多个ip值,第一个ip才是真实ip
        if (ip.indexOf(",") != -1) {
            ip = ip.split(",")[0];
        }
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = headers.getFirst("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = headers.getFirst("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = headers.getFirst("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = headers.getFirst("X-Real-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddress().getAddress().getHostAddress();
    }
    return ip;
}
————————————————
版权声明:本文为CSDN博主「枫树湾河桥」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_16511223/article/details/95592633

你可能感兴趣的:(springcloud)