Get Default Gateway programmatically using getHostAddress() from InetAddress class
Asked Answered
F

0

7

I want to get Default gateway in Android programmatically. I found following solution first: IP address of router in code answered by @Sandeep

Then I realised formatIpAddress is deprecated. As documentation described : We can getHostAddress()

I also thought, it is better since I may not need to add new permissions to my app as @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 following solution to get default gateway as for instance mentioned in : How to get default gateway using Ethernet, not wifi

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;
    }

This solution will not return Default Gateway as dhcp.gateway provided for me. But then how can I get default gateway as documentation mentioned by using getHostAddress() ?

Addenda:

As it is mentioned in the comment under IP address of router in code answered by @Sandeep, what if I disabled DHCP? then DhcpInfo will not work as I expected.

Facile answered 23/11, 2015 at 15:12 Comment(2)
Did you find any solution to this? I am struggling to find a way of determining the gateway without DHCP.Discount
@EmilS. This is an old question but as far as I remember, there were no solution.Facile

© 2022 - 2024 — McMap. All rights reserved.