Example #1
0
  public static void main(String[] args) {
    if (args.length == 0) {
      System.err.println("Usage: ntp.NTPClient <hostname-or-address-list>");
      System.exit(1);
    }

    NTPUDPClient client = new NTPUDPClient();
    // We want to timeout if a response takes longer than 10 seconds
    client.setDefaultTimeout(10000);
    try {
      client.open();
      for (String arg : args) {
        System.out.println();
        try {
          InetAddress hostAddr = InetAddress.getByName(arg);
          System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
          TimeInfo info = client.getTime(hostAddr);
          processResponse(info);
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }

    client.close();
  }
 public long getOffsetMs() throws SystemTimeManagerException {
   NTPUDPClient client = new NTPUDPClient();
   client.setDefaultTimeout(GET_OFFSET_DELAY_MS);
   try {
     client.open();
     try {
       InetAddress hostAddr = InetAddress.getByName(ntpServer);
       TimeInfo info = client.getTime(hostAddr);
       return getOffset(info);
     } catch (IOException e) {
       throw new SystemTimeManagerException(
           "Could not get time from " + ntpServer + ", because of " + e.getMessage(), e);
     } finally {
       client.close();
     }
   } catch (SocketException e) {
     throw new SystemTimeManagerException(
         "Could not open socket, because of " + e.getMessage(), e);
   }
 }
Example #3
0
  /**
   * Queries the given timeserver <code>hostname</code> and returns the time in milliseconds.
   *
   * @param hostname the timeserver to query
   * @return the time in milliseconds or the current time of the system if an error occurs.
   */
  protected static long getTime(String hostname) {

    try {
      NTPUDPClient timeClient = new NTPUDPClient();
      timeClient.setDefaultTimeout(NTP_TIMEOUT);
      InetAddress inetAddress = InetAddress.getByName(hostname);
      TimeInfo timeInfo = timeClient.getTime(inetAddress);

      return timeInfo.getReturnTime();
    } catch (UnknownHostException uhe) {
      logger.warn(
          "the given hostname '{}' of the timeserver is unknown -> returning current sytem time instead",
          hostname);
    } catch (IOException ioe) {
      logger.warn(
          "couldn't establish network connection [host '{}'] -> returning current sytem time instead",
          hostname);
    }

    return System.currentTimeMillis();
  }