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.