Find ip addresses connected to the android hotspot from java code

后端 未结 1 598
春和景丽
春和景丽 2021-01-23 10:36

I am writing a program that is using an android phone as a remote control via TCP/IP. The phone hosts a hotspot network that the devices connect to by knowing the SSID and passw

相关标签:
1条回答
  • 2021-01-23 11:03

    You can get connected devices from Hotspot from following snippet :

        public void getListOfConnectedDevice() {
        Thread thread = new Thread(new Runnable() {
    
            @Override
            public void run() {
                BufferedReader br = null;
                boolean isFirstLine = true;
    
                try {
                    br = new BufferedReader(new FileReader("/proc/net/arp"));
                    String line;
    
                    while ((line = br.readLine()) != null) {
                        if (isFirstLine) {
                            isFirstLine = false;
                            continue;
                        }
    
                        String[] splitted = line.split(" +");
    
                        if (splitted != null && splitted.length >= 4) {
    
                            String ipAddress = splitted[0];
                            String macAddress = splitted[3];
    
                            boolean isReachable = InetAddress.getByName(
                                    splitted[0]).isReachable(500);  // this is network call so we cant do that on UI thread, so i take background thread.
                            if (isReachable) {
                                Log.d("Device Information", ipAddress + " : "
                                        + macAddress);
                            }
    
                        }
    
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }
    
    0 讨论(0)
提交回复
热议问题