Fork me on GitHub

判断本网段有多少可用的IP地址

首先获取本机IP地址和网段。再使用Java执行ping命令,判断这些IP地址是否能用,把能用的打印出来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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);
List<String> ips = Collections.synchronizedList(new ArrayList<>());
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
AtomicInteger number = new AtomicInteger();
for (int i = 0; i < 255; i++) {
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 (String 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;
}
}
}

Your support will encourage me to continue to create!