コード例 #1
0
ファイル: NTPClient.java プロジェクト: qianhk/FeiAndroid
  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();
  }
コード例 #2
0
 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);
   }
 }
コード例 #3
0
ファイル: NtpBinding.java プロジェクト: ptrvif/openhab
  /**
   * 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();
  }