JAVA获取客户端IP地址

  • 场景:需要服务端获取到客户端得ip,然后塞到请求参数中。

  • 自己整理了下这两种获取客户端IP得方法。目前自己在使用得是第二种。

  1. 第一种方法

 public static String getIp2(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
  1. 第二种方法

public static String getClinetIP(HttpServletRequest request){
        String ip = null;
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            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("entrust-client-ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip.trim())){
                InetAddress inetAddress = null;
                try{
                    inetAddress =InetAddress.getLocalHost();
                }catch (UnknownHostException e){
                    System.out.println("获取IP地址失败");
                }
                ip = inetAddress.getHostAddress();
            }
        }
        //多级 方向代理
        if (ip.indexOf(",")>0){
            ip = ip.substring(0,ip.indexOf(",")).trim();
        }
        
        return ip;
    }

你可能感兴趣的:(java,servlet,tcp/ip,intellij-idea)