Obtain security time

Source: Internet
Author: User
Tags sntp server

The meaning of "Security Time" mostly lies in information security, and it can also provide users with more accurate time services. This article mainly discusses how to use the Network Time Protocol (NTP) for Network timing (Time Signal ). NTP can adapt to network latency and maximize the accuracy of the time obtained by users. For the synchronization algorithm and principle, see here (clock synchronization algorithm ).


Before writing this article, I originally wanted to use the time data provided by the National Time Service Center. However, due to my ignorance, I failed to find the relevant time service interface on the official website, so I used NTP for Network Time Service globally.


Get time: According to RFC 2030 (outdated, latest RFC 5905), NTP can use UDP protocol to work on IPv4 and IPv6. By sending a request to the NTP server, the server returns you a time response. The data packet format is defined in section 4. NTP message format in RFC 2030.

The section "5. SNTP client operations" describes how users send requests to the server. Because "a unicast or anycast client initializes the NTP message header, sends the request to the server and strips the time of day from the transmit Timestamp Field of the reply. for this purpose, all of the NTP header fields shown can be set to 0, cannot the first octet and (optional) Transmit timestamp fields. in the first octet, the Li field is set to 0 (no warning) and the Mode Field is set 3 (client ). the VN field must agree with the version number of the NTP/SNTP server ", so we can simply set the data of the first byte to 0x1b (0001 1011), that is: li = 0, vn = 4, mode = 3. All other data is set to zero.

Next, the server will return related packets. The time calculation formula given by RFC 2030: D = (T4-t1)-(T2-T3) t = (T2-t1) + (T3-T4)/2, in the end, we can get a relatively accurate local time. The simplified formula is approximately (server timespan + local wait time/2 ).


Beat time: A thread takes the initiative to obtain the time from the server every other security cycle, or gets the time from the server when the local machine finds that the time is too high. If an exception occurs when obtaining the time, select the next address from the list as the server address.


Implementation Code:

Public static class safedatetime {const int safe_cycle = 7200; const int cycle_interval = 500; const int allow_diff = 650; readonly static string [] _ hosts = new [] {// list of NTP servers "ntp.sjtu.edu.cn", // Shanghai Jiao Tong University "time-nw.nist.gov", // Microsoft, Redmond, washington "s1a.time.edu.cn", // Beijing University of Posts and Telecommunications "time-b.timefreq.bldrdoc.gov", // NIST, Boulder, Colorado "", // Fukuoka University of Japan }; readonly static ipendpoint [] _ EPS = NULL; static int _ sindex = 0; static int _ safecycle = 0; static bool _ ongetingtime = false; static datetime _ localutctime; static datetime _ networkutctime; static safedatetime () {// convert hosts to ipendpoints // _ EPS = _ hosts. select (S => (ienumerable <IPaddress>) DNS. gethostaddresses (s )). aggregate (x, y) => X. concat (y )). select (S => New ipendpoint (S, 123 )). toarray (); var list = new list <ipendpoint> (); foreach (VAR host in _ hosts) {try {foreach (var ip in DNS. gethostaddresses (host) list. add (New ipendpoint (IP, 123);} catch {}}_ EPS = List. toarray (); New thread () => {var currentthread = thread. currentthread; currentthread. priority = threadpriority. highest; currentthread. isbackground = true; datetime lastsafetime = datetime. minvalue; datetime currentsafetime = datetime. minvalue; while (true) {If (_ safecycle -- allow_diff) // out of threshold asyncnetworkutctime ();} lastsafetime = getsafedatetime (); thread. sleep (cycle_interval );}}). start ();} Private Static datetime getnetworkutctime (ipendpoint EP) {socket S = new socket (addressfamily. interNetwork, sockettype. dgram, protocoltype. UDP); S. connect (EP); byte [] ntpdata = new byte [48]; // RFC 2030 ntpdata [0] = 0x1b; // For (INT I = 1; i> 1); var timespan = timespan. fromticks (ticks); var datetime = new datetime (1900, 1, 1) + timespan; return datetime; // return UTC time} Private Static long parseraw (byte [] ntpdata, int offsettransmittime) {ulong intpart = 0; ulong fractpart = 0; For (INT I = 0; I

Thread Security: Updating _ networkutctime and _ localutctime may cause thread insecurity, but the probability of conflict is extremely low. You can add a thread lock as appropriate.


PS: For more information, see the source code and RFC documentation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.