【问题标题】:IP scan help - threads?IP 扫描帮助 - 线程?
【发布时间】:2015-04-04 00:10:37
【问题描述】:

我正在尝试实现一个 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 个线程可以正常工作)。什么是正确和最快的方法我该如何实现这一点,以确保应用程序将始终在任何设备上顺利运行?感谢您的帮助!

【问题讨论】:

    标签: android multithreading ping


    【解决方案1】:

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

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

    当您需要更新 UI 时,您可以通过以下方式进行onPostExecute

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      • 2011-12-07
      • 1970-01-01
      • 2014-10-01
      相关资源
      最近更新 更多