As an assignment I have to find all the alive computers on a LAN. For which I am using isReachable
function of InetAddress
class. But problem is
Here is the code which is platform independent, but requires information about any open port on the other machine (which we have most of the time).
private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
// Any Open port on other machine
// openPort = 22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
try {
try (Socket soc = new Socket()) {
soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
}
return true;
} catch (IOException ex) {
return false;
}
}
I found interesting solution. If you can't run your aplication as root, you may set raw socket capability on java:
sudo setcap cap_net_raw=ep /usr/lib/jvm/jdk/bin/java
And then ICMP protocol will be used istead of echo request on 7 TCP port.
Here are some details on why isReachable() might not always work as expected
The correct way for you is to use the ICMP protocol. This is what ping uses internatlly, I believe. Here is an example that get you started.