/**
* 遍历循环所有的网络接口,找到接口是 wlan0
* 必须的权限 <uses-permission android:name="android.permission.INTERNET" />
*
* @return mac from hardware
*/
public static String getMacWlan() {
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 "";
}
// 16进制转化
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02x:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
String s = res1.toString();
if (TextUtils.isEmpty(s)) {
s = getMacByCmd("cat /sys/class/net/wlan0/address");
}
return s;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取以太网mac
*
* @return the mac address
*/
public static String getMacEth() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("eth0")) {
continue;
}
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
// 16进制转化
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02x:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
String s = res1.toString();
if (TextUtils.isEmpty(s)) {
s = getMacByCmd("cat /sys/class/net/eth0/address");
}
return s;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}
Android设备如何获取mac值
最新推荐文章于 2024-08-15 16:27:36 发布