在Java下使用NTP获取时间

您所在的位置:网站首页 阿里云授时 在Java下使用NTP获取时间

在Java下使用NTP获取时间

2024-07-08 19:02:43| 来源: 网络整理| 查看: 265

NTP是仍在使用中的最古老的网络协议之一(在1985年前开始)。NTP最初由德拉瓦州大学的Dave Mills设计,他与一群志愿者仍在维护NTP。

常用的NTP服务器参考https://www.douban.com/note/171309770/

身在北邮,当然是使用北邮的NTP服务器最快,但是在外网发现访问不到。推荐上海交通大学的NTP服务,在其他网络仍然能够访问到。

两个类,一个用于解析NTP消息,另一个根据配置文件使用NTP协议获取时间。由于是JavaEE项目,文件路径使用的ServletActionContext的路径。如果是一般Java项目写成配置所在路径即可。

package monitor.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; 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; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.apache.struts2.ServletActionContext; public class NtpUtil { static final String configFile = ServletActionContext.getServletContext() .getRealPath( File.separator + "WEB-INF" + File.separator + "time.txt"); static String ntpServer = null; static Integer retry = null; static Integer port = null; static Integer timeout = null; /** * 读取time.txt中的配置,返回标准时间与本地时间的差值,单位秒 * * @return */ public static Double localClockOffset() { if (ntpServer == null) { Properties props = new Properties(); try { props.load(new FileInputStream(new File(configFile))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ntpServer = props.getProperty("server"); retry = Integer.parseInt(props.getProperty("retry")); port = Integer.parseInt(props.getProperty("port")); timeout = Integer.parseInt(props.getProperty("timeout")); } // get the address and NTP address request // InetAddress ipv4Addr = null; try { ipv4Addr = InetAddress.getByName(ntpServer);// 更多NTP时间服务器参考附注 } catch (UnknownHostException e1) { e1.printStackTrace(); } int serviceStatus = -1; DatagramSocket socket = null; long responseTime = -1; double localClockOffset = 0; try { socket = new DatagramSocket(); socket.setSoTimeout(timeout); // will force the // InterruptedIOException for (int attempts = 0; attempts > 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 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 pointer 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 ""; } }

配置文件很简单:

server = ntp.sjtu.edu.cn retry = 2 port = 123 timeout = 3000



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭