Reputation: 5167
I'm wanting to use Java to check if a server that's in a state of booting up is reachable yet via SSH (port 22). Currently, I'm just looping using the isReachable
method like so ...
reachable = InetAddress.getByName(host).isReachable(timeout);
But this of course doesn't specifically check SSH port 22, so my Java application may jump the gun and try to SSH into the host when it's "reachable" but not necessarily via SSH. Any recommendations for how best to check if a server is ready to be SSH'ed into?
Upvotes: 0
Views: 509
Reputation: 3759
In order to specifically check for port 22, you could use standard Java Sockets, e.g.:
Socket socket = null;
boolean reaching = false;
try {
socket = new Socket("yourserver.com", 22);
reaching = true;
}catch(Exception e){
reaching = false;
}finally{
if(socket != null){
try {
socket.close();
}catch(IOException e){}
}
}
System.out.println(reaching);
In order to avoid unpleasant blocking, you could also set a timeout:
try {
int timeout = 3000; // timeout in ms
socket = new Socket();
socket.connect(new InetSocketAddress("yourserver.com",22), timeout);
reaching = true;
} catch(Exception e) {
reaching = false;
}
Upvotes: 1