zoukankan      html  css  js  c++  java
  • java获取机器IP地址常用方法

       private String getHostIP(){
    
            Enumeration<NetworkInterface> 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<InetAddress> 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;
             
        }

        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<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
                InetAddress ip = null;
                Enumeration<InetAddress> 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);
            }
        }

    本机

  • 相关阅读:
    python基础之列表解析
    初学者学习python2还是python3?
    给曾经是phper的程序员推荐个学习网站
    详解python2 和 python3的区别
    Python如何进行中文注释
    import方法引入模块详解
    详解python 局部变量与全局变量
    131-19. 删除链表的倒数第N个节点
    65.django中关于跨域访问设置
    130-283. 移动零
  • 原文地址:https://www.cnblogs.com/tk55/p/9592500.html
Copyright © 2011-2022 走看看