zoukankan      html  css  js  c++  java
  • 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();  
             
               }  
  • 相关阅读:
    游戏方案
    团队介绍
    【面向对象程序设计】作业四
    FIFO与LRU实现(Java)
    spring事务介绍
    微信抢红包算法
    Hibernate Dao映射配置通用接口类反射获取加载calass实例
    股票两次买卖最大收益(java)
    Eclipse安装JD-Eclipse反编译插件看源码
    Java GC调优
  • 原文地址:https://www.cnblogs.com/tk55/p/10509583.html
Copyright © 2011-2022 走看看