关于eclipse:如何以编程方式获取android中已连接的wifi路由器的IP地址?

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

我想获取我的Android手机所连接的wifi路由器的IP地址吗?我知道我们可以使用android API来获取mac / BSSId和SSID,但是我找不到找到它的ip地址的方法吗?

我找到了用于获取拥有wifi路由器的电话的IP地址的代码

1
2
3
4
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))

但无法获得我想要的


您想要的是DhcpInfo ....

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

这将确定格式化的网关IP地址,该地址应为您要查找的地址。


由于formatIpAddress已被弃用,因此这是替代方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"
}