首頁 > 後端開發 > C++ > 如何使用C#查詢當前日期和時間的NTP服務器?

如何使用C#查詢當前日期和時間的NTP服務器?

Barbara Streisand
發布: 2025-01-29 00:31:09
原創
799 人瀏覽過

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

使用C#查詢NTP服務器:完整解決方案

本文提供一種可靠的方法,使用C#從NTP服務器檢索當前日期和時間。以下是涉及的步驟和完整的代碼解決方案。

此方法依賴於網絡時間協議(NTP),它涉及向NTP服務器發送查詢消息。服務器會回复包含當前時間的回复消息。然後,我們從回復中提取時間並將其轉換為可用的格式。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

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)

        );

    }

}

登入後複製

使用此代碼,您可以輕鬆查詢NTP服務器並獲取當前日期和時間。此解決方案處理字節序轉換,並提供了一種靈活的方式來從任何兼容的NTP服務器檢索時間。 注意代碼中SwapEndianness函數的修正,以確保正確的字節序轉換。

以上是如何使用C#查詢當前日期和時間的NTP服務器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板