2012-01-11 79 views

回答

10

作爲viralpatel指定可以使用Runtime.exec()

以下是它的一個例子

class pingTest { 

    public static void main(String[] args) { 
     String ip = "127.0.0.1"; 
     String pingResult = ""; 

     String pingCmd = "ping " + ip; 
     try { 
      Runtime r = Runtime.getRuntime(); 
      Process p = r.exec(pingCmd); 

      BufferedReader in = new BufferedReader(new 
      InputStreamReader(p.getInputStream())); 
      String inputLine; 
      while ((inputLine = in.readLine()) != null) { 
       System.out.println(inputLine); 
       pingResult += inputLine; 
      } 
      in.close(); 

     } catch (IOException e) { 
      System.out.println(e); 
     } 

    } 
} 

輸出

Pinging 127.0.0.1 with 32 bytes of data: 
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 

Ping statistics for 127.0.0.1: 
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), 
Approximate round trip times in milli-seconds: 
    Minimum = 0ms, Maximum = 0ms, Average = 0ms 

參閱http://www.velocityreviews.com/forums/t146589-ping-class-java.html

+0

我想在html中添加輸出而不是println當我嘗試這樣做時,它會一直執行很長時間,然後我取消它! – 2012-01-11 06:44:30

+0

我應該如何將它附加到html? – 2012-01-11 06:45:02

+0

我認爲你正在使用'servlet',那麼你可以使用printwriter對象將文本添加到servlet html – 2012-01-11 06:49:21

3

InetAddress類有一個使用ECMP迴應請求,以確定主機可用性的方法(又名平)。

String ipAddress = "192.168.1.10"; 
InetAddress inet = InetAddress.getByName(ipAddress); 
boolean reachable = inet.isReachable(5000); 

如果上述reachable變量爲真,那麼就意味着主機已經適當地與ECMP回顯應答(又名乒乓)給定的時間內(以毫秒)回答。

注意:並非所有的實現都必須使用ping。 The documentation states that

一個典型的實現將使用ICMP echo請求,如果能獲得特權 ,否則將嘗試建立目標主機的端口TCP連接 7(回聲)。

因此,該方法可用於檢查主機可用性,但它不能普遍用於檢查基於ping的檢查。

+1

在Windows下,似乎java不使用ping,並且默認使用端口7上的TCP連接,而這通常被防火牆阻止。在Unix下,ping需要root訪問權限,因此通常也默認使用端口7.因此在生產環境中isReachable是無用的。 – ssindelar 2016-06-01 11:45:04