NTP(网络时间协议)基本上是调整设置服务器时钟的事实标准。我已经提出了一个关于 Windows Azure本地时钟精度期望的问题。这里有一个稍微不同的问题:如何使用 NTP 验证当前时钟的可靠性?问题是 UDP 在 Windows Azure 上不可用(只有 TCP),而且似乎没有可用的 NTP 实现 TCP(尽管讨论已经有近十年的历史了)。
有什么拿吗?
NTP(网络时间协议)基本上是调整设置服务器时钟的事实标准。我已经提出了一个关于 Windows Azure本地时钟精度期望的问题。这里有一个稍微不同的问题:如何使用 NTP 验证当前时钟的可靠性?问题是 UDP 在 Windows Azure 上不可用(只有 TCP),而且似乎没有可用的 NTP 实现 TCP(尽管讨论已经有近十年的历史了)。
有什么拿吗?
假设 UDP 传出数据包仍然被 Azure 阻止(我很惊讶/失望,情况仍然如此!)那么也许您可以使用分辨率较低的 TCP 服务,例如 TIME 或 DAYTIME - 请参阅http 上的说明: //www.nist.gov/pml/div688/grp40/its.cfm - 您显然需要测量您的网络呼叫所用的时间长度,以确保返回的答案对您来说足够准确。
Joannes 和 Stuart:您说得对,Windows Azure 角色(Web、Worker 和 VM 角色)目前不支持托管 UDP 端点。但是,NTP 支持已经默认包含在 Windows Azure 角色 VM 中,当前默认配置为每周一次将时钟与服务器 time.windows.com 同步一次(这里的证据- 搜索“时间服务”)。
如果每周同步不够频繁,您可以在启动任务中调整注册表设置。
!
我对你关于 udp 的回答有点惊讶,而我实际上是从我的 azure Web 角色连接到 NTP 服务器以服务于我们的 JS 客户端同步。这工作正常...
请注意,天蓝色的网络角色时间与 NTP 相比有很大不同(实际上提前了 30 秒!!)。但是,NTP 时间与我的本地计算机与 time.microsoft.com 同步的时间几乎相同
{"network":"2013-07-16T18:18:25.9558581Z","server":"2013-07-16T18:18:52.5415999Z"}
这是我使用的代码:
static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
static DateTime Update(string server)
{
// NTP message size - 16 bytes of the digest (RFC 2030)
var 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)
var addresses = Dns.GetHostEntry(server).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], NTPPort);
//NTP uses UDP
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
DateTime l_now = DateTime.UtcNow;
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 = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var l_networkTime = (new DateTime(_epocBaseTicks, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
_networkTimeDelta = l_networkTime.Ticks - l_now.Ticks ;
return l_networkTime;
}
希望这有帮助。