在安卓开发文档中发现有IpConfiguration这个表示网络 IP 配置的类,但是不知道为什么不能使用。
private val manager: ConnectivityManager
get() = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
/**
* 以太网是否连接
*/
private fun connect(): Boolean {
val info = manager.activeNetworkInfo
if (info?.type != ConnectivityManager.TYPE_ETHERNET) {
logger.debug { "以太网未连接,请重试" }
return false
}
if (!info.isAvailable) {
logger.debug { "以太网不可用,请重试" }
return false
}
logger.debug { "以太网连接成功" }
return true
}
/**
* 获取以太网ip地址
*/
private fun ipAddress() {
try {
val etherInterface = NetworkInterface.getNetworkInterfaces()
while (etherInterface.hasMoreElements()) {//判断是否有数据
val element = etherInterface.nextElement()
if (!element.isUp) {
continue
}
if (element.displayName != "eth0") {
continue
}
val addresses = element.inetAddresses
while (addresses.hasMoreElements()) {
val subElement = addresses.nextElement()
if (subElement.isSiteLocalAddress) {
val ip = subElement.hostAddress
logger.debug { "ip地址$ip" }
}
}
}
} catch (e: Exception) {
logger.error(e) { "" }
}
}