【Android 應用】簡單實測可行的獲取NTP時間實例

最近在做一個應用,涉及到數據上報,數據上報就涉及到時間,如果時間不對,服務器可能會拒絕你的數據。就算不拒絕,你上報的數據也是不正確的,我們採取的是寧可不要數據,也用錯誤的數據。這就體現到NTP獲取數據的重要性了。

但是查詢了大半天,發現網上的ntp請求都是過時的,獲取格式不正確,很難讀懂。自己重新弄了一下,就記錄下來以防以後在用到查詢。


一、可用的NTP地址

"ntp1.aliyun.com, ntp2.aliyun.com, ntp3.aliyun.com, ntp4.aliyun.com, ntp5.aliyun.com, ntp6.aliyun.com, ntp7.aliyun.com,cn.pool.ntp.org, cn.ntp.org.cn, sg.pool.ntp.org, tw.pool.ntp.org, jp.pool.ntp.org, hk.pool.ntp.org, th.pool.ntp.org,time.windows.com, time.nist.gov, time.apple.com, time.asia.apple.com, dns1.synet.edu.cn, news.neu.edu.cn, dns.sjtu.edu.cn,dns2.synet.edu.cn, ntp.glnet.edu.cn, s2g.time.edu.cn, ntp-sz.chl.la, ntp.gwadar.cn, 3.asia.pool.ntp.org"

二、實例

由於比較簡單就直接上源碼了。

package com.android.vps.basic.protocol;

import android.os.SystemClock;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class NtpClient {
    private static final String TAG = "NTPClient";
    private static NtpClient mNtpClient = null;
    private boolean mNtpClientState = false;
    private boolean mGetNtpAsync = false;

    private static final int ORIGINATE_TIME_OFFSET = 24;
    private static final int RECEIVE_TIME_OFFSET = 32;
    private static final int TRANSMIT_TIME_OFFSET = 40;
    private static final int NTP_PACKET_SIZE = 48;

    private static final int NTP_PORT = 123;
    private static final int NTP_MODE_CLIENT = 3;
    private static final int NTP_VERSION = 3;

    // Number of seconds between Jan 1, 1900 and Jan 1, 1970
    // 70 years plus 17 leap days
    private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

    private NtpClient(){
        mNtpClientState = false;
    }

    public synchronized static NtpClient getInstance(){
        if(mNtpClient == null){
            mNtpClient = new NtpClient();
        }
        return mNtpClient;
    }

    /**
     * 開啓ntp獲取線程
     */
    public void getNTPAsync(){
        synchronized (this) {
            if (mGetNtpAsync) {
                Loger.d(TAG, "getNTPTime: mNtpClientState is false");
                return ;
            }
            mGetNtpAsync = true;
            new Thread(new Runnable(){
                @Override
                public void run() {
                    while(!requestNtp()){
                        try{
                            Thread.sleep(5*1000);
                        }catch (Exception e){
                            Loger.d(TAG, "run: " + e.toString());
                        }
                    }
                }
            }).start();
            return;
        }
    }

    /**
     * 獲取ntp獲取狀態
     */
    public boolean getNtpState(){
        return mNtpClientState;
    }

    private boolean requestNtp(){
        boolean ret = false;
        String[] urlList;
        String NtpUrlList = "ntp1.aliyun.com, ntp2.aliyun.com, ntp3.aliyun.com, ntp4.aliyun.com, ntp5.aliyun.com, ntp6.aliyun.com, ntp7.aliyun.com," +
                "cn.pool.ntp.org, cn.ntp.org.cn, sg.pool.ntp.org, tw.pool.ntp.org, jp.pool.ntp.org, hk.pool.ntp.org, th.pool.ntp.org," +
                "time.windows.com, time.nist.gov, time.apple.com, time.asia.apple.com, dns1.synet.edu.cn, news.neu.edu.cn, dns.sjtu.edu.cn," +
                "dns2.synet.edu.cn, ntp.glnet.edu.cn, s2g.time.edu.cn, ntp-sz.chl.la, ntp.gwadar.cn, 3.asia.pool.ntp.org";

        ///TODO:獲取下發URL
        try{
            String url = ConfigManager.getInstance(SessionManager.getInstance().getAppContext()).getCfg(VPSConfigs.CONFIG_NTP_SERVER_URL);
            if (url != null && url.length() != 0){
                urlList = url.split(",",30);
                for(String ntpUrl : urlList){
                    ret = requestNtp(ntpUrl, 30000);
                    if(ret){
                        Loger.d(TAG, "requestNTP: request ntp time ok : " + ntpUrl);
                        return ret;
                    }
                    try{
                        Thread.sleep(2*1000);
                    }catch (Exception e){
                        Loger.e(TAG, "run: " + e.toString());
                    }
                }
            }
        }catch (Exception e){
            Loger.e(TAG, "requestNTP error: " + e.toString());
        }

        try{
            urlList = NtpUrlList.split(",",30);
            for(String ntpUrl : urlList){
                ret = requestNtp(ntpUrl, 30000);
                if(ret){
                    Loger.d(TAG, "requestNTP: request ntp time ok : " + ntpUrl);
                    return ret;
                }
                try{
                    Thread.sleep(2*1000);
                }catch (Exception e){
                    Loger.e(TAG, "run: " + e.toString());
                }
            }
        }catch (Exception e){
            Loger.e(TAG, "requestNTP error: " + e.toString());
        }
        return ret;
    }

    /**
     * 請求ntp
     * @param host
     * @param timeout
     * @return 是否獲取成功
     */
    private boolean requestNtp(String host, int timeout){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        long ntpTime = requestTime(host, timeout);
        Loger.d(TAG, "requestNtp: mNtpTime " + dateFormat.format(ntpTime));
        if (ntpTime == -1){
            return false;
        }
        Date date = new Date();
        //對比本地時間,差距1分鐘則說明沒準備好
        try{
            if((date.getTime()-ntpTime > 60*1000)||(date.getTime()-ntpTime < (-60*1000))){
                return false;
            }
        }catch (Exception e){
            Loger.e(TAG,"requestNtp error :" +e.toString());
        }
        mNtpClientState = true;
        return true;
    }

    /**
     * 請求ntp時間
     * @param host
     * @param timeout
     * @return 成功返回獲取時間 失敗返回 -1
     */
    private long requestTime(String host, int timeout) {
        DatagramSocket socket = null;
        InetAddress address = null;
        long ntpTime = -1;
        try {
            address = InetAddress.getByName(host);
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

            // get current time and write it to the request packet
            final long requestTime = System.currentTimeMillis();
            final long requestTicks = SystemClock.elapsedRealtime();
            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);

            socket.send(request);

            // read the response
            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            final long responseTicks = SystemClock.elapsedRealtime();
            final long responseTime = requestTime + (responseTicks - requestTicks);

            // extract the results
            final byte leap = (byte) ((buffer[0] >> 6) & 0x3);
            final byte mode = (byte) (buffer[0] & 0x7);
            final int stratum = (int) (buffer[1] & 0xff);
            final long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
            final long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
            final long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
            long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
            Loger.d(TAG, "Request time form ntp server success, " + address.toString() + " ,roundTripTime: " + roundTripTime);

            ntpTime = responseTime + clockOffset;
        } catch (Exception e) {
            Loger.e(TAG, "Request time from ntp server failed ,msg: " + e.getMessage());
            return ntpTime;
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
        return ntpTime;
    }

    /**
     * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
     */
    private long read32(byte[] buffer, int offset) {
        byte b0 = buffer[offset];
        byte b1 = buffer[offset + 1];
        byte b2 = buffer[offset + 2];
        byte b3 = buffer[offset + 3];

        // convert signed bytes to unsigned values
        int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
        int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
        int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
        int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

        return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;
    }

    /**
     * Reads the NTP time stamp at the given offset in the buffer and returns
     * it as a system time (milliseconds since January 1, 1970).
     */
    private long readTimeStamp(byte[] buffer, int offset) {
        long seconds = read32(buffer, offset);
        long fraction = read32(buffer, offset + 4);
        // Special case: zero means zero.
        if (seconds == 0 && fraction == 0) {
            return 0;
        }
        return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
    }

    /**
     * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
     * at the given offset in the buffer.
     */
    private void writeTimeStamp(byte[] buffer, int offset, long time) {
        // Special case: zero means zero.
        if (time == 0) {
            Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
            return;
        }

        long seconds = time / 1000L;
        long milliseconds = time - seconds * 1000L;
        seconds += OFFSET_1900_TO_1970;

        // write seconds in big endian format
        buffer[offset++] = (byte) (seconds >> 24);
        buffer[offset++] = (byte) (seconds >> 16);
        buffer[offset++] = (byte) (seconds >> 8);
        buffer[offset++] = (byte) (seconds >> 0);

        long fraction = milliseconds * 0x100000000L / 1000L;
        // write fraction in big endian format
        buffer[offset++] = (byte) (fraction >> 24);
        buffer[offset++] = (byte) (fraction >> 16);
        buffer[offset++] = (byte) (fraction >> 8);
        // low order bits should be random data
        buffer[offset++] = (byte) (Math.random() * 255.0);
    }

}

三、測試

有網絡時,能正常獲取到ntp時間。

無網絡時,獲取到的時間是1970年。

NTP地址好用的還是阿里的那幾個。

四、時區設置

獲取東八區時間

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
String snow = sdf.format(now); 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章