この質問にはさまざまな方法でアプローチされていることは知っていますが、stackoverflowを確認したところ、探していた答えが見つかりませんでした。
簡単にするために:WindowsでIPサーバーへのTime ping値を取得する方法はありますか?
一部のサーバーが到達可能かどうかを確認する方法は知っていますが、ターミナルで読み取ることができるように、正確な値が必要です。
何卒ご理解とご協力を賜りますようお願い申し上げます。
この質問にはさまざまな方法でアプローチされていることは知っていますが、stackoverflowを確認したところ、探していた答えが見つかりませんでした。
簡単にするために:WindowsでIPサーバーへのTime ping値を取得する方法はありますか?
一部のサーバーが到達可能かどうかを確認する方法は知っていますが、ターミナルで読み取ることができるように、正確な値が必要です。
何卒ご理解とご協力を賜りますようお願い申し上げます。
あなたはこのようなことをすることができます:
//The command to execute
String pingCmd = "ping " + ip + " -t";
//get the runtime to execute the command
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(pingCmd);
//Gets the inputstream to read the output of the command
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
//reads the outputs
String inputLine = in.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0) {
........
}
inputLine = in.readLine();
}
更新: 必要に応じて
public class PingDemo {
public static void main(String[] args) {
String ip = "localhost";
String time = "";
//The command to execute
String pingCmd = "ping " + ip;
//get the runtime to execute the command
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(pingCmd);
//Gets the inputstream to read the output of the command
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
//reads the outputs
String inputLine = in.readLine();
while ((inputLine != null)) {
if (inputLine.length() > 0 && inputLine.contains("time")) {
time = inputLine.substring(inputLine.indexOf("time"));
break;
}
inputLine = in.readLine();
}
System.out.println("time --> " + time);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
少し急いで書かれました。
pingコマンドを呼び出して出力を読み取ることができます(前の回答で説明したように)。または、より低いレバーアクセスが必要な場合(RAWソケットで行うことができるように)、jpcapjavaライブラリを確認できます。
ここに示すように、クラスを利用Runtime
してpingを実行する必要があります。必要なのは、入力ストリームを解析することだけです(おそらく、正規表現を使用して時間のping値を取得します)。
public static void main(String[] args) {
System.out.println("Enter the host to be pinged : ");
Scanner sc = new Scanner(in);
String str = sc.next();
System.out.println("Enter the no. of packets to be sent : ");
int packets = sc.nextByte();
String pingResult;
int count=0;
try{
String command = "ping -c "+ packets +" -w 10 " + str;
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
if(count==packets+4) {
pingResult = (inputLine.substring(inputLine.indexOf("=")));
pingResult = (pingResult.substring
(pingResult.indexOf("/")+1,pingResult.indexOf("/")+7));
System.out.println(pingResult + " ms");
}
count++;
}
in.close();
if(count==0)System.out.println("Wrong host entered.");
}catch(Exception e){
System.out.println("Exception caught: " + e.toString());
}
}
}
出力:pingするホストを入力してください:8.8.8.8番号を入力してください 送信されるパケットの数:531.406ミリ秒
プロセスは終了コード0で終了しました