灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:4333回复:0

android下获取有线和无线的Ip地址

楼主#
更多 发布于:2012-09-06 14:02

Android的开发时,遇到了获取有线ip地址的问题.不多说 上代码!
for (Enumeration<Networkinterface> en = NetworkInterface
     .getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();
    if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")) {
     for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
      InetAddress inetAddress = enumIpAddr.nextElement();
      if (!inetAddress.isLoopbackAddress()) {
       ipaddress = inetAddress.getHostAddress().toString();
       if(!ipaddress.contains("::")){//ipV6的地址
        return ipaddress;
       }
      }
     }
    } else {
     continue;
    }
   }
红色地方表示:仅过滤无线和有线的ip. networkInterface是有很多的名称的 比如sim0,remt1.....等等.我不需要用到就直接过滤了
绿色的地方表示: 过滤掉ipv6的地址.不管无线还是有线 都有这个地址, 我这边显示地址大体是:fe80::288:88ff:fe00:1%eth0   fe80::ee17:2fff:fece:c0b4%wlan0 一般都是出现在第一次循环.第二次循环就是真正的ipv4的地址.


摘自 Adam Viki


喜欢0 评分0
游客

返回顶部