i am trying to ping remote Linux server using java, whenever i will get an acknowledgment from server i am printing "connected", but whenever the Linux server is not connected with internet, it has to show "disconnected"
I have tried to print disconnected, whenever i don't get any acknowledgment from Linux server. but i couldn't able to print it.
public class JavaLinuxConnection {
public static void main(String[] args) {
try {
Properties config = new Properties();
config.put(LinuxCredentials.STRICT_HOST_KEY_CHECKING, LinuxCredentials.HOST_KEY_VALUE);
JSch jsch = new JSch();
// Create a JSch session to connect to the server
Session session = jsch.getSession(LinuxCredentials.USERNAME, LinuxCredentials.HOST, LinuxCredentials.PORT);
session.setPassword(LinuxCredentials.PASS_WORD);
session.setConfig(config);
// Establish the connection
session.connect();
System.out.println("Connected...");
ChannelExec channel = (ChannelExec) session.openChannel(LinuxCredentials.EXEC);
channel.setCommand(LinuxCredentials.CMD);
channel.setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) { // --> I am getting error from here as "ping: sendmsg: Network is unreachable", whenever network isnt there.
System.out.print(new Timestamp(new Date().getTime()) + "--");
if(line.equalsIgnoreCase("ping: sendmsg: Network is unreachable")) {
System.out.println("Disconnected");
}else {
System.out.println("Connected");
}
if (channel.isClosed()) {
System.out.println("Exit Status: " + channel.getExitStatus());
break;
}
Thread.sleep(1000);
}
channel.disconnect();
session.disconnect();
System.out.println("DONE!!!");
} catch (Exception e) {
e.getStackTrace();
}
}
}
2019-09-06 19:19:38.063--Connected ping: sendmsg: Network is unreachable // Instead of this it should be printed as disconnected