Android获取MAC地址-getNetworkInterfaces
Posted 黄毛火烧雪下
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android获取MAC地址-getNetworkInterfaces相关的知识,希望对你有一定的参考价值。
/*获取ip-address*/
fun getPhoneIp(): String {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en?.hasMoreElements() == true) {
val intf = en.nextElement()
val enumIpAddr = intf.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return inetAddress.getHostAddress().toString()
}
}
}
} catch (ex: Exception) {
Logger.d("获取ip报错" + ex.printStackTrace())
return ""
}
return ""
}
/**
* 通过网络接口取
* @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;
}
打印输出:WLAN MAC地址 78:36:cc:57:b4:95
注意网络接口的Name有跟多:dummy0、p2p0、wlan0….其中wlan0就是我们需要WiFi mac地址。这个方法android 7.0及其以下版本都可以获取到
建议通过其它方式获取ip
以上是关于Android获取MAC地址-getNetworkInterfaces的主要内容,如果未能解决你的问题,请参考以下文章