有個(gè)需求:需要在Android設(shè)備上獲取所連(有線或無(wú)線)網(wǎng)絡(luò)路由器的mac,幾番搜索查詢終于找到一個(gè)可行方法,目前在Android8.1和Android12上驗(yàn)證都是可用的。在此記錄一下
/**
* 使用shell命令來(lái)獲取網(wǎng)關(guān)IP
* @return
*/
fun getGatewayIp(): String {
var result = ""
val order = "ip route list table 0"
try {
val exec = Runtime.getRuntime().exec(order)
val buff = BufferedReader(InputStreamReader(exec.inputStream))
var line: String? = ""
while (true){
line = buff.readLine()
Log.i("getGatewayIp", "result: $line")
if (line == null){
Log.i("getGatewayIp", "read finished")
break
} else{
result = line.trim().split("\\s+".toRegex()).toTypedArray()[2]
break
}
}
buff.close()
exec.waitFor()
} catch (e: Exception) {
e.printStackTrace()
}
Log.i("getGatewayIp", "gateway is $result")
return result
}
/**
* 使用shell命令來(lái)獲取網(wǎng)關(guān)mac
* @return
*/
fun getGatewayMac(): String {
var result = ""
val order = "ip neigh show"
try {
val exec = Runtime.getRuntime().exec(order)
val buff = BufferedReader(InputStreamReader(exec.inputStream))
var line: String? = ""
val gateWayIp = getGatewayIp()
while (true){
line = buff.readLine()
Log.i("getGatewayMac", "result: $line")
if (line == null){
Log.i("getGatewayMac", "read finished")
break
} else if (line.contains(gateWayIp)) {
result = line.trim().split("\\s+".toRegex()).toTypedArray()[4]
break
}
}
buff.close()
exec.waitFor()
} catch (e: Exception) {
e.printStackTrace()
}
Log.i("getGatewayMac", "mac is $result")
return result
}