Home >Backend Development >C++ >How to Retrieve Accurate Time from an NTP Server Using C#?

How to Retrieve Accurate Time from an NTP Server Using C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-29 00:36:09788browse

How to Retrieve Accurate Time from an NTP Server Using C#?

Retrieving Accurate Time from an NTP Server with C#

This C# code snippet demonstrates how to fetch the current time from a Network Time Protocol (NTP) server:

<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>

Remember to add these using statements:

<code class="language-csharp">using System.Net;
using System.Net.Sockets;</code>

This revised code offers improved clarity and utilizes more efficient byte order swapping. The SwapEndianness function is also corrected for proper ulong handling.

The above is the detailed content of How to Retrieve Accurate Time from an NTP Server Using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn