【发布时间】: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