-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIcmpBasicOperation.java
More file actions
73 lines (49 loc) · 1.93 KB
/
Copy pathIcmpBasicOperation.java
File metadata and controls
73 lines (49 loc) · 1.93 KB
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
package icmp;
import org.icmp4j.IcmpPingRequest;
import org.icmp4j.IcmpPingResponse;
import org.icmp4j.IcmpPingUtil;
import java.util.ArrayList;
/**
* Created by yuwang on 12/13/15.
* Main class for checking if a device is reachable via ICMP ping
*/
public class IcmpBasicOperation {
private int timeout;
private int retries;
private String ipAddress;
public IcmpBasicOperation(String ipAddress, int timeout, int retries) {
if (retries <= 0) {
throw new IllegalArgumentException("retries must be higher than zero");
}
if (timeout < 1000 || timeout > 10000) {
throw new IllegalArgumentException("timeout should be between 1000 to 10000 ms");
}
this.ipAddress = ipAddress;
this.timeout = timeout;
this.retries = retries;
}
public Boolean ifReachable() {
Boolean result = true;
ArrayList<Boolean> booleen = new ArrayList<>();
try {
// request
final IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest();
request.setHost(this.ipAddress);
// repeat 4 times by default
for (int count = 0; count < this.retries; count++) {
// delegate
final IcmpPingResponse response = IcmpPingUtil.executePingRequest(request);
// log
final String formattedResponse = IcmpPingUtil.formatResponse(response);
System.out.println(String.valueOf(count) + " " + formattedResponse);
if (formattedResponse.contains("Error: Timeout reached after")) booleen.add(false);
if (!formattedResponse.contains("Error: Timeout reached after")) booleen.add(true);
Thread.sleep(this.timeout);
}
} catch (final Throwable t) {
// log
t.printStackTrace();
}
return booleen.contains(true) ? true : false;
}
}