天天看点

安卓获取IP的代码

private final static String ETH0 = "eth0";
 
private static String getLocalIp()
{
   Map<String, String> map = new HashMap<String, String>();
   try {
      Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
      while (en.hasMoreElements())
      {
         NetworkInterface intf = en.nextElement();
         String name = intf.getName();
         Enumeration<InetAddress> ipAddr = intf.getInetAddresses();
         while ( ipAddr.hasMoreElements())
         {
            InetAddress inetAddress = ipAddr.nextElement();
            String hostAddress = inetAddress.getHostAddress();
            if (TextUtils.isEmpty(hostAddress)
                  || inetAddress.isLoopbackAddress()
                  || inetAddress.isLinkLocalAddress()
                  || (inetAddress instanceof Inet6Address))
            {
               continue;
            }
            map.put(name, hostAddress);
         }
      }
 
      //如果有以太网ip,去以太网ip,如果没有,取第一个ip
      if(map.containsKey(ETH0))
      {
         return map.get(ETH0);
      }
      return (String) map.values().toArray()[0];
   } catch (Exception e) {
   }
   return null;
}      
这里的HashMap在盒子上,也许更通用一些?      

继续阅读