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

2

10

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

Restaurateur answered 17/8, 2012 at 7:19 Comment(6)
try this soln. https://mcmap.net/q/11175/-how-to-get-ip-address-of-the-device-from-codeCarmelocarmen
what did you get using the given code? and what did you want to get?Tibold
Have you added permissions?I'm sure there's no problems in your code.Elastic
@paritybit I want to get ip address of the router so that i can connect to the other android phone which is connected to the same routerRestaurateur
@klaudo I just want a way to start it...i want a method for it so i can start coding for it..Restaurateur
@Dya bro this will give the ip address of the android device ..i want the ip address of the router to which it is connectedRestaurateur
S
13

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.

Sandlin answered 17/8, 2012 at 7:45 Comment(2)
This is great easy solution, and the main goal - it's works. But unfortunately, it does not support IPv6Daveen
its giving me the local ip addressIerna
A
4

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"
}
Amah answered 22/2, 2019 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.