Ping an IP address or DN in java

Ping an ip address host in java

Ping command allow us to test the reachability of a host on an Internet Protocol (IP) network.

import java.net.InetAddress;

public class PingHost {

    public static void main(String[] args){
        String ipAddress = "domain-name.com";
        // or using ip address "192.168.1.1";
        try {
            InetAddress inetAddress = InetAddress.getByName(ipAddress);
            int timeOut = 1000;
            
            // Ping the ip address
            if(inetAddress.isReachable(timeOut)) {
                System.out.println("The " + ipAddress + " is reachable");
            }else{
                System.out.println("The " + ipAddress + " is not reachable");
            }
        }catch (Exception e) {
            System.out.println(e);
        }

    }