Home > Backend Development > C++ > How to Query an NTP Server for Current Date and Time Using C#?

How to Query an NTP Server for Current Date and Time Using C#?

Barbara Streisand
Release: 2025-01-29 00:31:09
Original
742 people have browsed it

How to Query an NTP Server for Current Date and Time Using C#?

Use C#to query NTP server: complete solution

This article provides a reliable method to retrieve the current date and time from the C#from the NTP server. Here are the steps involved and a complete code solution.

This method depends on the network time protocol (NTP), which involves sending query messages to the NTP server. The server will reply to the reply message containing the current time. Then, we extract time from the reply and convert it to the available format.

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

public static class NTP
{
    public static DateTime GetNetworkTime()
    {
        const string ntpServer = "time.windows.com";
        const int ntpPort = 123;
        byte[] ntpData = new byte[48];

        ntpData[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (Client)

        using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            socket.Connect(new IPEndPoint(Dns.GetHostEntry(ntpServer).AddressList[0], ntpPort));

            socket.Send(ntpData);
            socket.Receive(ntpData);
        }

        const int serverReplyTime = 40;
        ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
        ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 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();
    }

    private static ulong SwapEndianness(ulong x)
    {
        return (ulong)(
            ((x & 0x000000ff) << 24) |
            ((x & 0x0000ff00) << 8) |
            ((x & 0x00ff0000) >> 8) |
            ((x & 0xff000000) >> 24)
        );
    }
}</code>
Copy after login
Using this code, you can easily query the NTP server and get the current date and time. This solution processing byte order conversion, and provides a flexible way to retrieve time from any compatible NTP server. Pay attention to the correction of the function in the code to ensure the correct byte order conversion.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template