java获取机器IP地址常用方法

   private String getHostIP(){

        Enumeration allNetInterfaces = null;
        String resultIP=null;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements())
        {
        NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
        System.out.println(netInterface.getName());
        Enumeration addresses = netInterface.getInetAddresses();
        while (addresses.hasMoreElements())
        {
        ip = (InetAddress) addresses.nextElement();
        if (ip != null && ip instanceof Inet4Address)
        { 
           if(resultIP==null)
            resultIP= ip.getHostAddress();  
           System.out.println("本机地址是:"+ip.getHostAddress());
        
        } 
        }
        }
          return resultIP;
         
    }

java获取机器IP地址常用方法_第1张图片

    private String getHostIP(){
         String tempIP = "127.0.0.1";
        try {
            tempIP = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         System.out.println(tempIP);
        try{
            Enumeration networks = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            Enumeration addrs;
            while (networks.hasMoreElements())
            {
                addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements())
                {
                    ip = addrs.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && ip.isSiteLocalAddress()
                            && !ip.getHostAddress().equals(tempIP))
                    {
                        return ip.getHostAddress();
                    }
                }
            }

            return tempIP;
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

 

java获取机器IP地址常用方法_第2张图片

 

本机

java获取机器IP地址常用方法_第3张图片

 

你可能感兴趣的:(java获取机器IP地址常用方法)