>從NTP服務器中檢索具有C#
的準確時間此C#代碼段演示瞭如何從網絡時間協議(NTP)服務器中獲取當前時間:
<code class="language-csharp">public static DateTime GetNetworkTime() { // Default NTP server address string ntpServer = "time.windows.com"; // NTP packet size byte[] ntpData = new byte[48]; // Configure NTP packet ntpData[0] = 0x1B; // Leap indicator, version, and client mode // Resolve NTP server IP address IPAddress[] addresses = Dns.GetHostAddresses(ntpServer); // Create endpoint for NTP server (port 123) IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { socket.Connect(ipEndPoint); // Set receive timeout socket.ReceiveTimeout = 3000; socket.Send(ntpData); socket.Receive(ntpData); socket.Close(); } // Offset for server reply time in the NTP packet const int serverReplyTimeOffset = 40; // Extract timestamp components ulong integerPart = BitConverter.ToUInt32(ntpData, serverReplyTimeOffset); ulong fractionalPart = BitConverter.ToUInt32(ntpData, serverReplyTimeOffset + 4); // Convert to little-endian byte order integerPart = SwapEndianness(integerPart); fractionalPart = SwapEndianness(fractionalPart); // Calculate milliseconds long milliseconds = (long)(integerPart * 1000) + (long)((fractionalPart * 1000) / 0x100000000L); // Construct DateTime object from NTP timestamp (UTC) DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds); // Convert to local time return networkDateTime.ToLocalTime(); } // Helper function for byte order conversion static ulong SwapEndianness(ulong x) { return (ulong)(((x & 0x000000ff) << 24) + ((x & 0x0000ff00) << 8) + ((x & 0x00ff0000) >> 8) + ((x & 0xff000000) >> 24)); }</code>
<code class="language-csharp">using System.Net; using System.Net.Sockets;</code>
的功能以進行適當的操作。 SwapEndianness
>
以上是如何使用C#從NTP服務器中檢索準確的時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!