Android: WifiInfo.getIpAddress() deprecated

Viewed 588

API 31 deprecated getIpAddress() Need help getting the address from the callback implementation

val networkCallback = object : ConnectivityManager.NetworkCallback() {

    override fun onAvailable(network: Network) {}


    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        val wifiInfo = networkCapabilities.transportInfo as? WifiInfo
    }

    override fun onLinkPropertiesChanged(network: Network, linkProperties: LinkProperties) {
        super.onLinkPropertiesChanged(network, linkProperties)
        // val ipV4Address = ?

    }
};

2 Answers

for deprecated method you can read afficial android Documents, as documnet syas :

This method was deprecated in API level 31. Use the methods on LinkProperties which can be obtained either via NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties) or ConnectivityManager#getLinkProperties(Network).

so by this method that i have added here you can obtain all of ip address:

   private fun getIpAddress() {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE)
     if (connectivityManager is ConnectivityManager) {
        var link:LinkProperties =  connectivityManager.getLinkProperties(connectivityManager.activeNetwork) as LinkProperties
         Log.e("NETWOOOOOOOOOOOORK", link.linkAddresses.toString())
    }

}

Notice: link.linkAddresses method may return array of addresses

For getting ip address (like 192.168.1.123) on Wifi network:

fun Context.getConnectivityManager() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

fun getIpAddress(context: Context) = with(context.getConnectivityManager()) {
    getLinkProperties(activeNetwork)!!.linkAddresses[1].address.hostAddress!!
}
Related