从NTP服务器获取时间(C#)
来源:互联网 发布:java完整项目案例 编辑:程序博客网 时间:2024/05/25 19:56
从NTP服务器可以获取准确的时间,常常被用于校准本地时间。子丰采用阿里的NTP服务器ntp1.aliyun.com进行介绍,需要注意的是从NTP服务器获得的时间是UTC时间,其与北京时间相差8个小时(北京时间 = UTC时间 + 8小时)。
在C#中可以使用DateTime的成员函数ToLocalTime()自动将UTC时间转换为本地时间(根据本地计算机设置的时区不同,其转换得到的时间也不同),只需要将本地计算机的时区设置为中国即可。
using System;using System.Net;using System.Net.Sockets;// 获取网络时间public DateTime getWebTime(){ // default ntp server const string ntpServer = "ntp1.aliyun.com"; // NTP message size - 16 bytes of the digest (RFC 2030) byte[] ntpData = new byte[48]; // Setting the Leap Indicator, Version Number and Mode values ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList; // The UDP port number assigned to NTP is 123 IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123); // NTP uses UDP Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Connect(ipEndPoint); // Stops code hang if NTP is blocked socket.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 part ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime); // Get the seconds fraction ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4); // Convert From big-endian to little-endian intPart = swapEndian(intPart); fractPart = swapEndian(fractPart); ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000UL); // UTC time DateTime webTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(milliseconds); // Local time return webTime.ToLocalTime();}// 小端存储与大端存储的转换private uint swapEndian(ulong x){ return (uint)(((x & 0x000000ff) << 24) + ((x & 0x0000ff00) << 8) + ((x & 0x00ff0000) >> 8) + ((x & 0xff000000) >> 24));}
注:这里使用小端存储与大端存储的转换,这是因为阿里服务器和本地计算机使用了不同的存储方式。因此,在实际使用过程中,还需要根据自己本地计算机判断是否需要进行小端与大端的转换。
阅读全文
0 0
- 从NTP服务器获取时间(C#)
- 从网络获取时间 NTP服务器
- 用windows搭建ntp时间服务器(从上级获取时间,并为客户机提供时间)
- 获取NTP时间服务器时间
- 通过NTP服务器获取网络时间C++
- NTP服务器(时间同步)
- 时间服务器:NTP服务器
- 时间服务器: NTP 服务器
- 计算机NTP时钟同步(NTP服务器-NTP时间服务器)的重要性及其配置方法
- Linux内网服务器从Windows通过NTP同步时间
- linux配置时间服务器(ntp)
- 搭建内部时间同步服务器(NTP)
- NTP服务器同步本地时间(WinForm)
- NTP网络时间服务器
- ntp时间服务器
- NTP时间服务器
- ntp时间服务器
- 搭建ntp时间服务器
- 51nod 1090 3个数和为0
- 10.4 博客
- 备考OCJP认证知识点总结(五)
- 如何显示二进制文件中的内容
- 递归-OpenJudge-7215:简单整数划分
- 从NTP服务器获取时间(C#)
- IIS下开启php扩展失效?
- 解决request中文乱码
- Java虚拟机:类加载
- mysql数据库初次登录时无法登录问题以及修改密码的问题
- python学习笔记--推导式(Comprehension)
- poj1251 Jungle Roads
- linux增加新的磁盘空间 采用lvm方式
- STM32标准外设库(有收获有进步)