pingを実行して応答時間を取得するだけでよい場合は、コンソールから出力を読み取るのはやり過ぎかもしれません。Java5以降を使用している限り、より簡単な方法があります。
これを行うために使用できる完全なプログラムを次に示します。注:Unix / Linux / Mac OSでは、「localhost」以外から応答を取得するには、「sudo」でこのプログラムを実行する必要があります。
import java.net.InetAddress;
import java.io.IOException;
class PingTest {
public static void main(String[] args) {
try {
String hostnameOrIP = args[0];
int timeout = Integer.parseInt(args[1]);
int pingCount = Integer.parseInt(args[2]);
System.out.println("Pinging '" + hostnameOrIP + "'");
for (int i = 0; i < pingCount; i++) {
System.out.println("Response time: " + getPingResponseTime(hostnameOrIP, timeout));
}
} catch (Exception e) {
System.out.println("Usage: java PingTest <hostname/IP address> <timeout in milliseconds> <number of pings to send>\n");
}
}
static long getPingResponseTime(String hostnameOrIP, int timeout) {
long startTime = System.currentTimeMillis();
boolean successfulPing = false;
try {
successfulPing = InetAddress.getByName(hostnameOrIP).isReachable(timeout);
} catch (IOException ioe) {
successfulPing = false;
}
long endTime = System.currentTimeMillis();
long responseTime = endTime-startTime;
if (successfulPing == false)
responseTime = -1;
return responseTime;
}
}
Mac OSで次のコマンドを実行したときに得られた結果は次のとおりです(結果はミリ秒単位です)。
$ sudo java PingTest google.com 5000 5
Pinging 'google.com'
Response time: 419
Response time: 15
Response time: 15
Response time: 16
Response time: 16
応答時間は実行ごとに異なる場合がありますが、特に複数のpingを実行する場合、ほとんどの主要なサイトへの応答時間は20ミリ秒未満です。