Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to obtain the ip address of the connected wifi router in android programmatically?

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

like image 837
akshay1728 Avatar asked Aug 17 '12 07:08

akshay1728


2 Answers

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.

like image 115
obataku Avatar answered Sep 26 '22 02:09

obataku


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"
}
like image 27
YPL Avatar answered Sep 24 '22 02:09

YPL