User Tools

Site Tools


java-example:request-ip

获取requestIP

/** 因为用户可以伪造http header所以,一般都是最曾的nginx配置:
proxy_set_header X-Forward-For $remote_addr;  表示拿用户真实的IP来放到header的 X-forwarded-for中
后面的层次就直接透传
*/
 
    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
                if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                    if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                        ip = request.getRemoteAddr();
                    }
                }
            }
        } else {
            int index = ip.indexOf(",");
            if (index != -1) {
                ip = ip.substring(0, index);
            }
        }
        return ip;
    }
java-example/request-ip.txt · Last modified: 2021/08/22 13:06 by morgan0329

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki