1

我用 Java 编写了以下 ping 函数供 Windows 使用,它可以在我自己的计算机上完美运行。不幸的是,我不知道为什么,但是在其他计算机(Windows 机器)上,当我运行它时,它会返回 "null"

例如,这会被 Windows 防火墙阻止吗?会不会是windows版本的问题?从XP到windows8,还是不同的语言版本?

在我的电脑上,我收到这样的结果:time=19ms TTL=111

有人可以启发我,为什么它会失败?

 private String ping() {

        String ip = "<external IP of a server running, always online>";
        String time = null;
        String pingCommand = "ping " + ip;
        ProcessBuilder builder = new ProcessBuilder(new String[] {"cmd.exe", "/C",pingCommand});
    try {
        Process newProcess = builder.start();
            BufferedReader in = new BufferedReader(new InputStreamReader(newProcess.getInputStream()));
            String inputLine = in.readLine();
            while ((inputLine != null)) {
                if (inputLine.length() > 0) {
                    if(inputLine.contains("time")){
                        // Checking for the time only
                        time = inputLine.substring(inputLine.indexOf("time"));
                        break;
                    }
                }
                inputLine = in.readLine();
            }
    } catch (IOException ex) {
        Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
    }
    return time; 
}
4

1 回答 1

-1

您可以使用 Runtime 类来运行 Windows 命令。请参阅此示例;

   private String ping() {
       Runtime rt = Runtime.getRuntime();   
       String time = null;
       String pingCommand = "cmd.exe /C ping yourIpAddress";
       try {
            Process newProcess = rt.exec(pingCommand);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                newProcess.getInputStream()));
            String inputLine = in.readLine();
            while ((inputLine != null)) {
                  if (inputLine.length() > 0) {
                     if (inputLine.contains("time")) {
                     // Checking for the time only
                         time = inputLine.substring(inputLine.indexOf("time"));
                               break;
                             }
                        }
                    inputLine = in.readLine();
        }
    } catch (IOException ex) {
    }
    return time;
}
于 2012-09-07T11:04:10.927 回答