第一种方法
public static String getMacAddress() {
String macAddress = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
byte[] bytes = networkInterface.getHardwareAddress();
if (bytes == null || bytes.length == 0) {
continue;
}
StringBuffer buffer = new StringBuffer();
for (byte b : bytes) {
buffer.append(String.format("%02X:", b));
}
if (buffer.length() > 0) {
buffer.deleteCharAt(buffer.length() - 1);
}
macAddress = buffer.toString();
Log.d("mac", "interface name=" + networkInterface.getName() + ", mac address=" + macAddress);
}
} catch (SocketException e) {
e.printStackTrace();
}
return macAddress;
}
第二种方法
public static String getMacAddress2() {
String macAddress = "";
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface networkInterface : interfaces) {
Log.e("DoorCard", "Mac Address Name: " + networkInterface.getName());
if (!networkInterface.getName().equalsIgnoreCase("wlan0")) {
continue;
}
byte[] bytes = networkInterface.getHardwareAddress();
if (bytes == null) {
return "";
}
StringBuffer buf = new StringBuffer();
for (byte b : bytes) {
Log.e("DoorCard", "b=" + b);
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
macAddress = buf.toString();
return macAddress;
}
} catch (SocketException e) {
e.printStackTrace();
}
return macAddress;
}