java获取本机ip,window和linux通用

    public static String getIp() throws SocketException {
        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        String ipStr = "";
        while (allNetInterfaces.hasMoreElements())
        {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements())
            {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address)
                {
                    ipStr = ip.getHostAddress();
                }
            }
        }
        return ipStr;
    }

 

posted @ 2021-11-25 11:04  _Lawrence  阅读(191)  评论(0编辑  收藏  举报