在java中Ping值

我知道这个问题已经以不同的方式处理,但是我已经检查了stackoverflow,但我没有找到我想要的答案。

为简单起见:有没有办法在Windows下为Windows服务器获取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套接字一样),您可以查看jpcap java库。

如此处所示,您将需要使用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输入no。 要发送的数据包:5 31.406 ms

进程以退出代码0结束