代码之家  ›  专栏  ›  技术社区  ›  Kelvin

如何将时间与WM上的Internet资源同步?

  •  3
  • Kelvin  · 技术社区  · 16 年前

    在Windows应用程序中,我使用W32TM强制计算机将时间与特定的时间资源同步。 但是现在我在wm5.0上做一个pda应用程序,w32tm已经不可用了,不知道如何在谷歌上搜索一点之后开始。

    1 回复  |  直到 12 年前
        1
  •  4
  •   ctacke    12 年前

    Here is a good example .

    为了完整起见,以下是博客文章中的代码:

    public DateTime GetNTPTime()
    {
        // 0x1B == 0b11011 == NTP version 3, client - see RFC 2030
        byte[] ntpPacket = new byte[] { 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    
        IPAddress[] addressList = Dns.GetHostEntry("pool.ntp.org").AddressList;
    
        if (addressList.Length == 0)
        {
            // error
            return DateTime.MinValue;
        }
    
        IPEndPoint ep = new IPEndPoint(addressList[0], 123);
        UdpClient client = new UdpClient();
        client.Connect(ep);
        client.Send(ntpPacket, ntpPacket.Length);
        byte[] data = client.Receive(ref ep);
    
        // receive date data is at offset 32
        // Data is 64 bits - first 32 is seconds - we'll toss the fraction of a second
        // it is not in an endian order, so we must rearrange
        byte[] endianSeconds = new byte[4];
        endianSeconds[0] = data[32 + 3];
        endianSeconds[1] = data[32 + 2];
        endianSeconds[2] = data[32 + 1];
        endianSeconds[3] = data[32 + 0];
        uint seconds = BitConverter.ToUInt32(endianSeconds, 0);
    
        return (new DateTime(1900, 1, 1)).AddSeconds(seconds);
    }
    
    推荐文章