您当前的位置: 首页 > 

柳鲲鹏

暂无认证

  • 0浏览

    0关注

    4642博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

安卓获取IP的代码

柳鲲鹏 发布时间:2018-05-22 18:14:24 ,浏览量:0

private final static String ETH0 = "eth0";

private static String getLocalIp()
{
   Map map = new HashMap();
   try {
      Enumeration en = NetworkInterface.getNetworkInterfaces();
      while (en.hasMoreElements())
      {
         NetworkInterface intf = en.nextElement();
         String name = intf.getName();
         Enumeration 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在盒子上,也许更通用一些?
关注
打赏
1665724893
查看更多评论
立即登录/注册

微信扫码登录

0.0543s