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

       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();  
         
           }  

 

posted on 2019-03-11 11:33  Honey_Badger  阅读(727)  评论(1编辑  收藏  举报

导航

github