I want to check which IP(s) is/are available in a segment.
public class Test {
static volatile int cnt;
public static void main(String[] s) throws InterruptedException{
int i;
for(i=1;i<256;i++){
PING ping = new PING(i);
Thread t = new Thread(ping);
t.start();
}
Thread.sleep(200);
System.out.println("\ncnt: "+cnt);
}
static class PING implements Runnable{
private int i;
private String ip = "172.20.1.";
private String host;
PING(int i){
this.i = i;
}
public void run() {
host = ip + i;
try {
if(InetAddress.getByName(host).isReachable(200)){
cnt++;
System.out.print(i+", ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I know there are 7 IPs available and the expected result is:
1, 2, 24, 79, 81, 254, 60,
cnt: 7
However, I got 5 or 6 IPs more frequently than 7 during my test, and sometimes I got below result(6 IPs but cnt
is 5):
24, 79, 81, 2, 1, 60,
cnt: 5
Can anyone tell me the reason? Thanks in advance.