android IP getIP

Android 通用获取Ip的方法   编辑文档 
   学分 +2 
大家好,我们这一节讲一下,Android获取Ip的一些方法,在我们开发中,有判断手机是否联网,或者想获得当前手机的Ip地址,当然WIFI连接的和

  我们3G卡的Ip地址当然是不一样的.

  首先我尝试了如下方法:

  view plaincopy to clipboardprint?

  WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

  WifiInfo wifiInfo = wifiManager.getConnectionInfo();

  int ipAddress = wifiInfo.getIpAddress();

  WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

  WifiInfo wifiInfo = wifiManager.getConnectionInfo();

  int ipAddress = wifiInfo.getIpAddress();

  但是获得的居然是一个整数,我尝试了用些数学方法都没有成功!,所以这种方法不可取!

  最后查了一些资料,发现如下方法是比较通用的,我尝试了WIFI和G3卡,都获取了争取的Ip地址:代码如下:

  view plaincopy to clipboardprint?

  public String getLocalIpAddress() {

  try {

  for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {

  NetworkInterface intf = en.nextElement();

  for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

  InetAddress inetAddress = enumIpAddr.nextElement();

  if (!inetAddress.isLoopbackAddress()) {

  return inetAddress.getHostAddress().toString();

  }

  }

  }

  } catch (SocketException ex) {

  Log.e(LOG_TAG, ex.toString());

  }

  return null;

  }

  public String getLocalIpAddress() {

  try {

  for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {

  NetworkInterface intf = en.nextElement();

  for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

  InetAddress inetAddress = enumIpAddr.nextElement();

  if (!inetAddress.isLoopbackAddress()) {

return inetAddress.getHostAddress().toString();

  }

  }

  }

  } catch (SocketException ex) {

  Log.e(LOG_TAG, ex.toString());

  }

  return null;

  }

  当我的手机处于飞行状态是,获得Ip地址为空,刚好符合要求!!!

  希望对大家有所帮助!谢谢~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值