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 server 11 const string ntpServer = "clock.via.net"; 12 13 // NTP message size - 16 bytes of the digest (RFC 2030) 14 var ntpData = new byte[48]; 15 16 //Setting the Leap Indicator, Version Number and Mode values 17 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 123 22 var ipEndPoint = new IPEndPoint(addresses[0], 123); 23 //NTP uses UDP 24 var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 25 26 socket.Connect(ipEndPoint); 27 28 //Stops code hang if NTP is blocked 29 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 part 40 ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime); 41 42 //Get the seconds fraction 43 ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4); 44 45 //Convert From big-endian to little-endian 46 intPart = SwapEndianness(intPart); 47 fractPart = SwapEndianness(fractPart); 48 49 var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L); 50 51 //**UTC** time 52 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/162671 58 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 }
.net代码实现
时间: 2024-10-07 10:03:02