Android 在托管热点时查找设备的 ip 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21804891/
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-08-20 05:06:49  来源:igfitidea点击:

Android Find the device's ip address when it's hosting a hotspot

androidwifiip-addressandroid-wifiandroid-networking

提问by user2224350

I need to find the device's ip address when it's hosting a hotspot. I've used this code so far :

我需要在托管热点时找到设备的 IP 地址。到目前为止,我已经使用了这段代码:

//if is using Hotspot
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();
    if (intf.getName().contains("wlan")) {
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (!inetAddress.isLoopbackAddress() && (inetAddress.getAddress().length == 4)) {
                return inetAddress.getHostAddress();
            }
        }
    }
}

This works quite fine but the wifi NetworkInterfacename differs on some devices. So I have to find the device's wifi NetworkInterfacename (for its hotspot) first. How can I find this name? Or is there a better approach to find the device's ip address?

这工作得很好,但NetworkInterface某些设备上的 wifi名称不同。所以我必须首先找到设备的 wifiNetworkInterface名称(对于它的热点)。我怎样才能找到这个名字?或者是否有更好的方法来查找设备的 IP 地址?

/// Finding the right ip address by the MAC also doesn't seem to work

/// 通过 MAC 找到正确的 ip 地址似乎也不起作用

采纳答案by user2224350

I recently figured out that the WifiAP ip address is hardcoded in Android. Unless a user has changed this value manually (I think that is very uncommon) using the hardcoded value is absolutely sufficient. I think this is the best way to go. The IP address is "192.168.43.1" : https://github.com/CyanogenMod/android_frameworks_base/blob/cm-10.1/wifi/java/android/net/wifi/WifiStateMachine.java?source=c#L1299

我最近发现 WifiAP ip 地址在 Android 中是硬编码的。除非用户手动更改了这个值(我认为这很不常见),使用硬编码值是绝对足够的。我认为这是最好的方法。IP地址是“192.168.43.1”:https: //github.com/CyanogenMod/android_frameworks_base/blob/cm-10.1/wifi/java/android/net/wifi/WifiStateMachine.java?source=c#L1299

回答by flx

At first I tried to fetch the MAC address of the WiFi interface to compare it with the MAC address of each interface. But it turns out, that at least on my N4 running CM the MAC of the WiFi interface changes when turning on the Hotspot.

一开始我尝试获取WiFi接口的MAC地址与每个接口的MAC地址进行比较。但事实证明,至少在运行 CM 的 N4 上,打开热点时 WiFi 接口的 MAC 会发生变化。

So I wrote some code to walk though the list of devices to find something to identify the wifi interface. This code works perfectly on my N4:

所以我写了一些代码来遍历设备列表以找到识别wifi接口的东西。这段代码在我的 N4 上完美运行:

private String getWifiIp() throws SocketException {
    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        if (intf.isLoopback()) {
            continue;
        }
        if (intf.isVirtual()) {
            continue;
        }
        if (!intf.isUp()) {
            continue;
        }
        if (intf.isPointToPoint()) {
            continue;
        }
        if (intf.getHardwareAddress() == null) {
            continue;
        }
        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                enumIpAddr.hasMoreElements(); ) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (inetAddress.getAddress().length == 4) {
                return inetAddress.getHostAddress();
            }
        }
    }
    return null;
}

Only one single interface matches all conditions: wlan0.

只有一个接口符合所有条件:wlan0.

Possible other solution:

可能的其他解决方案:

Walk trough some most common interface names and try to find them in the list: new String[] { "wlan0", "eth0", ...];

遍历一些最常见的接口名称并尝试在列表中找到它们: new String[] { "wlan0", "eth0", ...];

回答by cafebabe1991

This can help you out.

这可以帮助你。

Making a call to the shell to ask for the network adapters and check the ones you need like in this case is wlan so follow this code

调用 shell 来请求网络适配器并检查您需要的网络适配器,在这种情况下是 wlan,因此请遵循此代码

Process p=Runtime.getRuntime().exec("ip link show | grep -o \": wlan[0-9]:\" ");

BufferedReader readCommandOutput = 
    new BufferedReader(new InputStreamReader(p.getInputStream()));

String line=null;
while((line=readCommandOutput.readLine())!=null){
    // Lines containing wlan will be returned
    // parse to get the name of that interface.
    String interface=line.split(":")[1];
    //this is the interface you need.
}

if (line==null){
    //nothing was found.
}

readCommandOutput.close();

Attached notes

附注

This image is the output of the command on the shell.Or you can use the Android Terminal Emulator from the play store in order to run this command in android shell.

此图像是命令在 shell 上的输出。或者,您可以使用 Play 商店中的 Android Terminal Emulator 在 android shell 中运行此命令。

For retrieving the ip address

用于检索 IP 地址

WifiManager wifi=(WifiManager)getSystemService(WIFI_SERVICE);
int address=wifi.getDhcpInfo().ipAddress;
Toast.makeText(this,intToIP(address),1).show();         


public String intToIP(int i) {
    return ((i & 0xFF) 
            + "." + ((i >> 8) & 0xFF)
            + "." + ((i >> 16) & 0xFF)
            + "." + ((i >> 24) & 0xFF));
 }

回答by Priyank Patel

this solution works when you want to get ip of the hotspot device on the same device but dont know how to get it on connected device (mostly the ip of server is 192.168.43.1 you can get the work done by hardcoding it)

当您想在同一设备上获取热点设备的 ip 但不知道如何在连接的设备上获取它时,此解决方案有效(大多数服务器的 ip 是 192.168.43.1,您可以通过硬编码来完成工作)

 public void serverip()

    {
     DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
            if (dhcpInfo==null){
                Toast.makeText(MainActivity.this, "No ip for server", Toast.LENGTH_SHORT).show();
            }else{

                Toast.makeText(MainActivity.this, "ip of server "+android.text.format.Formatter.formatIpAddress(dhcpInfo.gateway), Toast.LENGTH_SHORT).show();
    }


            }

回答by yrt

user2224350 said : "I recently figured out that the WifiAP ip address is hardcoded in Android."

user2224350 说:“我最近发现 WifiAP ip 地址在 Android 中是硬编码的。”

Unless a user has changed this value manually (I think that is very uncommon) using the hardcoded value is absolutely sufficient. I think this is the best way to go. The IP address is "192.168.43.1", as seen here.

除非用户手动更改了这个值(我认为这很不常见),使用硬编码值是绝对足够的。我认为这是最好的方法。IP 地址为“192.168.43.1”,如下所示

This works on my Samsung A3, and Huawei PRA-LX1, but the HTC Desires 530 returns 192.168.1.1as well.

这适用于我的三星 A3 和华为 PRA-LX1,但 HTC Desires 530 也回归192.168.1.1了。

回答by Mobility

Please replace intf.getName()with intf.getDisplayName()and then try.

请替换intf.getName()intf.getDisplayName()然后尝试。

回答by R KiranKumar

Once Try this code :

一旦尝试此代码:

public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {

                        String ip = Formatter.formatIpAddress(inetAddress.hashCode());
                        Toast.makeText(getApplicationContext(), "***** IP="+ ip, 1).show();

                        return ip;
                    }
                }
            }
        } catch (SocketException ex) {
            Toast.makeText(getApplicationContext(), "***** IP="+ex.toString(), 1).show();

        }
        return null;
    }

Write code at oncreat to check ,hotspot is Enable are not.....

在oncreat写代码检查,热点是启用不是.....

WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
        wifiManager.setWifiEnabled(true);
        wifiManager.setWifiEnabled(false);
        boolean wifiEnabled = wifiManager.isWifiEnabled();
        if (wifiEnabled) {
            Toast.makeText(getApplicationContext(),"on",Toast.LENGTH_SHORT).show();
            getLocalIpAddress();
        }else {
                Toast.makeText(getApplicationContext(),"off",Toast.LENGTH_SHORT).show();
        }