| 1 |
package processing.app.helpers; |
| 2 |
|
| 3 |
import java.io.IOException; |
| 4 |
import java.net.InetAddress; |
| 5 |
import java.net.InetSocketAddress; |
| 6 |
import java.net.Socket; |
| 7 |
import java.util.Arrays; |
| 8 |
import java.util.List; |
| 9 |
|
| 10 |
public abstract class NetUtils { |
| 11 |
|
| 12 |
private static boolean isReachableByEcho(InetAddress address) { |
| 13 |
try { |
| 14 |
return address.isReachable(300); |
| 15 |
} catch (IOException e) { |
| 16 |
return false; |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
public static boolean isReachable(InetAddress address, int port) { |
| 21 |
return isReachable(address, Arrays.asList(port)); |
| 22 |
} |
| 23 |
|
| 24 |
public static boolean isReachable(InetAddress address, List<Integer> ports) { |
| 25 |
if (isReachableByEcho(address)) { |
| 26 |
return true; |
| 27 |
} |
| 28 |
|
| 29 |
boolean reachable = false; |
| 30 |
for (Integer port : ports) { |
| 31 |
reachable = reachable || isPortOpen(address, port); |
| 32 |
} |
| 33 |
|
| 34 |
return reachable; |
| 35 |
} |
| 36 |
|
| 37 |
private static boolean isPortOpen(InetAddress address, int port) { |
| 38 |
Socket socket = null; |
| 39 |
try { |
| 40 |
socket = new Socket(); |
| 41 |
socket.connect(new InetSocketAddress(address, port), 1000); |
| 42 |
return true; |
| 43 |
} catch (IOException e) { |
| 44 |
return false; |
| 45 |
} finally { |
| 46 |
if (socket != null) { |
| 47 |
try { |
| 48 |
socket.close(); |
| 49 |
} catch (IOException e) { |
| 50 |
|
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
} |