How to ping a host in java

This example shows you how to ping a host in java.

In Java 1.5 the InetAddress class introduces an isReachable() method that can be use to ping or check if the address specified by the InetAddress is reachable.

Below is the example code of pinging a host in java:

package com.java.connect.net;
 
import java.net.InetAddress;
 
//How to ping a host in java
 
public class NetworkPingExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getLocalHost();
 
            // Reach the specified address within the timeout
            // period. If during this period the address cannot be
            // reach then the method returns false.
            boolean reachable = address.isReachable(99999);
 
            if (reachable) {
                System.out.println("The host is reachable ");
            } else {
                System.out.println("The host is not reachable ");
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output of the above example will be as:

The host is reachable