如何获取网络标准时间
生活随笔
收集整理的這篇文章主要介紹了
如何获取网络标准时间
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
我提供一種獲取網(wǎng)絡(luò)標(biāo)準(zhǔn)時間的方法
<span style="font-family:KaiTi_GB2312;font-size:18px;">public static DateTime GetNetworkTime(){//default Windows time serverconst string ntpServer = "time.windows.com";// NTP message size - 16 bytes of the digest (RFC 2030)var ntpData = new byte[48];//Setting the Leap Indicator, Version Number and Mode valuesntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)var addresses = Dns.GetHostEntry(ntpServer).AddressList;//The UDP port number assigned to NTP is 123var ipEndPoint = new IPEndPoint(addresses[0], 123);//NTP uses UDPvar socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);socket.Connect(ipEndPoint);//Stops code hang if NTP is blockedsocket.ReceiveTimeout = 3000;socket.Send(ntpData);socket.Receive(ntpData);socket.Close();//Offset to get to the "Transmit Timestamp" field (time at which the reply //departed the server for the client, in 64-bit timestamp format."const byte serverReplyTime = 40;//Get the seconds partulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);//Get the seconds fractionulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);//Convert From big-endian to little-endianintPart = SwapEndianness(intPart);fractPart = SwapEndianness(fractPart);var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);//**UTC** timevar networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);return networkDateTime.ToLocalTime();}// stackoverflow.com/a/3294698/162671static uint SwapEndianness(ulong x){return (uint)(((x & 0x000000ff) << 24) +((x & 0x0000ff00) << 8) +((x & 0x00ff0000) >> 8) +((x & 0xff000000) >> 24));} </span>總結(jié)
以上是生活随笔為你收集整理的如何获取网络标准时间的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 这篇看完我得理解ES6中中常见语法
- 下一篇: Sql Server2005创建数据库