简体   繁体   中英

How to discover host in a WiFi network in Android (JAVA)

I'm developing an Android application, I have to discover each hosts in a WiFi network, I have implemented a function that "ping" all IP address between 1 and 255 of a certain network.

This solution it work perfectly, but there is a problem, the execution time.. Every time that i start my application I wait about 256 second, it too long, i can't wait this time.

This is my source code (i found this code on Stack, i modified the code to work in my condition):

public class ScanNetwork {

    ArrayList < String > hosts;

    int i;
    boolean finish = false;
    public ArrayList < String > ScanNetwork(String ipAddress) {

        hosts = new ArrayList < String > ();
        final String subnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));

        for (i = 0; i < 256; i++) {
            String currentHost = subnet + "." + i;
            Process p1 = null;
            int returnVal = 0;
            try {
                p1 = Runtime.getRuntime().exec("ping -w 50 -c 1 " + currentHost);
                returnVal = p1.waitFor();
            } catch (IOException e) {
                System.out.println("Log: " + e.toString());
            } catch (InterruptedException e) {
                System.out.println("Log: " + e.toString());
            }

            boolean reachable = (returnVal == 0);
            if (reachable) {

                if (!hosts.contains(currentHost)) {
                    hosts.add(currentHost);
                    System.out.println(currentHost);

                }
            }
        }
        return hosts;
    }
}

This source code is perfect but the execution time is excessive, there are other way to obtain all the host in the network ?

How i can solve this problem ?

The problem I see is that you are doing all the pings sequentially - the loop is spending most of its time waiting for replies. Try starting up a few AsyncTasks, each of which has an assigned range of addresses to search, and let them work in parallel.

Note that for a typical 192.168.1.x network, ".0" (all 0 bits) ".255" (all 1 bits) will not correspond to a host and doesn't need checking.

Also don't forget that not everybody responds to a ping (this is more likely in a corporate network, less so at home)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM