-
-
Notifications
You must be signed in to change notification settings - Fork 7k
/
Copy pathNetUtils.java
55 lines (47 loc) · 1.24 KB
/
NetUtils.java
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
package processing.app.helpers;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
public abstract class NetUtils {
private static boolean isReachableByEcho(InetAddress address) {
try {
return address.isReachable(300);
} catch (IOException e) {
return false;
}
}
public static boolean isReachable(InetAddress address, int port) {
return isReachable(address, Arrays.asList(port));
}
public static boolean isReachable(InetAddress address, List<Integer> ports) {
if (isReachableByEcho(address)) {
return true;
}
boolean reachable = false;
for (Integer port : ports) {
reachable = reachable || isPortOpen(address, port);
}
return reachable;
}
private static boolean isPortOpen(InetAddress address, int port) {
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(address, port), 1000);
return true;
} catch (IOException e) {
return false;
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// noop
}
}
}
}
}