获取Linux本地地址 即使服务在容器中

public static String getLocalIp() {
            String ip="";
            if (System.getProperty("os.name").toLowerCase().indexOf("windows")>-1) {
                try {
                    ip= InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    logger.error("UnknownHostException {}",e);
                }
            }else {
               try {                    
                for(Enumeration<NetworkInterface> en=    NetworkInterface.getNetworkInterfaces();en.hasMoreElements();) {
                    NetworkInterface interf = en.nextElement();
                    String name= interf.getName();
                    if (!name.contains("docker")&&!name.contains("lo")) {
                        for(Enumeration<InetAddress>enumeAddress=interf.getInetAddresses();enumeAddress.hasMoreElements();) {
                            InetAddress address=    enumeAddress.nextElement();
                            if (!address.isLoopbackAddress()) {
                                String ipAddress= address.getHostAddress().toString();
                                if (!ipAddress.contains("::")&&!ipAddress.contains("0:0")&&!ipAddress.contains("fe80")) {
                                    ip= ipAddress;
                                }
                            }
                        }
                    }
                }
               } catch (Exception e) {
                   logger.error("get Linux local ip error {}",e);
                }
            }
            return ip;
        }

 

posted @ 2021-05-21 11:14  蒙恬括  阅读(115)  评论(0编辑  收藏  举报