venerdì 13 aprile 2012

How To Get Date & Time from NTP SERVER

 

Se mai vi dovesse servire Sorriso

La chiamata

public class Program
 {
      public static void Main(string[] args)
     {
         var t =NTP.GetNTPTime();
     }
 }

 

La Funzione

public class NTP
   {
       public static DateTime GetNTPTime()
       {
           try
           {
               // 0x1B == 0b11011 == NTP version 3, client - vedi 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 };


               var ntp = (from p in (Dns.GetHostEntry("pool.ntp.org").AddressList).Take(1)
                          select new { Client = new UdpClient(), EP = new IPEndPoint(p, 123) }
                        ).ToArray().FirstOrDefault();

               ntp.Client.Connect(ntp.EP);
               ntp.Client.Send(ntpPacket, ntpPacket.Length);

               var TmpEP = ntp.EP;
               byte[] data = ntp.Client.Receive(ref TmpEP);

               // dal 32 byte inizia la data
               byte[] ConvertedSeconds = new byte[4];
               ConvertedSeconds[0] = (byte)(data[32 + 3] & (byte)0x7F); // disabilita l'MSB (sui server che lo usano)
               ConvertedSeconds[1] = data[32 + 2];
               ConvertedSeconds[2] = data[32 + 1];
               ConvertedSeconds[3] = data[32 + 0];

               uint seconds = BitConverter.ToUInt32(ConvertedSeconds, 0);

               return (new DateTime(1900, 1, 1)).AddSeconds(seconds);
           }
           catch (Exception ex )
           {
               Console.WriteLine(ex.Message);
               return DateTime.MinValue;
           }
   
       }
   }

Nessun commento: