近来遇到一个问题,发现调试的小板,在不同的平台上,获取mac的方式有所不同。下面做个总结:
public String getMacAddress() { String macAddress = SystemProperties.get("ubootenv.var.ethaddr"); String[] strings = macAddress.toLowerCase().split(":"); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < strings.length; i++) { stringBuilder.append(strings[i]); } Log.i(TAG, "--- DVB Mac Address : " + stringBuilder.toString()); return stringBuilder.toString(); }
先添加权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
public String getMacAddress() { String mac = ""; // 获取wifi管理器 WifiManager wifiMng = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfor = wifiMng.getConnectionInfo(); mac = wifiInfor.getMacAddress(); Log.i(TAG, "--- DVB Mac Address : " + mac); return mac; }
查看/sys/class/net/eth0 目录下的address文件,这就是mac地址文件的保存位置,剩下的工作就是去解析这个文件了。
private String getMacAddress() { String strMacAddr = ""; byte[] b; try { NetworkInterface NIC = NetworkInterface.getByName("eth0"); b = NIC.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 (SocketException e) { e.printStackTrace(); } Log.i(TAG, "--- DVB Mac Address : " + strMacAddr); return strMacAddr; }
运行结果: