Interview Questions

Java - Ping Host or Ip Address

In this article lets discuss about how to ping a host using java.

Consider a scenario where you need to determine whether a host is reachable from your machine or not. You can easily find it by using ping command in Windows or ipconfig in Linux systems. But what if this is part of your requirement in your application project. It can be easily done using java.net package available as a part of java api.

Consider the following program which pings a host.

PingPoller.java

package in.techdive.java;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class PingPoller
{
    public static void main(String[] args)
    {
        System.out.println("Ping Poller Starts...");

        String ipAddress = "localhost";

        try
        {
            InetAddress inet = InetAddress.getByName(ipAddress);
            System.out.println("Sending Ping Request to " + ipAddress);

            boolean status = inet.isReachable(5000); //Timeout = 5000 milli seconds

            if (status)
            {
                System.out.println("Status : Host is reachable");
            }
            else
            {
                System.out.println("Status : Host is not reachable");
            }
        }
        catch (UnknownHostException e)
        {
            System.err.println("Host does not exists");
        }
        catch (IOException e)
        {
            System.err.println("Error in reaching the Host");
        }
    }
}

Here is the sample output.

Output

Ping Poller Starts...
Sending Ping Request to localhost
Status : Host is reachable

In this way any host can be pinged from a java program.