I want to obtain the ip address of the the wifi router to which my android phone is connected? I know that we can get the mac/BSSId and SSID by using the android APIS but I don't find the way to find the way to find the ip address of it?
I found the code for obtaining the ip address of phone owns wifi router
WifiManager myWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
int ipAddress = myWifiInfo.getIpAddress();
System.out.println("WiFi address is " + android.text.format.Formatter.formatIpAddress(ipAddress))
but failed to get what I want
What you likely want is DhcpInfo
:
final WifiManager manager = (WifiManager) super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.gateway);
This will yield the (formatted) gateway IP address, which should be what you're looking for.
Since formatIpAddress is Deprecatted, here is the alternative :
public String getHotspotAdress(){
final WifiManager manager = (WifiManager)super.getSystemService(WIFI_SERVICE);
final DhcpInfo dhcp = manager.getDhcpInfo();
int ipAddress = dhcp.gateway;
ipAddress = (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) ?
Integer.reverseBytes(ipAddress) : ipAddress;
byte[] ipAddressByte = BigInteger.valueOf(ipAddress).toByteArray();
try {
InetAddress myAddr = InetAddress.getByAddress(ipAddressByte);
return myAddr.getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("Wifi Class", "Error getting Hotspot IP address ", e);
}
return "null"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With