`
lshh83
  • 浏览: 162571 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

java通过NTP时间服务器获得时间

阅读更多
本程序是java通过网络访问NTP时间服务器,而获得精准的时间。不是获得本地时间。

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;

public class TestNtp{

    public static void main(String[] args){
        int retry = 2;
        int port = 123;
        int timeout = 3000;

        // get the address and NTP address request
        //
        InetAddress ipv4Addr = null;
        try {
            ipv4Addr = InetAddress.getByName("203.117.180.36");//更多NTP时间服务器参考附注
               } catch (UnknownHostException e1) {
            e1.printStackTrace();
        }

        int serviceStatus = -1;
        DatagramSocket socket = null;
        long responseTime = -1;
        try {
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout); // will force the
            // InterruptedIOException

            for (int attempts = 0; attempts <= retry && serviceStatus != 1; attempts++) {
                try {
                    // Send NTP request
                    //
                    byte[] data = new NtpMessage().toByteArray();
                    DatagramPacket outgoing = new DatagramPacket(data, data.length, ipv4Addr, port);
                    long sentTime = System.currentTimeMillis();
                    socket.send(outgoing);

                    // Get NTP Response
                    //
                    // byte[] buffer = new byte[512];
                    DatagramPacket incoming = new DatagramPacket(data, data.length);
                    socket.receive(incoming);
                    responseTime = System.currentTimeMillis() - sentTime;
                    double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
                    //这里要加2208988800,是因为获得到的时间是格林尼治时间,所以要变成东八区的时间,否则会与与北京时间有8小时的时差

                    // Validate NTP Response
                    // IOException thrown if packet does not decode as expected.
                    NtpMessage msg = new NtpMessage(incoming.getData());
                    double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2;

                    System.out.println("poll: valid NTP request received the local clock offset is " + localClockOffset + ", responseTime= " + responseTime + "ms");
                    System.out.println("poll: NTP message : " + msg.toString());
                    serviceStatus = 1;
                } catch (InterruptedIOException ex) {
                    // Ignore, no response received.
                }
            }
        } catch (NoRouteToHostException e) {
            System.out.println("No route to host exception for address: " + ipv4Addr);
        } catch (ConnectException e) {
            // Connection refused. Continue to retry.
            e.fillInStackTrace();
            System.out.println("Connection exception for address: " + ipv4Addr);
        } catch (IOException ex) {
            ex.fillInStackTrace();
            System.out.println("IOException while polling address: " + ipv4Addr);
        } finally {
            if (socket != null)
                socket.close();
        }

        // Store response time if available
        //
        if (serviceStatus == 1) {
            System.out.println("responsetime=="+responseTime);
        }

        
    }
}

//**************************************************************************************************************
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NtpMessage {
    /** *//**
     * This is a two-bit code warning of an impending leap second to be
     * inserted/deleted in the last minute of the current day. It''s values may
     * be as follows:
     * 
     * Value Meaning ----- ------- 0 no warning 1 last minute has 61 seconds 2
     * last minute has 59 seconds) 3 alarm condition (clock not synchronized)
     */
    public byte leapIndicator = 0;

    /** *//**
     * This value indicates the NTP/SNTP version number. The version number is 3
     * for Version 3 (IPv4 only) and 4 for Version 4 (IPv4, IPv6 and OSI). If
     * necessary to distinguish between IPv4, IPv6 and OSI, the encapsulating
     * context must be inspected.
     */
    public byte version = 3;

    /** *//**
     * This value indicates the mode, with values defined as follows:
     * 
     * Mode Meaning ---- ------- 0 reserved 1 symmetric active 2 symmetric
     * passive 3 client 4 server 5 broadcast 6 reserved for NTP control message
     * 7 reserved for private use
     * 
     * In unicast and anycast modes, the client sets this field to 3 (client) in
     * the request and the server sets it to 4 (server) in the reply. In
     * multicast mode, the server sets this field to 5 (broadcast).
     */
    public byte mode = 0;

    /** *//**
     * This value indicates the stratum level of the local clock, with values
     * defined as follows:
     * 
     * Stratum Meaning ---------------------------------------------- 0
     * unspecified or unavailable 1 primary reference (e.g., radio clock) 2-15
     * secondary reference (via NTP or SNTP) 16-255 reserved
     */
    public short stratum = 0;

    /** *//**
     * This value indicates the maximum interval between successive messages, in
     * seconds to the nearest power of two. The values that can appear in this
     * field presently range from 4 (16 s) to 14 (16284 s); however, most
     * applications use only the sub-range 6 (64 s) to 10 (1024 s).
     */
    public byte pollInterval = 0;

    /** *//**
     * This value indicates the precision of the local clock, in seconds to the
     * nearest power of two. The values that normally appear in this field
     * range from -6 for mains-frequency clocks to -20 for microsecond clocks
     * found in some workstations.
     */
    public byte precision = 0;

    /** *//**
     * This value indicates the total roundtrip delay to the primary reference
     * source, in seconds. Note that this variable can take on both positive and
     * negative values, depending on the relative time and frequency offsets.
     * The values that normally appear in this field range from negative values
     * of a few milliseconds to positive values of several hundred milliseconds.
     */
    public double rootDelay = 0;

    /** *//**
     * This value indicates the nominal error relative to the primary reference
     * source, in seconds. The values that normally appear in this field range
     * from 0 to several hundred milliseconds.
     */
    public double rootDispersion = 0;

    /** *//**
     * This is a 4-byte array identifying the particular reference source. In
     * the case of NTP Version 3 or Version 4 stratum-0 (unspecified) or
     * stratum-1 (primary) servers, this is a four-character ASCII string, left
     * justified and zero padded to 32 bits. In NTP Version 3 secondary servers,
     * this is the 32-bit IPv4 address of the reference source. In NTP Version 4
     * secondary servers, this is the low order 32 bits of the latest transmit
     * timestamp of the reference source. NTP primary (stratum 1) servers should
     * set this field to a code identifying the external reference source
     * according to the following list. If the external reference is one of
     * those listed, the associated code should be used. Codes for sources not
     * listed can be contrived as appropriate.
     * 
     * Code External Reference Source ---- ------------------------- LOCL
     * uncalibrated local clock used as a primary reference for a subnet without
     * external means of synchronization PPS atomic clock or other
     * pulse-per-second source individually calibrated to national standards
     * ACTS NIST dialup modem service USNO USNO modem service PTB PTB (Germany)
     * modem service TDF Allouis (France) Radio 164 kHz DCF Mainflingen
     * (Germany) Radio 77.5 kHz MSF Rugby (UK) Radio 60 kHz WWV Ft. Collins (US)
     * Radio 2.5, 5, 10, 15, 20 MHz WWVB Boulder (US) Radio 60 kHz WWVH Kaui
     * Hawaii (US) Radio 2.5, 5, 10, 15 MHz CHU Ottawa (Canada) Radio 3330,
     * 7335, 14670 kHz LORC LORAN-C radionavigation system OMEG OMEGA
     * radionavigation system GPS Global Positioning Service GOES Geostationary
     * Orbit Environment Satellite
     */
    public byte[] referenceIdentifier = { 0, 0, 0, 0 };

    /** *//**
     * This is the time at which the local clock was last set or corrected, in
     * seconds since 00:00 1-Jan-1900.
     */
    public double referenceTimestamp = 0;

    /** *//**
     * This is the time at which the request departed the client for the server,
     * in seconds since 00:00 1-Jan-1900.
     */
    public double originateTimestamp = 0;

    /** *//**
     * This is the time at which the request arrived at the server, in seconds
     * since 00:00 1-Jan-1900.
     */
    public double receiveTimestamp = 0;

    /** *//**
     * This is the time at which the reply departed the server for the client,
     * in seconds since 00:00 1-Jan-1900.
     */
    public double transmitTimestamp = 0;

    /** *//**
     * Constructs a new NtpMessage from an array of bytes.
     */
    public NtpMessage(byte[] array) {
        // See the packet format diagram in RFC 2030 for details
        leapIndicator = (byte) ((array[0] >> 6) & 0x3);
        version = (byte) ((array[0] >> 3) & 0x7);
        mode = (byte) (array[0] & 0x7);
        stratum = unsignedByteToShort(array[1]);
        pollInterval = array[2];
        precision = array[3];

        rootDelay = (array[4] * 256.0) + unsignedByteToShort(array[5]) + (unsignedByteToShort(array[6]) / 256.0) + (unsignedByteToShort(array[7]) / 65536.0);

        rootDispersion = (unsignedByteToShort(array[8]) * 256.0) + unsignedByteToShort(array[9]) + (unsignedByteToShort(array[10]) / 256.0) + (unsignedByteToShort(array[11]) / 65536.0);

        referenceIdentifier[0] = array[12];
        referenceIdentifier[1] = array[13];
        referenceIdentifier[2] = array[14];
        referenceIdentifier[3] = array[15];

        referenceTimestamp = decodeTimestamp(array, 16);
        originateTimestamp = decodeTimestamp(array, 24);
        receiveTimestamp = decodeTimestamp(array, 32);
        transmitTimestamp = decodeTimestamp(array, 40);
    }

    /** *//**
     * Constructs a new NtpMessage
     */
    public NtpMessage(byte leapIndicator, byte version, byte mode, short stratum, byte pollInterval, byte precision, double rootDelay, double rootDispersion, byte[] referenceIdentifier, double referenceTimestamp, double originateTimestamp, double receiveTimestamp, double transmitTimestamp) {
        // ToDo: Validity checking
        this.leapIndicator = leapIndicator;
        this.version = version;
        this.mode = mode;
        this.stratum = stratum;
        this.pollInterval = pollInterval;
        this.precision = precision;
        this.rootDelay = rootDelay;
        this.rootDispersion = rootDispersion;
        this.referenceIdentifier = referenceIdentifier;
        this.referenceTimestamp = referenceTimestamp;
        this.originateTimestamp = originateTimestamp;
        this.receiveTimestamp = receiveTimestamp;
        this.transmitTimestamp = transmitTimestamp;
    }

    /** *//**
     * Constructs a new NtpMessage in client -> server mode, and sets the
     * transmit timestamp to the current time.
     */
    public NtpMessage() {
        // Note that all the other member variables are already set with
        // appropriate default values.
        this.mode = 3;
        this.transmitTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
    }

    /** *//**
     * This method constructs the data bytes of a raw NTP packet.
     */
    public byte[] toByteArray() {
        // All bytes are automatically set to 0
        byte[] p = new byte[48];

        p[0] = (byte) (leapIndicator << 6 | version << 3 | mode);
        p[1] = (byte) stratum;
        p[2] = (byte) pollInterval;
        p[3] = (byte) precision;

        // root delay is a signed 16.16-bit FP, in Java an int is 32-bits
        int l = (int) (rootDelay * 65536.0);
        p[4] = (byte) ((l >> 24) & 0xFF);
        p[5] = (byte) ((l >> 16) & 0xFF);
        p[6] = (byte) ((l >> 8) & 0xFF);
        p[7] = (byte) (l & 0xFF);

        // root dispersion is an unsigned 16.16-bit FP, in Java there are no
        // unsigned primitive types, so we use a long which is 64-bits
        long ul = (long) (rootDispersion * 65536.0);
        p[8] = (byte) ((ul >> 24) & 0xFF);
        p[9] = (byte) ((ul >> 16) & 0xFF);
        p[10] = (byte) ((ul >> 8) & 0xFF);
        p[11] = (byte) (ul & 0xFF);

        p[12] = referenceIdentifier[0];
        p[13] = referenceIdentifier[1];
        p[14] = referenceIdentifier[2];
        p[15] = referenceIdentifier[3];

        encodeTimestamp(p, 16, referenceTimestamp);
        encodeTimestamp(p, 24, originateTimestamp);
        encodeTimestamp(p, 32, receiveTimestamp);
        encodeTimestamp(p, 40, transmitTimestamp);

        return p;
    }

    /** *//**
     * Returns a string representation of a NtpMessage
     */
    public String toString() {
        String precisionStr = new DecimalFormat("0.#E0").format(Math.pow(2, precision));
        return "Leap indicator: " + leapIndicator + " " + "Version: " + version + " " + "Mode: " + mode + " " + "Stratum: " + stratum + " " + "Poll: " + pollInterval + " " + "Precision: " + precision + " (" + precisionStr + " seconds) " + "Root delay: " + new DecimalFormat("0.00").format(rootDelay * 1000) + " ms " + "Root dispersion: " + new DecimalFormat("0.00").format(rootDispersion * 1000) + " ms " + "Reference identifier: " + referenceIdentifierToString(referenceIdentifier, stratum, version) + " " + "Reference timestamp: " + timestampToString(referenceTimestamp) + " " + "Originate timestamp: " + timestampToString(originateTimestamp) + " " + "Receive timestamp:   " + timestampToString(receiveTimestamp) + " " + "Transmit timestamp: " + timestampToString(transmitTimestamp);
    }

    /** *//**
     * Converts an unsigned byte to a short. By default, Java assumes that a
     * byte is signed.
     */
    public static short unsignedByteToShort(byte b) {
        if ((b & 0x80) == 0x80)
            return (short) (128 + (b & 0x7f));
        else
            return (short) b;
    }

    /** *//**
     * Will read 8 bytes of a message beginning at <code>pointer</code> and
     * return it as a double, according to the NTP 64-bit timestamp format.
     */
    public static double decodeTimestamp(byte[] array, int pointer) {
        double r = 0.0;

        for (int i = 0; i < 8; i++) {
            r += unsignedByteToShort(array[pointer + i]) * Math.pow(2, (3 - i) * 8);
        }

        return r;
    }

    /** *//**
     * Encodes a timestamp in the specified position in the message
     */
    public static void encodeTimestamp(byte[] array, int pointer, double timestamp) {
        // Converts a double into a 64-bit fixed point
        for (int i = 0; i < 8; i++) {
            // 2^24, 2^16, 2^8, .. 2^-32
            double base = Math.pow(2, (3 - i) * 8);

            // Capture byte value
            array[pointer + i] = (byte) (timestamp / base);

            // Subtract captured value from remaining total
            timestamp = timestamp - (double) (unsignedByteToShort(array[pointer + i]) * base);
        }

        // From RFC 2030: It is advisable to fill the non-significant
        // low order bits of the timestamp with a random, unbiased
        // bitstring, both to avoid systematic roundoff errors and as
        // a means of loop detection and replay detection.
        array[7] = (byte) (Math.random() * 255.0);
    }

    /** *//**
     * Returns a timestamp (number of seconds since 00:00 1-Jan-1900) as a
     * formatted date/time string.
     */
    public static String timestampToString(double timestamp) {
        if (timestamp == 0)
            return "0";

        // timestamp is relative to 1900, utc is used by Java and is relative
        // to 1970
        double utc = timestamp - (2208988800.0);

        // milliseconds
        long ms = (long) (utc * 1000.0);

        // date/time
        String date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date(ms));

        // fraction
        double fraction = timestamp - ((long) timestamp);
        String fractionSting = new DecimalFormat(".000000").format(fraction);

        return date + fractionSting;
    }

    /** *//**
     * Returns a string representation of a reference identifier according to
     * the rules set out in RFC 2030.
     */
    public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) {
        // From the RFC 2030:
        // In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)
        // or stratum-1 (primary) servers, this is a four-character ASCII
        // string, left justified and zero padded to 32 bits.
        if (stratum == 0 || stratum == 1) {
            return new String(ref);
        }

        // In NTP Version 3 secondary servers, this is the 32-bit IPv4
        // address of the reference source.
        else if (version == 3) {
            return unsignedByteToShort(ref[0]) + "." + unsignedByteToShort(ref[1]) + "." + unsignedByteToShort(ref[2]) + "." + unsignedByteToShort(ref[3]);
        }

        // In NTP Version 4 secondary servers, this is the low order 32 bits
        // of the latest transmit timestamp of the reference source.
        else if (version == 4) {
            return "" + ((unsignedByteToShort(ref[0]) / 256.0) + (unsignedByteToShort(ref[1]) / 65536.0) + (unsignedByteToShort(ref[2]) / 16777216.0) + (unsignedByteToShort(ref[3]) / 4294967296.0));
        }

        return "";
    }
}


结果:

poll: valid NTP request received the local clock offset is 3606.92320227623, responseTime= 265ms
poll: NTP message : Leap indicator: 0 Version: 3 Mode: 4 Stratum: 1 Poll: 0 Precision: -18 (3.8E-6 seconds) Root delay: 0.00 ms Root dispersion: 0.00 ms Reference identifier: ACTS Reference timestamp: 26-三月-2009 20:50:23.508540 Originate timestamp: 26-三月-2009 19:51:10.031000 Receive timestamp:   26-三月-2009 20:51:17.086693 Transmit timestamp: 26-三月-2009 20:51:17.086712
responsetime==265

注意看红色部分,这是本地时间,我故意将本地时间调慢了一小时。


附注1:中国大概能用的NTP时间服务器
     server 133.100.11.8 prefer
     server 210.72.145.44
     server 203.117.180.36 //程序中所用的
     server 131.107.1.10
     server time.asia.apple.com
     server 64.236.96.53
     server 130.149.17.21
     server 66.92.68.246
     server www.freebsd.org
     server 18.145.0.30
     server clock.via.net
     server 137.92.140.80
     server 133.100.9.2
     server 128.118.46.3
     server ntp.nasa.gov
     server 129.7.1.66
     server ntp-sop.inria.frserver 210.72.145.44(国家授时中心服务器IP地址)
     ntpdate 131.107.1.10
     ntpdate -s time.asia.apple.com

附注2:NTP概念简介


  Network Time Protocol(NTP)是用来使计算机时间同步化的一种协议,它可以使计算机对其服务器或时钟源(如石英钟,GPS等等)做同步化,它可以提供高精准度的时间校正(LAN上与标准间差小于1毫秒,WAN上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。
分享到:
评论

相关推荐

    从NTP服务器获取准确的时间,常常被用于校准本地时间。

    从NTP服务器获取准确的时间,常常被用于校准本地时间。

    获取NTP服务器时间,更改本地时间

    此步骤是必要的,以便能够从服务器获取时间信息。 ```csharp client.Connect(); ``` 3. **接收时间戳**:通过调用`ReceiveTimestamp`属性可以获取到从NTP服务器接收到的时间戳。这个时间戳是一个`DateTime`类型...

    NTP内网时间同步

    当安卓设备无法直接访问互联网时,可以通过设置内网中的NTP服务器来实现时间校准。 NTP是一种协议,设计用于在计算机网络中同步系统时钟,确保所有设备都有相同的时间。这对于分布式系统和跨设备的事件追踪是必不可...

    Android NTP获取时间demo

    1. **理解NTP工作原理**:NTP通过向NTP服务器发送请求来获取精确的时间戳。这个时间戳代表的是自1900年1月1日以来经过的秒数。服务器返回的时间戳包含了服务器的UTC时间。 2. **构建NTP请求**:在Android应用中,...

    NTP配置时间同步。。。NTP配置时间同步!good!

    NTP通过在网络中寻找准确的时间源(通常为公共NTP服务器或内部GPS接收器),然后调整本地系统时钟,以使所有系统保持一致的时间。NTP服务器根据“层”或“级别”(stratum)进行分级,层次越低,时钟越准确。理想...

    转 Java校正电脑时间(java 时间同步)

    总之,Java中的时间同步主要依赖于网络通信和第三方库,如JNA来实现与NTP服务器的交互。通过这种方式,开发者可以确保本地系统时间与网络标准保持一致,这对于许多需要精确时间戳的应用场景,如金融交易、日志记录等...

    pj-ntp-server:纯Java NTP服务器。-开源

    纯Java NTP服务器。 在没有cmd参数的情况下以root / admin身份在cmd-mode中运行,例如:java -jar pj-ntp-server.jar(服务器在标准UDP / 123-port上启动)或在root-admin中以UDP-以cmd-mode运行port cmd参数,例如...

    获取淘宝服务器时间

    这涉及到网络同步技术,如NTP(Network Time Protocol),它允许设备通过网络从时间服务器获取精确的时间。 3. **淘宝网**:淘宝是中国最大的电商平台之一,其服务器时间对交易、库存更新和各种促销活动至关重要。...

    java自动同步时间(Windows) 修改版 (已编译,有源码)

    在Java程序中,通过发送请求到NTP服务器,获取当前的标准时间,然后调用nircmd执行时间设置命令,将系统时间更新为获取到的准确时间。 项目中包含的主要文件如下: 1. `点我校准时间.bat`:这是一个批处理文件,...

    用java获取网络时间

    - **效率与安全性**:频繁地从网络获取时间可能会影响性能,同时也可能存在安全风险。建议在实际应用中考虑使用缓存机制或者更安全的方法来获取时间。 #### 扩展知识点 1. **`URLConnection`类详解**: - `...

    NTP校时判断win或linux服务.rar

    NTP的工作原理是通过向NTP服务器发送请求,然后接收包含精确时间戳的响应,从而获取到准确的世界协调时间(UTC)。Java中的`java.net.Socket`和`java.io`库可以用来建立与NTP服务器的连接并交换数据。 要实现NTP校...

    计网课设:NTP协议网络对时程序

    2.2 NTPClient类:在项目中,开发者可能自定义了`NTPClient`类,该类负责与NTP服务器通信,发送请求并解析响应,获取时间信息。 三、Swing界面设计 3.1 Swing简介:Swing是Java的GUI库,提供了丰富的组件和布局...

    NTP时间同步

    这个类提供了获取远程NTP服务器时间的功能。开发者需要指定一个NTP服务器地址,然后发送请求并接收响应,解析返回的数据,最后调整设备时间。 3. **NTP服务器选择** NTP服务器的选择是关键,因为它们的时间准确性...

    自动获取国家授时中心服务器时间,并修改系统时间。自动同步时间!

    标题中的“自动获取国家授时中心服务器时间,并修改系统时间。自动同步时间!”表明这是一个程序,其功能是连接到国家授时中心的服务器,获取最准确的时间信息,并将用户的计算机系统时间同步到这个标准时间。这样的...

    java同步网络时间

    `netTime`源码可能包含了上述步骤的实现,通过阅读源码,我们可以深入理解网络时间同步的具体细节,包括错误处理、重试机制以及可能的优化策略,例如选择多个NTP服务器进行查询以提高准确性。 为了确保程序的正确...

    获取局域网服务器时间

    管理员可以配置服务器从外部NTP服务器获取时间,并让局域网内的其他Linux机器同步到这台服务器。 5. **数据库时间戳** 在数据库中,时间戳字段记录了数据插入或更新的具体时间,这对于审计追踪、数据分析和故障...

    时间同步软件JAVA

    5. **NTP服务器配置为主时间服务器.reg**:这是一个Windows注册表文件,用于将特定的NTP服务器设置为主时间服务器。注册表是Windows操作系统中存储系统设置和配置信息的地方。导入此文件可以修改本地系统的注册表...

    分布式系统从服务器获取时间

    在"分布式系统从服务器获取时间"的案例中,服务器端会实现一个包含当前时间的方法,例如`getCurrentTime()`。这个方法会返回服务器的系统时间,通常是`java.util.Date`或`java.time.LocalDateTime`等表示时间的对象...

    网络对时代码 用于将本地系统时间与网络时间一致

    次级时钟(Stratum 2及以上)服务器,通过连接到上级服务器获取时间。 在编程实现网络对时功能时,我们可以选择不同的编程语言。例如,在Python中,可以使用`pyNTP`库,或者手动实现NTP请求和响应的处理。以下是一...

    NTP.rar_ntp

    通过NTP协议,程序可以从远程NTP服务器获取时间戳,并校正本地系统时钟。Java中的NTP客户端通常依赖于如`com.sun.jna`这样的库,该库允许Java代码调用本机操作系统API,包括NTP协议的相关接口。 NTP的工作原理主要...

Global site tag (gtag.js) - Google Analytics