如何获取远程IP地址如180.171.121.32

    private static String getRemoteIp(HttpServletRequest request) {
        //x-forwarded-for:代表客户端,也就是HTTP的请求端真实的IP,只有在通过了HTTP代理或者负载均衡服务器时才会添加该项
        String ip = request.getHeader("x-forwarded-for");
        //Proxy-Client-IP和WL-Proxy-Client-IP: 只有在Apache(Weblogic Plug-In Enable)+WebLogic搭配下出现,其中“WL”就是WebLogic的缩写
        //访问路径是:Client -> Apache WebServer + Weblogic http plugin -> Weblogic Instances
        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();
        }
//        ip = "61.51.253.90";
//        ip = "218.25.19.153";
        //0:0:0:0:0:0:0:1: IPV6的形式,win7下可能会出现
        //获取远程IP地址
 
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

这段代码只能返回0:0:0:0:0:0:0:1

car
浏览 1851回答 2
2回答

逆光之羽

ip是环回地址不是因为项目是在本机启动,然后又是本机去调用对应接口造成的么?

言曌博客liuyanzhao_com

//获得物理ip public static String getIpAddr(HttpServletRequest request){     String ipAddress = request.getHeader("x-forwarded-for");     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {         ipAddress = request.getHeader("Proxy-Client-IP");     }     if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {         ipAddress = request.getHeader("WL-Proxy-Client-IP");     }     if(ipAddress == null || ipAddress.length() == 0 || "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按照','分割     if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15         if(ipAddress.indexOf(",")>0){             ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));         }     }     return ipAddress; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java