Diese Methode hängt vom Netzwerkzeitprotokoll (NTP) ab, bei dem Abfragenachrichten an den NTP -Server gesendet werden. Der Server antwortet auf die Antwortmeldung, die die aktuelle Zeit enthält. Dann extrahieren wir die Zeit aus der Antwort und konvertieren sie in das verfügbare Format.
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) ); } }
Das obige ist der detaillierte Inhalt vonWie kann ich einen NTP -Server für das aktuelle Datum und die aktuelle Uhrzeit mit C#abfragen?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!