How to know ip address of the router from code in android?

HotIceCream picture HotIceCream · Jan 27, 2012 · Viewed 15.7k times · Source

How can you find the IP address of the router (gateway address) from code?

WifiInfo.getIpAddress() - returns IP address of device.

In a shell command "ipconfig" does not return any value.

Here is my solution, but please let me know if there is a better way to do this:

WifiManager manager = (WifiManager)getSystemService(WIFI_SERVICE);
DhcpInfo info = manager.getDhcpInfo();
info.gateway;

Answer

Sandeep picture Sandeep · May 23, 2013

Hey this might help you: DHCPInfo

final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);

Add following rows to AndroidManifest.xml in order to access wifi functionalities:

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

As the formatIpAddress is deprecated now you can use below code

byte[] myIPAddress = BigInteger.valueOf(manager.getIpAddress()).toByteArray();
ArrayUtils.reverse(myIPAddress);
InetAddress myInetIP = InetAddress.getByAddress(myIPAddress);
String myIP = myInetIP.getHostAddress();