>从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中文网其他相关文章!