From 4c6758f764adf9962b4508dd0091bf67134b6918 Mon Sep 17 00:00:00 2001 From: Anshuman Jadiya Date: Thu, 9 Oct 2025 17:59:09 +0530 Subject: [PATCH] Implement PingCommand to execute ping on hostname This class executes a ping command to a specified hostname and prints the output. --- .../java/com/mycmd/commands/PingCommand.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/main/java/com/mycmd/commands/PingCommand.java diff --git a/src/main/java/com/mycmd/commands/PingCommand.java b/src/main/java/com/mycmd/commands/PingCommand.java new file mode 100644 index 0000000..6b87d85 --- /dev/null +++ b/src/main/java/com/mycmd/commands/PingCommand.java @@ -0,0 +1,36 @@ +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class PingCommand { + public static void main(String[] args) { + if (args.length < 1) { + System.out.println("Usage: java PingCommand "); + return; + } + + String host = args[0]; + + try { + // Run the ping command + Process process = Runtime.getRuntime().exec("cmd.exe /c ping " + host); + + // Read the output of the ping command + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getInputStream()) + ); + + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + + // Wait for the process to finish + int exitCode = process.waitFor(); + System.out.println("Ping command exited with code: " + exitCode); + + } catch (Exception e) { + System.out.println("Error executing ping command."); + e.printStackTrace(); + } + } +}