Get the default gateway programmatically using getHostAddress () from the InetAddress class

I want to get the default default gateway in Android. First I found the following solution: the IP address of the router in the code answered by @Sandeep

Then I realized formatIpAddress is deprecated. As described in the documentation:getHostAddress()

I also thought it was better since I might not need to add new permissions for my application like @Sandeep mentioned in his answer:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

I used the following solution for get default gateway, for example, the one mentioned in: How to get the default gateway via Ethernet, not Wi-Fi

public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

Default Gateway dhcp.gateway . , , getHostAddress()?

Addenda

IP- , @Sandeep, , DHCP? DhcpInfo , .

+4

Source: https://habr.com/ru/post/1617086/


All Articles