android 如何获取连接到WiFi热点的客户端设备的详细信息?

pgky5nke  于 11个月前  发布在  Android
关注(0)|答案(5)|浏览(124)

我在我的Android应用程序中通过WiFi热点AP连接不同的设备,如何通过编程检测客户端连接和断开连接以及WiFi热点AP?Android API中是否有任何回调事件来给予有关单个设备连接或断开连接事件的信息?提前感谢。

vom3gejh

vom3gejh1#

不幸的是,没有公共的API来给予有关这方面的信息.但是你可以读/proc/net/阿普文件,看到连接到你的接入点的客户端。
/proc/net/阿普文件有6个字段:IP地址硬件类型标志硬件地址掩码设备
问题是当客户端断开连接时,因为它不会从文件中消失。解决方案可能是对每个客户端执行 ping 并等待响应,但对我来说这不是一个好的解决方案,因为有些客户端不响应 ping。如果你喜欢这个解决方案,请在GitHub上查看这个项目--> https://github.com/nickrussler/Android-Wifi-Hotspot-Manager-Class/tree/master/src/com/whitebyte
我所做的是:读取/proc/net/阿普并检查 FLAGS 字段,当值为0x 2时,工作站已连接,0x 0已断开连接,但要刷新此字段,我需要不时清除ARP缓存,我用以下命令做到了这一点:ip neigh flush all

s8vozzvw

s8vozzvw2#

这种方法适用于我,但这是检测只有版本4.0及以上;它是无法找到与热点连接的版本2.2或2.3的设备.

public void getClientList() {
    int macCount = 0;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");
            if (splitted != null ) {
                // Basic sanity check
                String mac = splitted[3];
                System.out.println("Mac : Outside If "+ mac );
                if (mac.matches("..:..:..:..:..:..")) {
                    macCount++;
                   /* ClientList.add("Client(" + macCount + ")");
                    IpAddr.add(splitted[0]);
                    HWAddr.add(splitted[3]);
                    Device.add(splitted[5]);*/
                    System.out.println("Mac : "+ mac + " IP Address : "+splitted[0] );
                    System.out.println("Mac_Count  " + macCount + " MAC_ADDRESS  "+ mac);
                Toast.makeText(
                        getApplicationContext(),
                        "Mac_Count  " + macCount + "   MAC_ADDRESS  "
                                + mac, Toast.LENGTH_SHORT).show();

                }
               /* for (int i = 0; i < splitted.length; i++)
                    System.out.println("Addressssssss     "+ splitted[i]);*/

            }
        }
    } catch(Exception e) {

    }               
}

字符串

mkh04yzy

mkh04yzy3#

Android 10限制了访问/proc/net目录的权限,所以上面的一些解决方案已经不可行了,但是'ip'命令仍然可用

private fun getARPIps(): List<Pair<String, String>> {
    val result = mutableListOf<Pair<String, String>>()
    try {
//        val args = listOf("ip", "neigh")
//        val cmd = ProcessBuilder(args)
//        val process: Process = cmd.start()
      val process = Runtime.getRuntime().exec("ip neigh")
        val reader = BufferedReader(InputStreamReader(process.inputStream))
        reader.forEachLine {
            if (!it.contains("FAILED")) {
                val split = it.split("\\s+".toRegex())
                if (split.size > 4 && split[0].matches(Regex("([0-9]{1,3}\\.){3}[0-9]{1,3}"))) {
                    result.add(Pair(split[0], split[4]))
                }
            }
        }
        val errReader = BufferedReader(InputStreamReader(process.errorStream))
        errReader.forEachLine {
            Log.e(TAG, it)
            // post the error message to server
        }
        reader.close()
        errReader.close()
        process.destroy()
    } catch (e: Exception){
        e.printStackTrace()
        // post the error message to server
    }
    return result
}

字符串

alen0pnh

alen0pnh4#

@SuppressWarnings("ConstantConditions")
public static String getClientMacByIP(String ip)
{
    String res = "";
    if (ip == null)
        return res;

    String flushCmd = "sh ip -s -s neigh flush all";
    Runtime runtime = Runtime.getRuntime();
    try
    {
        runtime.exec(flushCmd,null,new File("/proc/net"));
    }

    BufferedReader br;
    try
    {
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null)
        {
            String[] sp = line.split(" +");
            if (sp.length >= 4 && ip.equals(sp[0]))
            {Assistance.Log(sp[0]+sp[2]+sp[3],ALERT_STATES.ALERT_STATE_LOG);
                String mac = sp[3];
                if (mac.matches("..:..:..:..:..:..") && sp[2].equals("0x2"))
                {
                    res = mac;
                    break;
                }
            }
        }

        br.close();
    }
    catch (Exception e)
    {}

    return res;
}

字符串
//--------------------------------------------------------

@SuppressWarnings("ConstantConditions")
public static String getClientIPByMac(String mac)
{
    String res = "";
    if (mac == null)
        return res;

    String flushCmd = "sh ip -s -s neigh flush all";
    Runtime runtime = Runtime.getRuntime();
    try
    {
        runtime.exec(flushCmd,null,new File("/proc/net"));
    }

    BufferedReader br;
    try
    {
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null)
        {
            String[] sp = line.split(" +");
            if (sp.length >= 4 && mac.equals(sp[3]))
            {
                String ip = sp[0];
                if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}") && sp[2].equals("0x2"))
                {
                    res = ip;
                    break;
                }
            }
        }

        br.close();
    }
    catch (Exception e)
    {}

    return res;
}

dphi5xsq

dphi5xsq5#

您可以使用BroadcastReciever“android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED”来检测客户端连接。在您的AndroidManifest中:

<receiver
            android:name=".WiFiConnectionReciever"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED" />
            </intent-filter>
        </receiver>

字符串
在你的活动中

IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.net.wifi.WIFI_HOTSPOT_CLIENTS_CHANGED");
                        rcv = new WiFiConnectionReciever();
                        registerReceiver(rcv,
                                mIntentFilter);

相关问题