OneCompiler

PRAVA-PING O1

1632

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

public class PingProgram {

public static void pingHost(String host, int count, int timeout) {
    System.out.println("Pinging " + host + " with " + count + " attempts:\n");

    for (int i = 1; i <= count; i++) {
        try {
            InetAddress inet = InetAddress.getByName(host);
            long startTime = System.currentTimeMillis();
            boolean isReachable = inet.isReachable(timeout);
            long endTime = System.currentTimeMillis();
            
            if (isReachable) {
                System.out.println("Request " + i + ": Reply from " + host + " - Time=" + (endTime - startTime) + "ms");
            } else {
                System.out.println("Request " + i + ": Timed out");
            }
        } catch (IOException e) {
            System.out.println("Request " + i + ": Ping failed due to error - " + e.getMessage());
        }
    }
}

public static void main(String[] args) {
    String host = "8.8.8.8"; // Example: Google's public DNS server
    int count = 4;            // Number of ping attempts
    int timeout = 1000;       // Timeout in milliseconds

    pingHost(host, count, timeout);
}

}