c#
を使用してNTPサーバーからネットワーク時間を取得しますこのガイドは、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;
関数の返品タイプを明確にします。 また、無期限のブロッキングを防ぐために、ソケット受信操作にタイムアウトが追加されます。
以上がC#を使用してNTPサーバーから現在のネットワーク時間を取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。