samaxu
V2EX  ›  问与答

Java 获取请求 ip 失败

  •  
  •   samaxu · Oct 31, 2018 · 1488 views
    This topic created in 2787 days ago, the information mentioned may be changed or developed.

    同一个方法,在接口 1、A 服务器上获取不了 ip,在接口 2、A 服务器上能获取,在接口 1、B 服务器上能获取 真是奇了怪了 方法如下

    public String getIpAddr(HttpServletRequest request) {
            String 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.getRemoteAddr();
                if(ip.equals("127.0.0.1")){
                    //根据网卡取本机配置的 IP
                    InetAddress inet=null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ip= inet.getHostAddress();
                }
            }
            // 多个代理的情况,第一个 IP 为客户端真实 IP,多个 IP 按照','分割
            if(ip != null && ip.length() > 15){
                if(ip.indexOf(",")>0){
                    ip = ip.substring(0,ip.indexOf(","));
                }
            }
            return ip;
        }
    
    2 replies    2018-10-31 13:05:35 +08:00
    limuyan44
        1
    limuyan44  
       Oct 31, 2018 via Android
    我遇见过的是机器有问题,取 ip 的时候会一直卡着直到抛异常每次都要重启后来找人看了下最后出了个方案好像把什么配置给关了
    samaxu
        2
    samaxu  
    OP
       Oct 31, 2018
    @limuyan44 #1 没有任何异常就是取不到,都是 null
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5062 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 07:32 · PVG 15:32 · LAX 00:32 · JFK 03:32
    ♥ Do have faith in what you're doing.