Skip to content

Instantly share code, notes, and snippets.

@madan712
Last active December 19, 2023 06:57
Show Gist options
  • Select an option

  • Save madan712/4509039 to your computer and use it in GitHub Desktop.

Select an option

Save madan712/4509039 to your computer and use it in GitHub Desktop.
Java program to ping an IP address
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PingIP {
public static void runSystemCommand(String command) {
try {
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String ip = "google.com";
runSystemCommand("ping " + ip);
}
}
@fidobyigero

fidobyigero commented Jan 20, 2018

Copy link
Copy Markdown

Awesome!
I struggled alot with NetworkInterfaces but couldn't help.
Thanks so much, it works fine.

@ArielMannes

Copy link
Copy Markdown

thanks !

@f5killer

f5killer commented Jun 6, 2018

Copy link
Copy Markdown

Hi JavaExpert, I am new member in this group. I would like to add bulk ping, which will take from file and generate output in CSV format if 3 consecutive ping successful. I am sure you guys will help me in writing program. Appreciate your help

@nguyenlinhnttu

Copy link
Copy Markdown

@eandresen You can try p.destroy(); to stop ping.

@yudistira000

Copy link
Copy Markdown

how to use that code in java jframe?

@auto-1

auto-1 commented Feb 22, 2020

Copy link
Copy Markdown

how to use that code in java jframe?

Exact same method, you'd just need to handle an event that triggers it and obviously the response. Let me know if you need more info!

@auto-1

auto-1 commented Feb 22, 2020

Copy link
Copy Markdown

This works fine on Mac OS, however is there an additional command that needs to be called for Windows systems? Seems to fail on Windows.

@xtrecoolx

Copy link
Copy Markdown

I would do it in a different way:

public static void isReachable(String address) {
        try {
            InetAddress inetAddress = InetAddress.getByName(address);
            boolean isReachable = inetAddress.isReachable(5000);
            System.out.printf("Is the address [%s] reachable? -%s\n", address, isReachable ? "Yes" : "No");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

This is ICMP way. Unfortunately, it is not always available.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment