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