2012-11-26 28 views
0

我有一個任務是在Java中創建一個簡單的控制檯pinger。 我試過下面的代碼,我有兩個主要問題。如何在Java中ping和保持統計信息

首先,即使我連接到互聯網(我可以從控制檯任何網站ping),當我運行代碼返回false。

其次,是否有可能跟蹤ping的響應時間?

下面是代碼:

try { 
    InetAddress address = InetAddress.getByName(the_link); 
    System.out.println(the_link); 
    // Try to reach the specified address within the timeout 
    // periode. If during this periode the address cannot be 
    // reach then the method returns false. 
    boolean reachable = address.isReachable(5000); 
    System.out.println("Is host reachable? " + reachable); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

地獄呢?哎呀。 – Raptor

+0

剛剛編輯...你好...! :) – Vagelism

+1

見過:http://stackoverflow.com/questions/2448666/how-to-do-a-true-java-ping-from-windows? – fatfredyy

回答

1

這不是一個很好的用於大多數外部的IP。 相反,可以使用如下

boolean reachable = (java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.lk").waitFor()==0); 
+0

這看起來不錯,但我想卡車的響應時間。我可以用這個命令做到這一點,並將多重ping的時間保存到數組中嗎? – Vagelism

+1

你也可以用這個做同樣的事情。例如:您可以將其添加到線程並迭代它,等待期望的時間段。 – namalfernandolk

+0

對於等待我瞭解它,但我想有時間的反饋?我想抓取需要ping的保存時間並將其保存到列表中。 – Vagelism