c# 获取服务器时间.doc_第1页
c# 获取服务器时间.doc_第2页
c# 获取服务器时间.doc_第3页
c# 获取服务器时间.doc_第4页
c# 获取服务器时间.doc_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C# 获取服务器时间 Posted on 2009-12-16 13:17 Pagan 阅读(1052) 评论(0) 编辑 收藏 代码 using System;using System.Net;using System.Net.Sockets;namespace SNTPTime / 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 (e.g. radio-clock) SecondaryReference, / 2-15 - secondary reference (via NTP or SNTP) Reserved / 16-255 - reserved / / SNTPTimeClient 的摘要说明。 / / Public class members: / / LeapIndicator - Warns of an impending leap second to be inserted/deleted in the last / minute of the current 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 _Stratum enum) / / PollInterval - Maximum interval between successive messages. / / Precision - Precision of the clock. / / RootDelay - Round trip time to the primary reference source. / / RootDispersion - Nominal error relative to the primary reference source. / / ReferenceID - Reference identifier (either a 4 character string or an IP address). / / ReferenceTimestamp - 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 connection. / / Connect - Connects to the time server and populates the data structure. / / IsResponseValid - Returns true if received data is valid and if comes from / a NTP-compliant time server. / / ToString - Returns a string representation of the object. / / - / 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 / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / |LI | VN |Mode | Stratum | Poll | Precision | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | Root Delay | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | Root Dispersion | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | Reference Identifier | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | | / | Reference Timestamp (64) | / | | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | | / | Originate Timestamp (64) | / | | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | | / | Receive Timestamp (64) | / | | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | | / | Transmit Timestamp (64) | / | | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | Key Identifier (optional) (32) | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | | / | | / | Message Digest (optional) (128) | / | | / | | / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / - / / 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 byteNTPDataLength; / Offset constants for timestamps in the data structure private const byte offReferenceID = 12; private const byte offReferenceTimestamp = 16; private const byte offOriginateTimestamp = 24; private const byte offReceiveTimestamp = 32; private const byte offTransmitTimestamp = 40; / Leap Indicator public _LeapIndicator LeapIndicator get / Isolate the two most significant bits byte val = (byte)(NTPData0 6); switch (val) case 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)(NTPData0 & 0x38) 3); return val; / Mode public _Mode Mode get / Isolate bits 0 - 3 byte val = (byte)(NTPData0 & 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; case 4: return _Mode.Server; case 5: return _Mode.Broadcast; / Stratum public _Stratum Stratum get byte val = (byte)NTPData1; 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, NTPData2); / Precision (in milliseconds) public double Precision get return (1000 * Math.Pow(2, NTPData3); / Root Delay (in milliseconds) public double RootDelay get int temp = 0; temp = 256 * (256 * (256 * NTPData4 + NTPData5) + NTPData6) + NTPData7; return 1000 * (double)temp) / 0x10000); / Root Dispersion (in milliseconds) public double RootDispersion get int temp = 0; temp = 256 * (256 * (256 * NTPData8 + NTPData9) + NTPData10) + NTPData11; return 1000 * (double)temp) / 0x10000); / Reference Identifier public string ReferenceID get string val = ; switch (Stratum) case _Stratum.Unspecified: case _Stratum.PrimaryReference: val += Convert.ToChar(NTPDataoffReferenceID + 0); val += Convert.ToChar(NTPDataoffReferenceID + 1); val += Convert.ToChar(NTPDataoffReferenceID + 2); val += Convert.ToChar(NTPDataoffReferenceID + 3); break; case _Stratum.SecondaryReference: / switch(VersionNumber) / / case 3: / Version 3, Reference ID is an IPv4 address / string Address = NTPDataoffReferenceID + 0.ToString() + . + / NTPDataoffReferenceID + 1.ToString() + . + / NTPDataoffReferenceID + 2.ToString() + . + / NTPDataoffReferenceID + 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 timestamp of last update / DateTime time = ComputeDate(GetMilliSeconds(offReferenceID); / / Take care of the time zone / long offset = TimeZone.CurrentTimeZone.GetUTCOffset(DateTime.Now); / TimeSpan offspan = TimeSpan.FromTicks(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 OriginateTimestamp get return ComputeDate(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 milliseconds, given the offset 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 + NTPDataoffset + i; for (int i = 4; i = 0; i-) NTPDataoffset + i = (byte)(temp % 256); temp = temp / 256; temp = fractpart; for (int i = 7; i = 4; i-) NTPDataoffset + i = (byte)(temp % 256); temp = temp / 256; / Initialize the NTPClient data private void Initialize() / Set version number to 4 and Mode to 3 (client) NTPData0 = 0x1B; / Initialize all other fields with 0 for (int i = 1; i 48; i+) NTPDatai = 0; / Initialize the transmit timestamp TransmitTimestamp = DateTime.Now; / Connect to the time server public void Connect() try IPAddress hostadd = IPAddress.Parse(TimeServer); I

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论