Ios

NTPを使用してJavaで時間を取得する



Use Ntp Get Time Java



NTPは、現在も使用されている(1985年以前の)最も古いネットワークプロトコルの1つです。もともとデラウェア大学のデイブミルズによって設計されたNTPは、現在もボランティアのグループとともにNTPを維持しています。

一般的なNTPサーバーリファレンス https://www.douban.com/note/171309770/



もちろん、北陽では、北陽を使ったNTPサーバーが最速ですが、インターネットでは見つかりません。上海交通大学のNTPサービスが推奨されており、他のネットワークからもアクセスできます。

2つのクラス。1つはNTPメッセージを解析するためのもので、もう1つは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 /** * Read the configuration in time.txt and return the difference between standard time and local time, in seconds * * @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)// More NTP time server reference notes } 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 <= 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 // I want to add 2208988800 here because the time I got was Greenwich Mean Time, so I have to change the time in the East Eight District, otherwise there will be an 8 hour time difference with Beijing time. // Validate NTP Response // IOException thrown if packet does not decode as expected. NtpMessage msg = new NtpMessage(incoming.getData()) 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) // } return localClockOffset } } 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 /** */ /** * 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

構成ファイルは単純です。




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