Obtain Interent Time

I have a Fez Spider. Can anyone provide or drect me to code that shows how to obtain the time from the NIST Internet Time Service?
Thank You, Bob

Hey Bob,

http://www.tinyclr.com/codeshare/search?q=ntp

This one is probably the clearest example: http://www.tinyclr.com/codeshare/entry/244 even though it’s not explicitly for Spider/EMX but the W5100.

Hope they help !

Bob my Palm Garden Monitor with Gadgeteer has an NTPT routine in it and uses a Spider http://www.tinyclr.com/codeshare/entry/426


public static bool NTPTime(string TimeServer, int GmtOffset = 0)
216.       {
217.            Socket s = null;
218.            try
219.            {
220.                EndPoint rep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);
221.                s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
222.                byte[] ntpData = new byte[48];
223.                Array.Clear(ntpData, 0, 48);
224.                ntpData[0] = 0x1B; // Set protocol version
225.                s.SendTo(ntpData, rep); // Send Request   
226.                if (s.Poll(30*1000*1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
227.                {
228.                    s.ReceiveFrom(ntpData, ref rep); // Receive Time
229.                    byte offsetTransmitTime = 40;
230.                    ulong intpart = 0;
231.                    ulong fractpart = 0;
232.                    for (int i = 0; i <= 3; i++) intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];
233.                    for (int i = 4; i <= 7; i++) fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];
234.                    ulong milliseconds = (intpart*1000 + (fractpart*1000)/0x100000000L);
235.                    s.Close();
236.                    DateTime dateTime = new DateTime(1900, 1, 1) +
237.                                        TimeSpan.FromTicks((long) milliseconds*TimeSpan.TicksPerMillisecond);
238.                    Utility.SetLocalTime(dateTime.AddMinutes(GmtOffset));
239.                    return true;
240.                }
241.                s.Close();
242.            }
243.            catch
244.            {
245.                try
246.                {
247.                    s.Close();
248.                }
249.                catch
250.                {
251.                }
252.            }
253.            return false;
254.        }

Perfect! Thank you for sharing your code. It is a very well built and a cool Gadgeteer application. The NTPT time sync is exactly what I was looking for and will find a home in my project. Again, thank you.

Here’s my version, which didn’t have the timeout try and catch before (Thanks @ Duke)



using System;
using System.Net;
using System.Net.Sockets;
using Microsoft.SPOT;
using GT = Gadgeteer;

namespace InternetTime
{
    public partial class Program
    {
        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {

            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");

            ethernet_J11D.UseDHCP();

            GT.Timer timer = new GT.Timer(5000);
            timer.Tick += new GT.Timer.TickEventHandler(timer_Tick);

            ethernet_J11D.UseDHCP();            
            timer.Start();
        }

        void timer_Tick(GT.Timer timer)
        {
            timer.Stop();
            Debug.Print("--------------------------");
            Debug.Print("Seeing if we are online...");
            if (ethernet_J11D.IsNetworkConnected)
            {
                Debug.Print("Online!");
                Debug.Print("IP Address: " + ethernet_J11D.NetworkSettings.IPAddress);
                DateTime ntpTime = NTPTime("time-a.nist.gov", -5);
                if (ntpTime != DateTime.MinValue)
                {
                    Debug.Print("Local Time is: " + ntpTime.ToString());
                }                    
            }
            else
            {
                Debug.Print("Not connected to network!");
            }
            timer.Start();
            
        }

        public static DateTime NTPTime(String TimeServer, int UTC_offset)
        {
            // Find endpoint for timeserver
            IPEndPoint ep = new IPEndPoint(Dns.GetHostEntry(TimeServer).AddressList[0], 123);

            // Connect to timeserver
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            try
            {
                s.Connect(ep);

                // Make send/receive buffer
                byte[] ntpData = new byte[48];
                Array.Clear(ntpData, 0, 48);

                // Set protocol version
                ntpData[0] = 0x1B;

                // Send Request
                Debug.Print("Sending request to server " + TimeServer);
                s.Send(ntpData);

                if (s.Poll(30 * 1000 * 1000, SelectMode.SelectRead)) // Waiting an answer for 30s, if nothing: timeout
                {

                    // Receive Time
                    Debug.Print("Receiving time data from to server " + TimeServer);
                    s.Receive(ntpData);

                    byte offsetTransmitTime = 40;

                    Debug.Print("Calculating time.. ");
                    ulong intpart = 0;
                    ulong fractpart = 0;

                    for (int i = 0; i <= 3; i++)
                        intpart = (intpart << 8) | ntpData[offsetTransmitTime + i];

                    for (int i = 4; i <= 7; i++)
                        fractpart = (fractpart << 8) | ntpData[offsetTransmitTime + i];

                    ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);

                    TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    DateTime dateTime = new DateTime(1900, 1, 1);
                    dateTime += timeSpan;

                    TimeSpan offsetAmount = new TimeSpan(0, UTC_offset, 0, 0, 0);
                    DateTime networkDateTime = (dateTime + offsetAmount);

                    return networkDateTime;
                }
                else
                {
                    Debug.Print("No response from time server " + TimeServer);
                }
                s.Close();
            }
            catch
            {
                try
                {
                    s.Close();
                }
                catch
                {
                }
            }
            return DateTime.MinValue;

        }
    }
}


No problem Bob, I got my code from someone else (I wish I could remember who as I’ve gotten help from so many Gadgeteer folks here), as there are lots of most worthy coders on this forum and some uber hardware dudes also, so pretty much any questions or problems you have, someone on this site will help, I’m just sharing what someone shared with me.

@ stevepresley - Thank you. I am new to the forum and can not express how much everyones support is appreciated. I hope I can pass on the same kind of support in the future.