首页 > 代码库 > 通过NTP协议进行时间同步
通过NTP协议进行时间同步
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 GetNetworkTime(); 6 } 7 8 public static DateTime GetNetworkTime() 9 {10 //default Windows time server11 const string ntpServer = "clock.via.net";12 13 // NTP message size - 16 bytes of the digest (RFC 2030)14 var ntpData = http://www.mamicode.com/new byte[48];15 16 //Setting the Leap Indicator, Version Number and Mode values17 ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)18 19 var addresses = Dns.GetHostEntry(ntpServer).AddressList;20 21 //The UDP port number assigned to NTP is 12322 var ipEndPoint = new IPEndPoint(addresses[0], 123);23 //NTP uses UDP24 var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);25 26 socket.Connect(ipEndPoint);27 28 //Stops code hang if NTP is blocked29 socket.ReceiveTimeout = 3000;30 31 socket.Send(ntpData);32 socket.Receive(ntpData);33 socket.Close();34 35 //Offset to get to the "Transmit Timestamp" field (time at which the reply 36 //departed the server for the client, in 64-bit timestamp format."37 const byte serverReplyTime = 40;38 39 //Get the seconds part40 ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);41 42 //Get the seconds fraction43 ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);44 45 //Convert From big-endian to little-endian46 intPart = SwapEndianness(intPart);47 fractPart = SwapEndianness(fractPart);48 49 var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);50 51 //**UTC** time52 var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);53 54 return networkDateTime.ToLocalTime();55 }56 57 // stackoverflow.com/a/3294698/16267158 static uint SwapEndianness(ulong x)59 {60 return (uint)(((x & 0x000000ff) << 24) +61 ((x & 0x0000ff00) << 8) +62 ((x & 0x00ff0000) >> 8) +63 ((x & 0xff000000) >> 24));64 }65 }
通过NTP协议进行时间同步
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。