Search code examples
androidwifiip-addressandroid-wifiandroid-networking

Android Find the device's ip address when it's hosting a hotspot


I need to find the device's ip address when it's hosting a hotspot. I've used this code so far :

//if is using Hotspot
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();
    if (intf.getName().contains("wlan")) {
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                return inetAddress.getHostAddress();
            }
        }
    }
}

This works quite fine but the wifi NetworkInterface name differs on some devices. So I have to find the device's wifi NetworkInterface name (for its hotspot) first. How can I find this name? Or is there a better approach to find the device's ip address?

/// Finding the right ip address by the MAC also doesn't seem to work


Solution

  • I recently figured out that the WifiAP ip address is hardcoded in Android. Unless a user has changed this value manually (I think that is very uncommon) using the hardcoded value is absolutely sufficient. I think this is the best way to go. The IP address is "192.168.43.1" : https://github.com/CyanogenMod/android_frameworks_base/blob/cm-10.1/wifi/java/android/net/wifi/WifiStateMachine.java?source=c#L1299