Home >Backend Development >C++ >How to Get the Current Network Time from an NTP Server using C#?

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

DDD
DDDOriginal
2025-01-29 00:26:12847browse

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

Retrieving Network Time from an NTP Server with C#

This guide demonstrates a simple method for obtaining the current time from an NTP (Network Time Protocol) server using C#.

Here's the C# code:

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

Remember to add using System.Net; and using System.Net.Sockets; to your project. This improved version uses more descriptive variable names and clarifies the SwapEndianness function's return type for better readability and maintainability. A timeout is also added to the socket receive operation to prevent indefinite blocking.

The above is the detailed content of How to Get the Current Network 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