C # SNTP client takes SNTP time server code

xiaoxiao2021-03-06  69

code show as below:

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Threading; using System.IO; using System.Net.Sockets; using System. Using system.net;

namespace AutoExitWindows {// Leap indicator field values ​​public enum _LeapIndicator {NoWarning, // 0 - No warning LastMinute61, // 1 - Last minute has 61 seconds LastMinute59, // 2 - Last minute has 59 seconds Alarm // 3 - Alarm condition (Clock Not Synchronized)}

// Mode Field Values ​​Public Enum_Mode {SymmetricActive, // 1 - Symmetric Active SymmetricPassive, // 2 - Symmetric Pasive Client, // 3 - Client Server, // 4 - Server Broadcast, // 5 - Broadcast Unknown // 0 , 6, 7 - reserved}

// Stratum field values ​​public enum _Stratum {Unspecified, // 0 - unspecified or unavailable PrimaryReference, // 1 - primary reference (eg radio-clock) SecondaryReference, // 2-15 - secondary reference (via NTP or SNTP) Reserved / / 16-255 - reserved}

///

/// SNTPTIMECLIENT summary description.

/// // public class members:

///// Leapindicator - WARNS OF An Impeding Leap Second To BE INSERTED / DELETEDITED INTD DAY. (See The_Leapindicator Enum) /// /// VersionNumber - Version Number of the Protocol (3 or 4). ///// Mode - Returns Mode. (See the _Mode Enum) /// /// Stratum - Stratum of The Clock.

(See the_////////////////////// Precision - Precision of the Clock. /// // RootdeLay - Round Trip Time To The Primary Reference Source. ///// RootdisPersion - Nominal Error Relative To the primary reason Source. /// /// ReferenceID - Reference Identifier (Either A 4 Character String OR An IP Address). ///// ReferenceimeStamp - The Time At which the clock was last set or corrected /// /// OriginateTimestamp -. The time at which the request departed the client for the server /// /// ReceiveTimestamp -. The time at which the request arrived at the server /. // /// Transmit Timestamp - The time at which the reply departed the server for client /// /// RoundTripDelay -.. The time between the departure of request and arrival of reply /// /// LocalClockOffset - The offset Of The Local Clock Relative To The Primary Reference /// Source. // /// Initialize - Sets Up Data Structure and Prepares for Connectio n. // ///connect - Connects To The Time Server and Populates The Data Structure. ///// iResponsevalid - ReturiRes True If Received Data IS Valid and if Comes from /// A NTP-Compliant Time Server. ///// ////////// -------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------- / // structure of the standard ntp header (as described in RFC 2030) /// 1 2 3 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 /// - - - - - - - - - - - - - - - - & # 4

3; - /// | li | vn | mode | stratum | poll | precision | /// - - - - - - - - - - - - - - - - / / / | ROOT DELAY | /// - - - - - - - - - - - - - - - - - /// | root dispition | /// - - - - - - - - - - - - - - / / / | Reference Identifier | /// - - - - - - - - - - - - - - - - - /// | | /// | Reference TimeStamp (64) | /// | | | // - - - - - - - - - - - - - - - - - - /// | | /// | Originate TimeSTAMP (64) | /// | | ///

- - - - - - - - - - /// | | /// | Receive TimeStamp (64) | /// | | /// - - - - - - - - - - /// | | /// | Transmit timestamp (64) | /// | | /// - - - - - - - - - - - - - / / | Key Identifier (optional) (Optional) 32) | /// - - - - - - - - - - - - - - - - - - /// | | /// | | /// | Message Digest (Optional) (128) | /// | | /// | | /// - - - - - - - - &

# 43; - - - - - - - - ///// ------- -------------------------------------------------- -------------------- /// /// NTP TimeStamp Format (AS Described in RFC 2030) /// 1 2 3 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 /// - - - - - - - - - - - - - - - - - - /// | Seconds | /// - - - - - - - - - - - - - - - - - / / / | SECONDS FRAction (0-padded) | /// - - - - - - - - - - - - - - - - - - / / // /// public class SNTPTimeClient {// NTP Data Structure Length private const byte NTPDataLength = 48; // NTP Data Structure (as described in RFC 2030) byte [] NTPData = new byte [NTPDataLength]; / / Offset constants for timestamps in the data structure private const byte offreferenceId = 12; private cons T byte offreferenceimesTAMP = 16; private const byte = 24; private const byte offrecetimestamp = 32; private const byte offtransmitTimeStamp = 40;

// Leap indeicator public _LEAPIndicator Leapindicator {Get {// isolate the Two Most Significant Bits BYTE VAL = (Byte) (NTPDATA [0] >> 6); Switch (VAL) {cas 0: return_leapindicator.nowarning; case 1: return _LeapIndicator.LastMinute61; case 2: return _LeapIndicator.LastMinute59; case 3: default: return _LeapIndicator.Alarm;}}} // Version Number public byte VersionNumber {get {// Isolate bits 3 - 5 byte val = (byte) ( (NTPDATA [0] & 0x38) >> 3); Return Val;}}

// Mode public _mode mode {Get {// isolate bits 0 - 3 byte val = (byte) (NTPDATA [0] & 0x7); Switch (VAL) {Case 0: Case 6: Case 7: Default: return_mode. Unknown; case 1: return _mode.symmetricactive; case 2: return _mode.symmetricpassive; case 3: return_mode.client; cas 4: return_mode.broad;}}}

// stratum public _stratum stratum {get {byte val = (byte) NTPDATA [1]; if (val == 0) Return_stratum.unspecified; else if (val == 1) Return_stratum.primaryreference; Else IF (VAL < = 15) Return _stratum.secondaryreference; else return_stratum.reserved;}}

// Poll Interval Public Uint Pollinterval {Get {Return (UINT) Math.Round (Math.Pow (2, NTPData [2]));}}

// precision (in milliseconds) public double precision {get {return (1000 * math.pow (2, ntpdata [3]));}}

// root delay (in milliseconds) public double rootdelay {get {int Temp = 0; Temp = 256 * (256 * (256 * ntpdata [4] ntpdata [5]) NTPDATA [6]) NTPDATA [7] Return 1000 * ((Double) Temp) / 0x10000);}}} // root dispersion (in milliseconds) public double rootdispersion {get {int Temp = 0; Temp = 256 * (256 * (256 * ntpdata [8] NTPDATA [9]) NTPDATA [10]) NTPDATA [11]; RETURN 1000 * ((Double) TEMP) / 0x10000);}}

// Reference Identifier public string ReferenceID {get {string val = ""; switch (Stratum) {case _Stratum.Unspecified: case _Stratum.PrimaryReference: val = Convert.ToChar (NTPData [offReferenceID 0]); val = Convert .ToChar (NTPData [offReferenceID 1]); val = Convert.ToChar (NTPData [offReferenceID 2]); val = Convert.ToChar (NTPData [offReferenceID 3]); break; case _Stratum.SecondaryReference: switch ( VersionNumber) {case 3: // version 3, reference id is an ipv4 address string address = ntpdata [offreferenceid 0] .tostring () " NTPData [offreferenceid 1] .tostring () ". 1 "." NTPData [offReferenceID 2] .ToString () NTPData [offReferenceID 3] .ToString (); try {IPAddress RefAddr = new IPAddress (Address); IPHostEntry Host = DNS.GetHostByAddr (RefAddr); val = Host .Hostname "(" Address ")";} catch (exception) {val = "n / a";} Break; case 4: // version 4, reference id is the time = computedate (offmilliseconds (offreference); // Take Care of the time zone long offset = timezone.currenttimezone.getutcoffset (datetime.now); timeespan offspan = timeespan.fromtics (offset); val = (time offspan) .tostring (); Break;

DEFAULT: VAL = "N / A";} Break;} Return Val;}}

// Reference Timestamp public DateTime ReferenceTimestamp {get {DateTime time = ComputeDate (GetMilliSeconds (offReferenceTimestamp)); // Take care of the time zone long offset = Convert.ToInt64 (TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now)); TimeSpan offspan = Timespan.fromticks (offset); Return Time Offspan;}}

// Originate TimeStamp Public DateTime Orig InsputimeStamp {Get {Return Computeate (GETMILLISECONDS (OfforiginateTimeStamp);}}

// Receive Timestamp public DateTime ReceiveTimestamp {get {DateTime time = ComputeDate (GetMilliSeconds (offReceiveTimestamp)); // Take care of the time zone long offset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now) .Ticks; TimeSpan offspan = TimeSpan. Fromticks (offset); Return Time Offspan;}}

// Transmit Timestamp public DateTime TransmitTimestamp {get {DateTime time = ComputeDate (GetMilliSeconds (offTransmitTimestamp)); // Take care of the time zone long offset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now) .Ticks; TimeSpan offspan = TimeSpan. FROMTICKS (OFFSET); Return Time Offspan;} set {setdate (offtransmitTimeStamp, Value);}}

// Reception Timestamp public DateTime ReceptionTimestamp; // Round trip delay (in milliseconds) public int RoundTripDelay {get {TimeSpan span = (ReceiveTimestamp - OriginateTimestamp) (ReceptionTimestamp - TransmitTimestamp); return (int) span.TotalMilliseconds;}}

// Local clock offset (in milliseconds) public int LocalClockOffset {get {TimeSpan span = (ReceiveTimestamp - OriginateTimestamp) - (ReceptionTimestamp - TransmitTimestamp); return (int) (span.TotalMilliseconds / 2);}} // Compute date, given the number of milliseconds since January 1, 1900 private DateTime ComputeDate (ulong milliseconds) {TimeSpan span = TimeSpan.FromMilliseconds ((double) milliseconds); DateTime time = new DateTime (1900, 1, 1); time = span; return time }

// compute the number of a 8-byte array private ulong getmilliseconds (byte offset) {ulong intpart = 0, FractPART = 0;

For (int i = 0; i <= 3; i ) {INTPART = 256 * intPart NTPART I];} for (int i = 4; i <= 7; i ) {fractpart = 256 * FractPart NTPDATA [OFFSET I];} Ulong MilliseConds = INTPART * 1000 (FractPART * 1000) / 0x100000000L; Return MilliseConds;

// compute the 8-byte array, given the date private void setdate (byte offset, datetime date) {ulong intpart = 0, fractpart = 0; DateTime Startofector = New DateTime (1900, 1, 1, 0, 0, 0) ; // January 1, 1900 12:00 AM

Ulong Milliseconds = (Ulong) .totalmilliseConds; INTPART = MilliseConds / 1000; FractPART = ((MilliseConds% 1000) * 0x100000000L) / 1000;

Ulong Temp = INTPART; for (int i = 3; i> = 0; I -) {ntpdata [offset i] = (byte) (Temp% 256); temp = temp / 256;}

Temp = fractpart; for (int i = 7; i> = 4; I -) {ntpdata [offset i] = (byte) (Temp% 256); Temp = Temp / 256;}} // Initialize the NtpClient Data Private Void Initialize () {// set version number to 4 and mode to 3 (client) NTPDATA [0] = 0x1b; // initialize all osfields with 0 for (int i = 1; i <48; i ) { NTPDATA [I] = 0;} // Initialize the Transmit TimeStamp TransmitTimeStamp = DateTime.now;}

// Connect To the Time Server Public Void Connect () {ipaddress Hostadd = ipaddress.parse (TimeServer); IpendPoint Ephost = New IpendPoint (Hostadd, Convert.Toint32);

UdpClient TimeSocket = new UdpClient (); TimeSocket.Connect (EPhost); Initialize (); TimeSocket.Send (NTPData, NTPData.Length); NTPData = TimeSocket.Receive (ref EPhost); if {throw new (IsResponseValid ()!) Exception ("INVALID RESPONSE FROM" TIMESERVER);} receivedTimeStamp = DateTime.now;} catch (socketexception e) {throw new exception (E.MESSAGE);}}

// Check if The Response from Server Is Valid Public Bool IsResponsevalid () {if (NTPData.Length

// converts the object to string public override string Tostring () {string Str;

str = "Leap Indicator:"; switch (LeapIndicator) {case _LeapIndicator.NoWarning: str = "No warning"; break; case _LeapIndicator.LastMinute61: str = "Last minute has 61 seconds"; break; case _LeapIndicator.LastMinute59 : Str = "Last Minute Has 59 Seconds"; Break; Case_Leapindicator.alarm: Str = "Alarm Condition (Clock Not Synchronized)"; Break;} Str = "/ R / NVERSION Number:" VersionNumber.toString () "/ r / n"; Str = "Mode:"; switch (mode) {case _mode.unknown: str = "unknown"; break; case _mode.symmetricactive: str = "Symmetric Active"; Break; case_mode.symmetricpassive: Str = "Symmetric Pasive"; Break; Case_Mode.Client: Str = "Client"; Break; Case_Mode.Server: Str = "Server"; Break; Case_Mode.Broadcast: Str = "Broadcast"; Break;} Str = "/ r / nstratum:"; switch (stratum) {case _stratum.unspecified: case _stratum.reserved: Str = "Unspecified"; break; case _Stratum.PrimaryReference: str = "Primary Reference"; break; case _Stratum.SecondaryReference: str = "Secondary Reference"; break;} str = "/ r / nLocal time:" TransmitTimestamp .Tostring (); str = "/ r / nprecision:" Precision.toString () "ms"; str = "/ r / npoll interval:" PollInterVal.Tostring () "s";

Str = "/ r / nreference ID:" ReferenceId.tostring (); str = "/ r / nRoot Dispersion:" rootdispersion.tostring () "ms"; str = "/ r / nRound Trip delay : " RoundtripDelay.toString () " MS "; STR =" / R / NLOCAL Clock Offset: " localclockoffset.toString () " ms "; str =" / r / n "; return str;}

// The Url of the Time Server We're Connecting To Private String Timeserver; Private String Timeport;

Public SNTPTIMECLIENT (String Host, String Port) {// // Todo: Add Constructor Logic // TimeServer = Host; TimeServer = Port;

}

Call

SNTPTimeClient Client = New SNTPTIMECLIENT (Server, Port); Client.Connect (); string strate = client.toString (); console.write (strTest);

转载请注明原文地址:https://www.9cbs.com/read-97847.html

New Post(0)