ICMP Ping through program is often useful in many cases like testing server state, accessibility of the given host, etc.
Below is the code to ping host by executing the Ping command through Java.
public boolean pingHostByCommand(String host){
try{
String strCommand = "";
System.out.println("My OS :" + System.getProperty("os.name"));
if(System.getProperty("os.name").startsWith("Windows")) {
// construct command for Windows Operating system
strCommand = "ping -n 1 " + host;
} else {
// construct command for Linux and OSX
strCommand = "ping -c 1 " + host;
}
System.out.println("Command: " + strCommand);
// Execute the command constructed
Process myProcess = Runtime.getRuntime().exec(strCommand);
myProcess.waitFor();
if(myProcess.exitValue() == 0) {
return true;
} else {
return false;
}
} catch( Exception e ) {
e.printStackTrace();
return false;
}
}
Below is the code to ping host without using JNI or NOI. It is very reliable way to Ping the host.
public void pingHostByJavaClass(String host, int timeout){
try {
boolean isreachable = InetAddress.getByName(host).isReachable(timeout);
System.out.println(isreachable);
} catch (IOException ex) {
ex.printStackTrace();
}
}
This comment has been removed by the author.
ReplyDeletebut if i want to get ping message?
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete