1

Windows で使用するために、Java で次の ping 関数をコーディングしました。これは、自分のコンピューターで完全に動作します。残念ながら、理由はわかりませんが、他のコンピューター (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 に答える