Example usage for org.apache.commons.net.ntp NTPUDPClient open

List of usage examples for org.apache.commons.net.ntp NTPUDPClient open

Introduction

In this page you can find the example usage for org.apache.commons.net.ntp NTPUDPClient open.

Prototype

public void open() throws SocketException 

Source Link

Document

Opens a DatagramSocket on the local host at the first available port.

Usage

From source file:org.urbancortex.routes.NTPClient.java

public static TimeInfo main(String[] args) {
    System.out.println(args);//from  www .j  av a2s . c  o  m

    if (args.length == 0) {
        System.err.println("Usage: 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);

                return info;

            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    client.close();
    return null;
}

From source file:util.android.util.DateUtils.java

public static Date getNTPTime() {
    NTPUDPClient timeClient = new NTPUDPClient();
    timeClient.setDefaultTimeout(2000);// w  w w .  j  a  v a  2s.c om

    TimeInfo timeInfo;
    try {
        timeClient.open();
        InetAddress inetAddress = InetAddress.getByName(getNTPServer());
        timeInfo = timeClient.getTime(inetAddress);

        long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
        Date time = new Date(returnTime);
        timeClient.close();
        return time;
    } catch (Exception e) {
        e.printStackTrace();
        return new Date();
    }
}