2013-07-19 15:17:27 +02:00
|
|
|
package processing.app.helpers;
|
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.net.InetAddress;
|
|
|
|
import java.net.InetSocketAddress;
|
|
|
|
import java.net.Socket;
|
2015-02-19 09:34:32 +01:00
|
|
|
import java.util.Arrays;
|
|
|
|
import java.util.List;
|
2013-07-19 15:17:27 +02:00
|
|
|
|
|
|
|
public abstract class NetUtils {
|
|
|
|
|
2015-02-19 09:34:32 +01:00
|
|
|
private static boolean isReachableByEcho(InetAddress address) {
|
|
|
|
try {
|
2015-03-24 12:50:26 +01:00
|
|
|
return address.isReachable(300);
|
2015-02-19 09:34:32 +01:00
|
|
|
} catch (IOException e) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-07-22 10:06:21 +02:00
|
|
|
public static boolean isReachable(InetAddress address, int port) {
|
2015-02-19 09:34:32 +01:00
|
|
|
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) {
|
2013-07-19 15:17:27 +02:00
|
|
|
Socket socket = null;
|
|
|
|
try {
|
|
|
|
socket = new Socket();
|
2015-03-24 12:50:26 +01:00
|
|
|
socket.connect(new InetSocketAddress(address, port), 1000);
|
2013-07-19 15:17:27 +02:00
|
|
|
return true;
|
|
|
|
} catch (IOException e) {
|
|
|
|
return false;
|
|
|
|
} finally {
|
2015-05-22 09:21:07 +02:00
|
|
|
if (socket != null) {
|
|
|
|
try {
|
|
|
|
socket.close();
|
|
|
|
} catch (IOException e) {
|
|
|
|
// noop
|
|
|
|
}
|
|
|
|
}
|
2013-07-19 15:17:27 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|