我知道这个问题已经以不同的方式处理,但是我已经检查了stackoverflow,但我找不到我想要的答案。
简化:有没有办法让 Time ping值到 Windows 下的IP服务器?
我知道如何检查某些服务器是否可访问,但我想拥有精确的值,就像我们可以在终端上阅读一样。
感谢您的帮助和理解。
答案 0 :(得分:6)
您可以这样做:
//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);
}
}
}
写得很匆忙。
答案 1 :(得分:1)
您可以调用 ping 命令并读取输出(如上一个答案中所述),或者如果您需要更低的杠杆访问(就像您可以使用RAW套接字一样),您可以拥有看一下 jpcap java库。
答案 2 :(得分:1)
如图here所示,您将需要使用Runtime
类来清除ping。所有你需要的是解析输入流(可能使用正则表达式获取时间ping值)。
答案 3 :(得分:0)
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 输入号码。要发送的数据包: 五 31.406 ms
处理完成,退出代码为0