注:方法一(adb shell命令在安卓7.0及以后不能用)
方法一:
/**
* 这是使用adb shell命令来获取mac地址的方式
* @return
*/
public static String getMac() {
String macSerial = null;
String str = "";
try {
Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null){
macSerial = str.trim();// 去空格
break;
}
}
} catch (IOException ex) {
// 赋予默认值
ex.printStackTrace();
}
return macSerial;
}
方法二:
/**
* 通过网络接口取
* @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;
}
方法三:
/**
* 根据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;
}
测试统计:
安卓4版本
方法一:74 5C 9F06 1C CF
方法二:74 5C 9F06 1C CF
方法三:74 5C 9F06 1C CF
安卓7版本
方法一:无法获取
方法二:00 5A 13 35 01 8B
目前发现有的方法在某些安卓版本并不兼容,若你发现或者有更好的方法,欢迎交流!