>從NTP服務器中檢索網絡時間,並使用C#
檢索網絡時間本指南展示了一種使用C#。
從NTP(網絡時間協議)服務器獲取當前時間的簡單方法這是C#代碼:
<code class="language-csharp">using System; using System.Net; using System.Net.Sockets; public static class NetworkTime { public static DateTime GetNetworkTime() { const string ntpServer = "time.windows.com"; // Or another NTP server const int ntpDataSize = 48; const int serverReplyTimeOffset = 40; byte[] ntpData = new byte[ntpDataSize]; IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList; using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123); socket.Connect(ipEndPoint); socket.ReceiveTimeout = 3000; // 3-second timeout socket.Send(ntpData); socket.Receive(ntpData); } ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTimeOffset); ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTimeOffset + 4); intPart = SwapEndianness(intPart); fractPart = SwapEndianness(fractPart); long milliseconds = (long)(intPart * 1000) + (long)((fractPart * 1000) / 0x100000000L); DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds); return networkDateTime.ToLocalTime(); } static uint SwapEndianness(ulong x) { return (uint)(((x & 0x000000ff) << 24) + ((x & 0x0000ff00) << 8) + ((x & 0x00ff0000) >> 8) + ((x & 0xff000000) >> 24)); } }</code>
請記住將using System.Net;
和using System.Net.Sockets;
添加到您的項目中。 此改進的版本使用了更多描述性變量名稱,並闡明了SwapEndianness
函數的返回類型,以提高可讀性和可維護性。 插座接收操作還添加了超時,以防止無限期阻塞。
以上是如何使用C#從NTP服務器獲取當前的網絡時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!