0 Replies - 1533 Views - Last Post: 08 October 2012 - 08:56 PM

#1 rfs02  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 70
  • Joined: 30-September 12

NTP Client

Posted 08 October 2012 - 08:56 PM

Description: NTPClient.GetNetworkTime("time.windows.com");A simple class to retrieve the current time from a remote NTP server.
using System;
using System.Net;
using System.Net.Sockets;

namespace GetTime
{
    public static class NTPClient
    {
        /// 
        /// Retrieves the current time from an NTP Server
        /// 
        /// Server to get the time from
        /// 
        public static DateTime GetNetworkTime(string server)
        {
            // SNTP packets are 48 bytes in length
            var ntpData = new byte[48];

            // Leap indicator = 0; Use IPv4 only; Client mode
            // |    Byte + 3   |    Byte + 2   |    Byte + 1   |    Byte + 0   |
            //  7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
            // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
            // |   Precision   |      Poll     |    Stratum    |LI | VN  |Mode | 
            // |               |               |               |0 0|0 1 1|0 1 1| 
            // 
            // LI = 0    => no warnings / last minute had 60 seconds
            // VN = 3    => Version number is 3
            // Mode = 3  => set to 3 for client
            ntpData[0] = 0x1B;

            // get the address of the server
            var addresses = Dns.GetHostEntry(server).AddressList;

            // SNTP uses port 123
            var ipEndPoint = new IPEndPoint(addresses[0], 123);

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            socket.Connect(ipEndPoint);
            socket.Send(ntpData);
            socket.Receive(ntpData);
            socket.Close();

            // we start reading the reply time at byte 40 of the response
            const byte serverReplyTime = 40;
            ulong intPart = SwapByteOrder(BitConverter.ToUInt32(ntpData, serverReplyTime));
            ulong fractPart = SwapByteOrder(BitConverter.ToUInt32(ntpData, serverReplyTime + 4));

            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

            var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);

            return networkDateTime + TimeZone.CurrentTimeZone.GetUtcOffset(networkDateTime);
        }

        private static uint SwapByteOrder(ulong x)
        {
            return (uint)(((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
        }

    }

}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1