Android, detect local IP and subnet mask for WiFi, both while tethering and connected to access point

倾然丶 夕夏残阳落幕 提交于 2019-12-03 20:16:18

Best solution I found at the moment:

It baffles me how info/interface about tethering is so cumbersome/hidden to get, and yet not taken into consideration when you get info from WifiManager, or ConnectivityManager for the Wifi type: it all works only when NOT in tethering. I'm actually lost to that branch of investigation.

Best solution I found at the moment is using standard Java NetworkInterface.getNetworkInterfaces(), instead of any Android API.

Experimentally, Android seems smart enough to set to null broadcast for network interfaces to the external mobile network. It actually makes lot of sense since Android silently drop UDP broadcasts involving external mobile network.

    // This works both in tethering and when connected to an Access Point

    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

    while (interfaces.hasMoreElements()) 
    {
        NetworkInterface networkInterface = interfaces.nextElement();

        if (networkInterface.isLoopback())
            continue; // Don't want to broadcast to the loopback interface

        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) 
        {
                InetAddress broadcast = interfaceAddress.getBroadcast();

                // InetAddress ip = interfaceAddress.getAddress();                  
                // interfaceAddress.getNetworkPrefixLength() is another way to express subnet mask

                // Android seems smart enough to set to null broadcast to
                //  the external mobile network. It makes sense since Android
                //  silently drop UDP broadcasts involving external mobile network.
                if (broadcast == null)
                    continue;

                ... // Use the broadcast                
        }
    }

As for subnet mask, the result from getNetworkPrefixLength() can be coerced into a subnet mask. I used getBroadcast() directly since that was my ultimate goal.

No special permissions seem to be needed for this code (no ACCESS_WIFI_STATE nor NETWORK, just INTERNET).

Primary reference for the code snippet: http://enigma2eureka.blogspot.it/2009/08/finding-your-ip-v4-broadcast-address.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!