DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Roger has posted 34 posts at DZone. View Full User Profile

How To Call Ping From Java

03.25.2009
| 7742 views |
  • submit to reddit
        // Java's socket class is too high-level to make an ICMP call (which ping relies on),
// and IntetAddress.getByName().isReachable() relies on Port 7 (the "echo" port) being
// open, which it never is in a properly secured server. So we have to call ping by
// executing it externally, which is what this code does...

System.out.println("Testing ping...");
try {
	Process ping = Runtime.getRuntime().exec("ping " + host);
	BufferedReader br = new BufferedReader(new InputStreamReader(ping.getInputStream()));
	StringBuilder sb = new StringBuilder();
	String line;
	while ((line = br.readLine()) != null) {
		sb.append(line);
		sb.append("\n");
	}
	System.out.print(sb.toString());
	
} catch (IOException e) {
	e.printStackTrace();
}