ホームページ >バックエンド開発 >C++ >C#を使用してNTPサーバーから現在のネットワーク時間を取得するにはどうすればよいですか?

C#を使用してNTPサーバーから現在のネットワーク時間を取得するにはどうすればよいですか?

DDD
DDDオリジナル
2025-01-29 00:26:12851ブラウズ

How to Get the Current Network Time from an NTP Server using C#?

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 サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。