【问题标题】:I want to get the ping execution time and result in string after ping host我想在 ping 主机后获取 ping 执行时间并生成字符串
【发布时间】:2012-01-11 09:25:14
【问题描述】:

我想在 ping 主机后获取 ping 执行时间和结果字符串。我该怎么做?

【问题讨论】:

    标签: java ping


    【解决方案1】:
    long currentTime = System.currentTimeMillis();
    boolean isPinged = InetAddress.getByName(servername).isReachable(2000); // 2 seconds
    currentTime = System.currentTimeMillis() - currentTime;
    if(isPinged) {
        System.out.println("pinged successfully in "+ currentTime+ "millisecond");
    } else {
        System.out.println("PIng failed.");
    }
    

    但这只会在 windows 系统中使用 ICMP ping。

    【讨论】:

      【解决方案2】:
      【解决方案3】:
      long start = System.currentTimeMillis();
      long ping;
      
      
      
      
      String[] command = { "cmd.exe", "/C", "ping 192.168.1.101" };
      commandProcess = Runtime.getRuntime().exec(command);
      BufferedReader buffy = new BufferedReader(new InputStreamReader(commandProcess.getInputStream()));
      String readline;
      while((readline = buffy.readLine())!=null){
      System.out.println(readline);
      if(readline.contains("reply")){
       long ping = System.currentTimeMillis();
       System.out.println("Pinged in:"+ ping);
       }
      }
       long end = System.currentTimeMillis();
       String done = "Completed in times:" +start + ping +end;
      

      【讨论】:

        【解决方案4】:

        这就是我使用它的方式-

        private static void checkPing(String hostName) {
        
            String[] command = { "cmd.exe", "/C", "ping " + hostName };
            try {
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader buff = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String readline;
                while ((readline = buff.readLine()) != null) {
                    if (readline.contains("Reply")) {
                        System.out.println("Pinged " + hostName + " in : "
                                + readline.substring(readline.indexOf("time=") + 5, readline.indexOf("ms")) + " ms");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        

        为您提供每个 ping 请求的准确(可靠)ping 延迟(以毫秒为单位)。 如果需要,您可以添加其中的四个

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-21
          • 2017-04-29
          • 1970-01-01
          • 2013-05-28
          相关资源
          最近更新 更多