8

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

我找到了获取手机ip地址的代码拥有wifi路由器

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))

但未能得到我想要的

4

2 回答 2

12

您可能想要的是DhcpInfo

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

这将产生(格式化的)网关 IP 地址,这应该是您正在寻找的。

于 2012-08-17T07:45:15.303 回答
4

由于 formatIpAddress 已被弃用,这里是替代方案:

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"
}
于 2019-02-22T10:40:01.057 回答