#region 获取互联网时间
private static string[] Servers = { "ntp.aliyun.com",
"ntp1.aliyun.com",
"ntp2.aliyun.com",
"ntp3.aliyun.com",
"ntp4.aliyun.com",
"ntp5.aliyun.com",
"ntp6.aliyun.com",
"ntp7.aliyun.com"
};
private void button1_Click_1(object sender, EventArgs e)
{
foreach (string server in Servers)
{
string ntpServer = server;
var ntpData = new byte[48];
ntpData[0] = 0x1B;
try
{
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
}
catch (Exception ex)
{
continue;
}
const byte serverReplyTime = 40;
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//计算后的时间
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
}
uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
#endregion
通过阿里云获取互联网时间
最新推荐文章于 2024-05-26 15:24:36 发布