Friday, 10 May 2013

ICMP Ping through Java


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();
    }
}

2 comments: