商务合作:179001057@qq.com

使用java取得本机的IP地址的方法

技术2022-05-11  0


某平台价值19860元的编程课程资料免费领取【点我领取】


public String getHostIP() {        String localHostIP = null;        try {            // ms windowsのIPを取得する。            String osName2UpperCase = System.getProperty("os.name").toUpperCase();            if (osName2UpperCase.indexOf("WINDOWS") >= 0) {                InetAddress localHostAddr = InetAddress.getLocalHost();                localHostIP = localHostAddr.getHostAddress();            } else {                // LinuxのIPを取得する。                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface                        .getNetworkInterfaces();                Enumeration<InetAddress> netAddresses = null;                InetAddress netAddr = null;                while (allNetInterfaces.hasMoreElements()) {                    netAddresses = allNetInterfaces.nextElement().getInetAddresses();                    while (netAddresses.hasMoreElements()) {                        netAddr = netAddresses.nextElement();                        if (netAddr.isSiteLocalAddress() && !netAddr.isLoopbackAddress()                                && netAddr.getHostAddress().indexOf(":") == -1) {                            localHostIP = netAddr.getLocalHost().getHostAddress();                        }                    }                }            }        } catch (Exception e) {            // ログを出力する。            log.error(DONOT_GET_IP, e);        }        return localHostIP;    }


最新回复(0)