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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12001449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 18:49:20  来源:igfitidea点击:

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

androideclipseip-addressandroid-wifiwifimanager

提问by akshay1728

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?

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

I found the code for obtaining the ip address of phone owns wifi router

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

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

但未能得到我想要的

回答by oldrinb

What you want is DhcpInfo....

你要的是DhcpInfo……

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

This will determine the formatted gateway IP address, which should be what you're looking for.

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

回答by YPL

Since formatIpAddress is Deprecatted, here is the alternative :

由于 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"
}