日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何获取网络标准时间

發布時間:2023/12/10 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何获取网络标准时间 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我提供一種獲取網絡標準時間的方法

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

總結

以上是生活随笔為你收集整理的如何获取网络标准时间的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。