网络信息

    fun myTest(){
val connectivityManager=getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetWorkInfo=connectivityManager.activeNetworkInfo
if (activeNetWorkInfo!=null&&activeNetWorkInfo.isConnected){
Log.d("qtest","网络信息:${connectivityManager.getLinkProperties(connectivityManager.activeNetwork).toString()}")
val linkAddress=connectivityManager.getLinkProperties(connectivityManager.activeNetwork)?.linkAddresses
if (linkAddress!=null&& linkAddress.isNotEmpty()){
for(i in 0 until linkAddress.size){
val addresses=linkAddress[i].address
Log.d("qtest","ip地址:${addresses.hostAddress}")
if (addresses is Inet4Address){
Log.d("qtest","ip地址(Inet4Address):${addresses.hostAddress}")
}

}
}
val routes=connectivityManager.getLinkProperties(connectivityManager.activeNetwork)?.routes
if (!routes.isNullOrEmpty()){
routes?.forEach {
Log.d("qtest","网关地址信息:${it.gateway?.hostAddress}")
}
}

val dnsServer=connectivityManager.getLinkProperties(connectivityManager.activeNetwork)?.dnsServers
Log.d("qtest","dns:${dnsServer?.size}")
if (dnsServer!=null&&dnsServer.size>=2){
                Log.d("qtest","dns1:${dnsServer[0].toString()}")
Log.d("qtest","dns2:${dnsServer[1].toString()}")
}

val networkInterfaces=NetworkInterface.getNetworkInterfaces()
while (networkInterfaces.hasMoreElements()){
val networkInterface=networkInterfaces.nextElement()
if (!networkInterface.isUp&&!networkInterface.equals(networkInterface.displayName)){
continue
}
networkInterface.interfaceAddresses.forEach {
if (it.address is Inet4Address){
Log.d("qtest","子网掩码:${calcMaskByPrefixLength(it.networkPrefixLength.toInt())}")
return
}
}
}
}
}

fun calcMaskByPrefixLength(length: Int): Long {
val mask = -1 shl 32 - length
val partsNum = 4
val bitsOfPart = 8
val maskParts = IntArray(partsNum)
val selector = 0x000000ff
for (i in maskParts.indices) {
val pos = maskParts.size - 1 - i
maskParts[pos] = mask shr i * bitsOfPart and selector
}
var result = ""
result = result + maskParts[0]
for (i in 1 until maskParts.size) {
result = result + "." + maskParts[i]
}
Log.d("qtest","子网掩码:$result")
return ((maskParts[0] shl 24) + (maskParts[1] shl 16) + (maskParts[2] shl 8) + maskParts[3]).toLong()
}














posted @ 2023-12-19 14:32  Prime_T  阅读(6)  评论(0编辑  收藏  举报