判斷本網段有多少可用的ip地址


為了提高效率,使用多線程方式同時ping。 但是如果開啟255個線程,又會因為網絡端口太擁擠,會被判定為無法ping通。
所以本例使用java自帶線程池,線程池的連接數還不能太大,啟動了15個線程。 

等待所有的線程結束后打印出ping通了的ip地址。

 

 

package AtomicInteger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
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;
import java.util.concurrent.atomic.AtomicInteger;

public class TestSocket {

public static void main(String[] args) throws IOException, InterruptedException {
InetAddress host = InetAddress.getLocalHost();
String ip = host.getHostAddress();
String ipRange = ip.substring(0, ip.lastIndexOf('.'));
System.out.println("本機ip地址:" + ip);
System.out.println("網段是: " + ipRange);

final List<Object> ips = Collections.synchronizedList(new ArrayList<>());
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
final AtomicInteger number = new AtomicInteger();
for (int i = 0; i < 255; i++) {
final String testIP = ipRange + "." + (i + 1);
threadPool.execute(new Runnable() {
@Override
public void run() {
boolean reachable = isReachable(testIP);
if (reachable)
// System.out.println("找到可連接的ip地址:" + testIP);
ips.add(testIP);

synchronized (number) {
System.out.println("已經完成:" + number.incrementAndGet() + " 個 ip 測試");
}
}

});

}

// 等待所有線程結束的時候,就關閉線程池
threadPool.shutdown();
//等待線程池關閉,但是最多等待1個小時
if (threadPool.awaitTermination(1, TimeUnit.HOURS)) {
System.out.println("如下ip地址可以連接");
for (Object theip : ips) {
System.out.println(theip);
}
System.out.println("總共有:" + ips.size() + " 個地址");

}
}

private static boolean isReachable(String ip) {
try {
boolean reachable = false;

Process p = Runtime.getRuntime().exec("ping -n 1 " + ip);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
if (line.length() != 0)
sb.append(line + "\r\n");
}

//當有TTL出現的時候,就表示連通了
reachable = sb.toString().contains("TTL");
br.close();
return reachable;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM