/**
* 获取设备 MAC 地址(优先返回有线 MAC,其次 WiFi MAC)
* 注意:Android 10+ 会返回伪装的 MAC 地址
*/
@SuppressLint("HardwareIds", "MissingPermission")
fun getMacAddress(context: Context): String {
// 1. 优先获取有线 MAC
var mac = getEthernetMacAddress()
if (!TextUtils.isEmpty(mac)) return mac
// 2. 获取 WiFi MAC
mac = getWifiMacAddress(context)
if (!TextUtils.isEmpty(mac)) return mac
// 3. 最终兜底方案
return "02:00:00:00:00:00" // Android 10+ 默认返回值
}
/**
* 获取有线网络 MAC 地址
*/
private fun getEthernetMacAddress(): String {
return try {
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val networkInterface = interfaces.nextElement()
// 根据接口名称判断有线网卡(不同设备可能名称不同)
if (networkInterface.name.equals("eth0", ignoreCase = true)) {
val macBytes = networkInterface.hardwareAddress ?: continue
return bytesToHex(macBytes)
}
}
""
} catch (e: Exception) {
e.printStackTrace()
""
}
}
/**
* 获取 WiFi MAC 地址
*/
@SuppressLint("HardwareIds", "MissingPermission")
private fun getWifiMacAddress(context: Context): String {
return when {
// Android 10+ 返回伪装地址
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> "02:00:00:00:00:00"
else -> try {
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val info = wifiManager.connectionInfo
info.macAddress ?: ""
} catch (e: Exception) {
e.printStackTrace()
""
}
}
}
/**
* 字节数组转 MAC 地址格式
*/
private fun bytesToHex(bytes: ByteArray): String {
val sb = StringBuilder()
for (b in bytes) {
sb.append(String.format("%02x:", b))
}
if (sb.isNotEmpty()) sb.deleteCharAt(sb.length - 1)
return sb.toString()
}
获取mac工具类
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 1. IMEI IMEI(International Mobile Equipment Identity)是国际移...
- LZ-Says:给大家推荐一个网站,有兴趣可以查阅,想为大家贡献一点自己的力量也可以投稿,老大审核通过会发表,更好...
- 前言: 各位同学大家好有段时间没有给大家更新博客 具体多久我不记得了 今天有朋友问我 获取手机好的问题 所以就自...
- 本人开发过程中遇到的问题,类似map获取数据的方式,根据枚举类code获取msg。 第一步,定义CodeEnum接...
- + (UIColor *)colorWithHexString:(NSString *)color { NSStr...