从NTP服务器获取时间同步客户端:
1 import java.io.IOException; 2 import java.io.InterruptedIOException; 3 import java.net.ConnectException; 4 import java.net.DatagramPacket; 5 import java.net.DatagramSocket; 6 import java.net.InetAddress; 7 import java.net.NoRouteToHostException; 8 import java.net.UnknownHostException; 9 10 public class TestNtp{ 11 12 public static void main(String[] args){ 13 int retry = 2; 14 int port = 123; 15 int timeout = 3000; 16 17 // get the address and NTP address request 18 // 19 InetAddress ipv4Addr = null; 20 try { 21 ipv4Addr = InetAddress.getByName("203.117.180.36");//更多NTP时间服务器参考附注 22 } catch (UnknownHostException e1) { 23 e1.printStackTrace(); 24 } 25 26 int serviceStatus = -1; 27 DatagramSocket socket = null; 28 long responseTime = -1; 29 try { 30 socket = new DatagramSocket(); 31 socket.setSoTimeout(timeout); // will force the 32 // InterruptedIOException 33 34 for (int attempts = 0; attempts <= retry && serviceStatus != 1; attempts++) { 35 try { 36 // Send NTP request 37 // 38 byte[] data = new NtpMessage().toByteArray(); 39 DatagramPacket outgoing = new DatagramPacket(data, data.length, ipv4Addr, port); 40 long sentTime = System.currentTimeMillis(); 41 socket.send(outgoing); 42 43 // Get NTP Response 44 // 45 // byte[] buffer = new byte[512]; 46 DatagramPacket incoming = new DatagramPacket(data, data.length); 47 socket.receive(incoming); 48 responseTime = System.currentTimeMillis() - sentTime; 49 double destinationTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0; 50 //这里要加2208988800,是因为获得到的时间是格林尼治时间,所以要变成东八区的时间,否则会与与北京时间有8小时的时差 51 52 // Validate NTP Response 53 // IOException thrown if packet does not decode as expected. 54 NtpMessage msg = new NtpMessage(incoming.getData()); 55 double localClockOffset = ((msg.receiveTimestamp - msg.originateTimestamp) + (msg.transmitTimestamp - destinationTimestamp)) / 2; 56 57 System.out.println("poll: valid NTP request received the local clock offset is " + localClockOffset + ", responseTime= " + responseTime + "ms"); 58 System.out.println("poll: NTP message : " + msg.toString()); 59 serviceStatus = 1; 60 } catch (InterruptedIOException ex) { 61 // Ignore, no response received. 62 } 63 } 64 } catch (NoRouteToHostException e) { 65 System.out.println("No route to host exception for address: " + ipv4Addr); 66 } catch (ConnectException e) { 67 // Connection refused. Continue to retry. 68 e.fillInStackTrace(); 69 System.out.println("Connection exception for address: " + ipv4Addr); 70 } catch (IOException ex) { 71 ex.fillInStackTrace(); 72 System.out.println("IOException while polling address: " + ipv4Addr); 73 } finally { 74 if (socket != null) 75 socket.close(); 76 } 77 78 // Store response time if available 79 // 80 if (serviceStatus == 1) { 81 System.out.println("responsetime=="+responseTime); 82 } 83 84 85 } 86 }
协议解析模型
1 import java.text.DecimalFormat;
2 import java.text.SimpleDateFormat;
3 import java.util.Date;
4
5 public class NtpMessage {
6 /** *//**
7 * This is a two-bit code warning of an impending leap second to be
8 * inserted/deleted in the last minute of the current day. It''s values may
9 * be as follows:
10 *
11 * Value Meaning ----- ------- 0 no warning 1 last minute has 61 seconds 2
12 * last minute has 59 seconds) 3 alarm condition (clock not synchronized)
13 */
14 public byte leapIndicator = 0;
15
16 /** *//**
17 * This value indicates the NTP/SNTP version number. The version number is 3
18 * for Version 3 (IPv4 only) and 4 for Version 4 (IPv4, IPv6 and OSI). If
19 * necessary to distinguish between IPv4, IPv6 and OSI, the encapsulating
20 * context must be inspected.
21 */
22 public byte version = 3;
23
24 /** *//**
25 * This value indicates the mode, with values defined as follows:
26 *
27 * Mode Meaning ---- ------- 0 reserved 1 symmetric active 2 symmetric
28 * passive 3 client 4 server 5 broadcast 6 reserved for NTP control message
29 * 7 reserved for private use
30 *
31 * In unicast and anycast modes, the client sets this field to 3 (client) in
32 * the request and the server sets it to 4 (server) in the reply. In
33 * multicast mode, the server sets this field to 5 (broadcast).
34 */
35 public byte mode = 0;
36
37 /** *//**
38 * This value indicates the stratum level of the local clock, with values
39 * defined as follows:
40 *
41 * Stratum Meaning ---------------------------------------------- 0
42 * unspecified or unavailable 1 primary reference (e.g., radio clock) 2-15
43 * secondary reference (via NTP or SNTP) 16-255 reserved
44 */
45 public short stratum = 0;
46
47 /** *//**
48 * This value indicates the maximum interval between successive messages, in
49 * seconds to the nearest power of two. The values that can appear in this
50 * field presently range from 4 (16 s) to 14 (16284 s); however, most
51 * applications use only the sub-range 6 (64 s) to 10 (1024 s).
52 */
53 public byte pollInterval = 0;
54
55 /** *//**
56 * This value indicates the precision of the local clock, in seconds to the
57 * nearest power of two. The values that normally appear in this field
58 * range from -6 for mains-frequency clocks to -20 for microsecond clocks
59 * found in some workstations.
60 */
61 public byte precision = 0;
62
63 /** *//**
64 * This value indicates the total roundtrip delay to the primary reference
65 * source, in seconds. Note that this variable can take on both positive and
66 * negative values, depending on the relative time and frequency offsets.
67 * The values that normally appear in this field range from negative values
68 * of a few milliseconds to positive values of several hundred milliseconds.
69 */
70 public double rootDelay = 0;
71
72 /** *//**
73 * This value indicates the nominal error relative to the primary reference
74 * source, in seconds. The values that normally appear in this field range
75 * from 0 to several hundred milliseconds.
76 */
77 public double rootDispersion = 0;
78
79 /** *//**
80 * This is a 4-byte array identifying the particular reference source. In
81 * the case of NTP Version 3 or Version 4 stratum-0 (unspecified) or
82 * stratum-1 (primary) servers, this is a four-character ASCII string, left
83 * justified and zero padded to 32 bits. In NTP Version 3 secondary servers,
84 * this is the 32-bit IPv4 address of the reference source. In NTP Version 4
85 * secondary servers, this is the low order 32 bits of the latest transmit
86 * timestamp of the reference source. NTP primary (stratum 1) servers should
87 * set this field to a code identifying the external reference source
88 * according to the following list. If the external reference is one of
89 * those listed, the associated code should be used. Codes for sources not
90 * listed can be contrived as appropriate.
91 *
92 * Code External Reference Source ---- ------------------------- LOCL
93 * uncalibrated local clock used as a primary reference for a subnet without
94 * external means of synchronization PPS atomic clock or other
95 * pulse-per-second source individually calibrated to national standards
96 * ACTS NIST dialup modem service USNO USNO modem service PTB PTB (Germany)
97 * modem service TDF Allouis (France) Radio 164 kHz DCF Mainflingen
98 * (Germany) Radio 77.5 kHz MSF Rugby (UK) Radio 60 kHz WWV Ft. Collins (US)
99 * Radio 2.5, 5, 10, 15, 20 MHz WWVB Boulder (US) Radio 60 kHz WWVH Kaui
100 * Hawaii (US) Radio 2.5, 5, 10, 15 MHz CHU Ottawa (Canada) Radio 3330,
101 * 7335, 14670 kHz LORC LORAN-C radionavigation system OMEG OMEGA
102 * radionavigation system GPS Global Positioning Service GOES Geostationary
103 * Orbit Environment Satellite
104 */
105 public byte[] referenceIdentifier = { 0, 0, 0, 0 };
106
107 /** *//**
108 * This is the time at which the local clock was last set or corrected, in
109 * seconds since 00:00 1-Jan-1900.
110 */
111 public double referenceTimestamp = 0;
112
113 /** *//**
114 * This is the time at which the request departed the client for the server,
115 * in seconds since 00:00 1-Jan-1900.
116 */
117 public double originateTimestamp = 0;
118
119 /** *//**
120 * This is the time at which the request arrived at the server, in seconds
121 * since 00:00 1-Jan-1900.
122 */
123 public double receiveTimestamp = 0;
124
125 /** *//**
126 * This is the time at which the reply departed the server for the client,
127 * in seconds since 00:00 1-Jan-1900.
128 */
129 public double transmitTimestamp = 0;
130
131 /** *//**
132 * Constructs a new NtpMessage from an array of bytes.
133 */
134 public NtpMessage(byte[] array) {
135 // See the packet format diagram in RFC 2030 for details
136 leapIndicator = (byte) ((array[0] >> 6) & 0x3);
137 version = (byte) ((array[0] >> 3) & 0x7);
138 mode = (byte) (array[0] & 0x7);
139 stratum = unsignedByteToShort(array[1]);
140 pollInterval = array[2];
141 precision = array[3];
142
143 rootDelay = (array[4] * 256.0) + unsignedByteToShort(array[5]) + (unsignedByteToShort(array[6]) / 256.0) + (unsignedByteToShort(array[7]) / 65536.0);
144
145 rootDispersion = (unsignedByteToShort(array[8]) * 256.0) + unsignedByteToShort(array[9]) + (unsignedByteToShort(array[10]) / 256.0) + (unsignedByteToShort(array[11]) / 65536.0);
146
147 referenceIdentifier[0] = array[12];
148 referenceIdentifier[1] = array[13];
149 referenceIdentifier[2] = array[14];
150 referenceIdentifier[3] = array[15];
151
152 referenceTimestamp = decodeTimestamp(array, 16);
153 originateTimestamp = decodeTimestamp(array, 24);
154 receiveTimestamp = decodeTimestamp(array, 32);
155 transmitTimestamp = decodeTimestamp(array, 40);
156 }
157
158 /** *//**
159 * Constructs a new NtpMessage
160 */
161 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) {
162 // ToDo: Validity checking
163 this.leapIndicator = leapIndicator;
164 this.version = version;
165 this.mode = mode;
166 this.stratum = stratum;
167 this.pollInterval = pollInterval;
168 this.precision = precision;
169 this.rootDelay = rootDelay;
170 this.rootDispersion = rootDispersion;
171 this.referenceIdentifier = referenceIdentifier;
172 this.referenceTimestamp = referenceTimestamp;
173 this.originateTimestamp = originateTimestamp;
174 this.receiveTimestamp = receiveTimestamp;
175 this.transmitTimestamp = transmitTimestamp;
176 }
177
178 /** *//**
179 * Constructs a new NtpMessage in client -> server mode, and sets the
180 * transmit timestamp to the current time.
181 */
182 public NtpMessage() {
183 // Note that all the other member variables are already set with
184 // appropriate default values.
185 this.mode = 3;
186 this.transmitTimestamp = (System.currentTimeMillis() / 1000.0) + 2208988800.0;
187 }
188
189 /** *//**
190 * This method constructs the data bytes of a raw NTP packet.
191 */
192 public byte[] toByteArray() {
193 // All bytes are automatically set to 0
194 byte[] p = new byte[48];
195
196 p[0] = (byte) (leapIndicator << 6 | version << 3 | mode);
197 p[1] = (byte) stratum;
198 p[2] = (byte) pollInterval;
199 p[3] = (byte) precision;
200
201 // root delay is a signed 16.16-bit FP, in Java an int is 32-bits
202 int l = (int) (rootDelay * 65536.0);
203 p[4] = (byte) ((l >> 24) & 0xFF);
204 p[5] = (byte) ((l >> 16) & 0xFF);
205 p[6] = (byte) ((l >> 8) & 0xFF);
206 p[7] = (byte) (l & 0xFF);
207
208 // root dispersion is an unsigned 16.16-bit FP, in Java there are no
209 // unsigned primitive types, so we use a long which is 64-bits
210 long ul = (long) (rootDispersion * 65536.0);
211 p[8] = (byte) ((ul >> 24) & 0xFF);
212 p[9] = (byte) ((ul >> 16) & 0xFF);
213 p[10] = (byte) ((ul >> 8) & 0xFF);
214 p[11] = (byte) (ul & 0xFF);
215
216 p[12] = referenceIdentifier[0];
217 p[13] = referenceIdentifier[1];
218 p[14] = referenceIdentifier[2];
219 p[15] = referenceIdentifier[3];
220
221 encodeTimestamp(p, 16, referenceTimestamp);
222 encodeTimestamp(p, 24, originateTimestamp);
223 encodeTimestamp(p, 32, receiveTimestamp);
224 encodeTimestamp(p, 40, transmitTimestamp);
225
226 return p;
227 }
228
229 /** *//**
230 * Returns a string representation of a NtpMessage
231 */
232 public String toString() {
233 String precisionStr = new DecimalFormat("0.#E0").format(Math.pow(2, precision));
234 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);
235 }
236
237 /** *//**
238 * Converts an unsigned byte to a short. By default, Java assumes that a
239 * byte is signed.
240 */
241 public static short unsignedByteToShort(byte b) {
242 if ((b & 0x80) == 0x80)
243 return (short) (128 + (b & 0x7f));
244 else
245 return (short) b;
246 }
247
248 /** *//**
249 * Will read 8 bytes of a message beginning at pointer
and
250 * return it as a double, according to the NTP 64-bit timestamp format.
251 */
252 public static double decodeTimestamp(byte[] array, int pointer) {
253 double r = 0.0;
254
255 for (int i = 0; i < 8; i++) {
256 r += unsignedByteToShort(array[pointer + i]) * Math.pow(2, (3 - i) * 8);
257 }
258
259 return r;
260 }
261
262 /** *//**
263 * Encodes a timestamp in the specified position in the message
264 */
265 public static void encodeTimestamp(byte[] array, int pointer, double timestamp) {
266 // Converts a double into a 64-bit fixed point
267 for (int i = 0; i < 8; i++) {
268 // 2^24, 2^16, 2^8, .. 2^-32
269 double base = Math.pow(2, (3 - i) * 8);
270
271 // Capture byte value
272 array[pointer + i] = (byte) (timestamp / base);
273
274 // Subtract captured value from remaining total
275 timestamp = timestamp - (double) (unsignedByteToShort(array[pointer + i]) * base);
276 }
277
278 // From RFC 2030: It is advisable to fill the non-significant
279 // low order bits of the timestamp with a random, unbiased
280 // bitstring, both to avoid systematic roundoff errors and as
281 // a means of loop detection and replay detection.
282 array[7] = (byte) (Math.random() * 255.0);
283 }
284
285 /** *//**
286 * Returns a timestamp (number of seconds since 00:00 1-Jan-1900) as a
287 * formatted date/time string.
288 */
289 public static String timestampToString(double timestamp) {
290 if (timestamp == 0)
291 return "0";
292
293 // timestamp is relative to 1900, utc is used by Java and is relative
294 // to 1970
295 double utc = timestamp - (2208988800.0);
296
297 // milliseconds
298 long ms = (long) (utc * 1000.0);
299
300 // date/time
301 String date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date(ms));
302
303 // fraction
304 double fraction = timestamp - ((long) timestamp);
305 String fractionSting = new DecimalFormat(".000000").format(fraction);
306
307 return date + fractionSting;
308 }
309
310 /** *//**
311 * Returns a string representation of a reference identifier according to
312 * the rules set out in RFC 2030.
313 */
314 public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) {
315 // From the RFC 2030:
316 // In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)
317 // or stratum-1 (primary) servers, this is a four-character ASCII
318 // string, left justified and zero padded to 32 bits.
319 if (stratum == 0 || stratum == 1) {
320 return new String(ref);
321 }
322
323 // In NTP Version 3 secondary servers, this is the 32-bit IPv4
324 // address of the reference source.
325 else if (version == 3) {
326 return unsignedByteToShort(ref[0]) + "." + unsignedByteToShort(ref[1]) + "." + unsignedByteToShort(ref[2]) + "." + unsignedByteToShort(ref[3]);
327 }
328
329 // In NTP Version 4 secondary servers, this is the low order 32 bits
330 // of the latest transmit timestamp of the reference source.
331 else if (version == 4) {
332 return "" + ((unsignedByteToShort(ref[0]) / 256.0) + (unsignedByteToShort(ref[1]) / 65536.0) + (unsignedByteToShort(ref[2]) / 16777216.0) + (unsignedByteToShort(ref[3]) / 4294967296.0));
333 }
334
335 return "";
336 }
337 }
结果:
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上几十毫秒),且可介由加密确认的方式来防止恶毒的协议攻击。