View Javadoc

1   package nl.toolforge.core.util.net;
2   
3   import java.util.Date;
4   
5   /***
6    * The good old <code>ping</code> command in Java. Probably a copy of what exists elsewhere, but since I would have
7    * expect this one in the JDK ... Then, it took me 15 minutes to build this.
8    *
9    * @author D.A. Smedes
10   * @version $Id: Ping.java,v 1.1 2004/09/06 20:06:08 asmedes Exp $
11   */
12  public final class Ping {
13  
14    private Ping() {}
15  
16    /***
17     * Check if port <code>port</code> is reachable on host <code>host</code> within the next <code>timeOutInMillis</code>
18     * milliseconds, or else the check failed.
19     */
20    public static boolean ping(String host, int port, int timeOutInMillis) {
21  
22      PingThread t = new PingThread(host, port);
23  
24      t.start();
25  
26      long now = new Date().getTime();
27      long start = now;
28      boolean success = false;
29  
30      while (!success && now < (start + timeOutInMillis)) {
31  
32        try {
33          Thread.sleep(10);
34        } catch (InterruptedException e) {
35          return false;
36        }
37        success = t.pingOk();
38        now = new Date().getTime();
39      }
40      return success;
41    }
42  }