How to Implement Ping in Java

In Java, the ping functionality can be implemented by calling the ping command provided by the operating system using system commands. Here is an example code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PingExample {

    public static void main(String[] args) {
        String ipAddress = "127.0.0.1";

        try {
            Process process = Runtime.getRuntime().exec("ping " + ipAddress);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            int exitValue = process.waitFor();
            if (exitValue == 0) {
                System.out.println("Ping successful");
            } else {
                System.out.println("Ping failed");
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In the code above, we execute the ping command using Runtime.getRuntime().exec(“ping ” + ipAddress), then we read the output of the ping command and print it out. Finally, we use the process.waitFor() method to get the exit value of the ping command. A return value of 0 indicates a successful ping, while any other value indicates a failed ping.

Please be aware that there is a certain security risk in executing system commands, so input parameters should be handled with caution.

bannerAds