2012-01-11 46 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