首页 > 编程语言 > 详细

java笔记----获取电脑上ip(内网ip)

时间:2019-03-11 12:29:12      阅读:133      评论:0      收藏:0      [点我收藏+]
       private static String getHostIP(){
               String tempIP = "127.0.0.1";
                try {
                    if(isIpv4(InetAddress.getLocalHost().getHostAddress()))
                    tempIP = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
              
              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))
                          {   if(isIpv4(ip.getHostAddress()))
                              return ip.getHostAddress();
                          }
                      }
                  }

                  return tempIP;
              } catch(Exception e){
                  System.out.println("获取IP地址抛出异常");
                  throw new RuntimeException(e);
                
              }
          }
           public static boolean isIpv4(String ipAddress) {  
               
               String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."  
                       +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."  
                       +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."  
                       +"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";  
         
               Pattern pattern = Pattern.compile(ip);  
               Matcher matcher = pattern.matcher(ipAddress);  
               return matcher.matches();  
         
           }  

 

java笔记----获取电脑上ip(内网ip)

原文:https://www.cnblogs.com/tk55/p/10509583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!