2010-04-13 79 views

回答

4

這是我今天寫的「實現」Java中的跟蹤路由命令。我只在Windows上測試過,但它也應該在Linux中工作,儘管有幾種traceroute工具可用於Linux,所以很可能需要對這些程序的存在進行一些檢查。

public class NetworkDiagnostics{ 
    private final String os = System.getProperty("os.name").toLowerCase(); 

    public String traceRoute(InetAddress address){ 
    String route = ""; 
    try { 
     Process traceRt; 
     if(os.contains("win")) traceRt = Runtime.getRuntime().exec("tracert " + address.getHostAddress()); 
     else traceRt = Runtime.getRuntime().exec("traceroute " + address.getHostAddress()); 

     // read the output from the command 
     route = convertStreamToString(traceRt.getInputStream()); 

     // read any errors from the attempted command 
     String errors = convertStreamToString(traceRt.getErrorStream()); 
     if(errors != "") LOGGER.error(errors); 
    } 
    catch (IOException e) { 
     LOGGER.error("error while performing trace route command", e); 
    } 

    return route; 
} 
+2

應將條件更改爲os.toLowerCase()。contains(「win」) – Hassan 2015-09-12 02:59:00

+0

您在哪裏使用了** convertStreamToString **方法? – Omore 2018-01-25 19:26:29

+0

@Omore你問問它在哪裏定義?我認爲這是我寫的一種自定義方法。我再也無法訪問代碼,所以你必須弄清楚如何實現它。如果你這樣做,請更新我的答案以包含它;你會得到這樣的積分。 – 2018-01-26 18:10:10