Example usage for org.apache.commons.net.ntp NtpV3Packet setDatagramPacket

List of usage examples for org.apache.commons.net.ntp NtpV3Packet setDatagramPacket

Introduction

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

Prototype

public void setDatagramPacket(DatagramPacket dp);

Source Link

Document

Set the contents of this object from the datagram packet

Usage

From source file:examples.ntp.SimpleNTPServer.java

/**
 * Handle incoming packet. If NTP packet is client-mode then respond
 * to that host with a NTP response packet otherwise ignore.
 *
 * @param request incoming DatagramPacket
 * @param rcvTime time packet received//  w  ww . j  av a2  s . c  om
 *
 * @throws IOException  if an I/O error occurs.
 */
protected void handlePacket(DatagramPacket request, long rcvTime) throws IOException {
    NtpV3Packet message = new NtpV3Impl();
    message.setDatagramPacket(request);
    System.out.printf("NTP packet from %s mode=%s%n", request.getAddress().getHostAddress(),
            NtpUtils.getModeName(message.getMode()));
    if (message.getMode() == NtpV3Packet.MODE_CLIENT) {
        NtpV3Packet response = new NtpV3Impl();

        response.setStratum(1);
        response.setMode(NtpV3Packet.MODE_SERVER);
        response.setVersion(NtpV3Packet.VERSION_3);
        response.setPrecision(-20);
        response.setPoll(0);
        response.setRootDelay(62);
        response.setRootDispersion((int) (16.51 * 65.536));

        // originate time as defined in RFC-1305 (t1)
        response.setOriginateTimeStamp(message.getTransmitTimeStamp());
        // Receive Time is time request received by server (t2)
        response.setReceiveTimeStamp(TimeStamp.getNtpTime(rcvTime));
        response.setReferenceTime(response.getReceiveTimeStamp());
        response.setReferenceId(0x4C434C00); // LCL (Undisciplined Local Clock)

        // Transmit time is time reply sent by server (t3)
        response.setTransmitTime(TimeStamp.getNtpTime(System.currentTimeMillis()));

        DatagramPacket dp = response.getDatagramPacket();
        dp.setPort(request.getPort());
        dp.setAddress(request.getAddress());
        socket.send(dp);
    }
    // otherwise if received packet is other than CLIENT mode then ignore it
}