JAVA 优先获取外网Ip,再获取内网Ip

1、获取内网Ip

private String getLocalhostIp(){
        String hostAddress = "";
        try {
            InetAddress address = InetAddress.getLocalHost();
            hostAddress = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return hostAddress;
    }

2、获取外网Ip

private String getRemoteAddr() {
        String ip ="";
        try {
            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();
                }
                return ip.split(",")[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

3、获取用户Ip

public String getIpAddr(){
        String ip = this.getRemoteAddr();
        if("".equals(ip)){
            ip = this.getLocalhostIp();
        }
        return ip;    
    }

 

posted @ 2017-10-27 11:10  紫薇帝星的故事  阅读(576)  评论(0编辑  收藏  举报