Android 获取WiFi下所有连接设备的ip

直接上代码:

WifiManager wifi_service = (WifiManager)getSystemService(WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
new Thread(new Runnable() {
            @Override
            public void run() {

                List<String> list = new ArrayList<>();
                InetAddress host;
                try
                {
                    host = InetAddress.getByName(intToIp(dhcpInfo.dns1));
                    byte[] ip = host.getAddress();
                    for(int i = 1; i <= 254; i++)
                    {
                        ip[3] = (byte) i;
                        InetAddress address = InetAddress.getByAddress(ip);
                        if(address.isReachable(100))
                        {
                            System.out.println(address + " machine is turned on and can be pinged");
                            String ipAddress = address.toString().replace("/","");
                            list.add(ipAddress);
                        }
                        else if(!address.getHostAddress().equals(address.getHostName()))
                        {
                            System.out.println(address + " machine is kNown in a DNS lookup");
                        }
                    }
                }
                catch(UnknownHostException e1)
                {
                    e1.printStackTrace();
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        }).start();

还有一种方法:

private List<String> getConnectIp() throws Exception {

        List<String> connectIpList = new ArrayList();

        Runtime runtime = Runtime.getRuntime();

        Process proc = runtime.exec("ip neigh show");

        proc.waitFor();

        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line;

        while ((line = br.readLine()) != null) {

            String[] splitted = line.split(" +");

            if (splitted != null && splitted.length >= 4) {

                String ip = splitted[0];

                connectIpList.add(ip);

            }

        }
        return connectIpList;

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容