IP扫描帮助 - 线程?

时间:2015-04-04 00:10:38

标签: android multithreading ping

我试图实施IP扫描程序,让我们说我有这个代码:

// Background Task: Scan network
class BackgroundScan extends AsyncTask<Void, Icmp_scan_result_params, Void> {

    // Process
    @Override
    protected Void doInBackground(Void... params) {

        // Load intervals
        long start_interval = scanner.info.get_network_bounds(false); // Start IP address converted to decimal
        long end_interval = scanner.info.get_network_bounds(true); // End IP address converted to decimal

        // Perform scan - Skip network, broadcast and gateway address:
        for (long ip_decimal=start_interval+1; ip_decimal < end_interval; ip_decimal++) {
            // Skip default gateway
            if (ip_decimal == info.ip_to_long(info.default_gateway)) {
                continue;
            }
            // Convert the IP address to string
            final String ip = info.long_to_ip(ip_decimal);
            // Start and run new thread
            new Thread(new Runnable() {
                @Override
                public void run() {

                    boolean is_reachable = scanner.icmp_scan(ip);
                    Icmp_scan_result_params _params = new Icmp_scan_result_params(ip, is_reachable);
                    publishProgress(_params);
                }
            }).start();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate (Icmp_scan_result_params... _params) {
         // ...
    }
}

此处扫描方法:

public boolean icmp_scan(String ip) {
    for (int i=0; i<4; i++) {
        // Send ping command *ROOT*
        try {
            Process p1 = Runtime.getRuntime().exec("ping -c 1 "+ip);
            int result = p1.waitFor();
            // Positive match
            if (result == 0) {
                return true;
            }
        } catch (IOException e) {
        } catch (InterruptedException e) {
        }
    }
    return false;
}

但问题是应用程序崩溃,可能是因为一次执行的线程太多(5线程左右工作正常)。什么是正确和最快的方式我如何实现这一点,以确保应用程序将始终在任何设备上顺利运行?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

为什么使用异步任务和来自doInBackground的线程? doInBackground已经在自己的主题上了。您可能甚至不需要异步任务。

您可以使用单个主题并在icmp_scan内调用run(),而threadIsNotStopped这样的标记为真。或者,如果要使用多个线程,请将icmp_scan的功能包含在实现runnable的类中,传入分区的ip地址范围,并使用ExecutorService。请参阅http://developer.android.com/reference/java/util/concurrent/ExecutorService.htmlhttp://codetheory.in/android-java-executor-framework/

当您需要更新用户界面时,可以通过以下方式执行onPostExecute

Handler uiCallback = new Handler(Looper.getMainLooper());
uiCallback.post(new Runnable() {
  @Override public void run() {
    // will run on ui thread
  }
});