ping
命令空格问题,正确如下:
Process p = Runtime.getRuntime().exec("ping -n 1 "+ip);//空格引发的灾难
- 线程池关闭方式有误,只使用了
threadPool.shutdown()
进行关闭,正确如下:
// 等待所有线程结束的时候,就关闭线程池
threadPool.shutdown();
System.out.println("终于找完了,可以ping通ip如下:");
//等待线程池关闭,但是最多等待1个小时
if (threadPool.awaitTermination(1, TimeUnit.HOURS)) {
for (String theip : slist) {
System.out.println(theip);
}
}
该图片来自于https://blog.csdn.net/weixin_43207056/article/details/103566392
完整实现如下:
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestIp {
public static void main(String[] args) throws IOException,InterruptedException {
// 创建线程池
ThreadPoolExecutor threadPool= new ThreadPoolExecutor(200, 200, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
//保证List线程安全
List<String> slist = Collections.synchronizedList(new ArrayList<>());
for(int i = 0; i<255; i++) {
String s = "192.168.1."+i;
threadPool.execute(new Runnable(){
public void run() {
if(isPing(s))
slist.add(s);
}
});
}
// 等待所有线程结束的时候,就关闭线程池
threadPool.shutdown();
System.out.println("终于找完了,可以ping通ip如下:");
//等待线程池关闭,但是最多等待1个小时
if (threadPool.awaitTermination(1, TimeUnit.HOURS)) {
for (String theip : slist) {
System.out.println(theip);
}
}
}
//判断一个ip是否能够ping通
private static boolean isPing(String ip){
try {
boolean reachable =false;
StringBuilder sb = new StringBuilder();
Process p = Runtime.getRuntime().exec("ping -n 1 "+ip);//空格引发的灾难
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line=br.readLine()) != null) {
if(line.length() != 0)
sb.append(line+"\r\n");
}
reachable = sb.toString().contains("TTL");
br.close();
return reachable;
}catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}