获取mac工具类

/**
     * 获取设备 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()
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容