当前位置: 移动技术网 > 移动技术>移动开发>Android > Android手机获取Mac地址的几种方法

Android手机获取Mac地址的几种方法

2019年07月29日  | 移动技术网移动技术  | 我要评论

最常用的方法,通过wifimanager获取:

/**
 * 通过wifimanager获取mac地址
 * @param context
 * @return
 */
 private static string trygetwifimac(context context) {
 wifimanager wm = (wifimanager) context.getapplicationcontext().getsystemservice(context.wifi_service);
 wifiinfo wi = wm.getconnectioninfo();
 if (wi == null || wi.getmacaddress() == null) {
  return null;
 }
 if ("02:00:00:00:00:00".equals(wi.getmacaddress().trim())) {
  return null;
 } else {
  return wi.getmacaddress().trim();
 }
 }

这个方法android 7.0是获取不到的,返回的是null,其实是返回“02:00:00:00:00:00”

根据本地ip获取:

/**
 * 根据ip地址获取mac地址
 * @return
 */
 private static string getlocalmacaddressfromip() {
 string strmacaddr = null;
 try {
  //获得ipd地址
  inetaddress ip = getlocalinetaddress();
  byte[] b = networkinterface.getbyinetaddress(ip).gethardwareaddress();
  stringbuffer buffer = new stringbuffer();
  for (int i = 0; i < b.length; i++) {
  if (i != 0) {
   buffer.append(':');
  }
  string str = integer.tohexstring(b[i] & 0xff);
  buffer.append(str.length() == 1 ? 0 + str : str);
  }
  strmacaddr = buffer.tostring().touppercase();
 } catch (exception e) {
 }
 return strmacaddr;
 }
/**
 * 获取移动设备本地ip
 * @return
 */
 private static inetaddress getlocalinetaddress() {
 inetaddress ip = null;
 try {
  //列举
  enumeration<networkinterface> en_netinterface = networkinterface.getnetworkinterfaces();
  while (en_netinterface.hasmoreelements()) {//是否还有元素
  networkinterface ni = (networkinterface) en_netinterface.nextelement();//得到下一个元素
  enumeration<inetaddress> en_ip = ni.getinetaddresses();//得到一个ip地址的列举
  while (en_ip.hasmoreelements()) {
   ip = en_ip.nextelement();
   if (!ip.isloopbackaddress() && ip.gethostaddress().indexof(":") == -1)
   break;
   else
   ip = null;
  }
  if (ip != null) {
   break;
  }
  }
 } catch (socketexception e) {
  e.printstacktrace();
 }
 return ip;
 }

这个方法android 7.0及其以下版本都可以获取到。

根据网络接口获取:

 /**
 * 通过网络接口取
 * @return
 */
 private static string getnewmac() {
 try {
  list<networkinterface> all = collections.list(networkinterface.getnetworkinterfaces());
  for (networkinterface nif : all) {
  if (!nif.getname().equalsignorecase("wlan0")) continue;
  byte[] macbytes = nif.gethardwareaddress();
  if (macbytes == null) {
   return null;
  }
  stringbuilder res1 = new stringbuilder();
  for (byte b : macbytes) {
   res1.append(string.format("%02x:", b));
  }
   if (res1.length() > 0) {
   res1.deletecharat(res1.length() - 1);
  }
  return res1.tostring();
  }
 } catch (exception ex) {
  ex.printstacktrace();
 }
 return null;
 }

注意网络接口的name有跟多:dummy0、p2p0、wlan0....其中wlan0就是我们需要wifi mac地址。这个方法android 7.0及其以下版本都可以获取到。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网