Advertisement
giammin

Get Time from NTP Server

Jan 14th, 2013
2,095
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. public static DateTime GetNetworkTime()
  2. {
  3.     //default Windows time server
  4.     const string ntpServer = "time.windows.com";
  5.  
  6.     // NTP message size - 16 bytes of the digest (RFC 2030)
  7.     var ntpData = new byte[48];
  8.  
  9.     //Setting the Leap Indicator, Version Number and Mode values
  10.     ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
  11.  
  12.     var addresses = Dns.GetHostEntry(ntpServer).AddressList;
  13.  
  14.     //The UDP port number assigned to NTP is 123
  15.     var ipEndPoint = new IPEndPoint(addresses[0], 123);
  16.     //NTP uses UDP
  17.     var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  18.  
  19.     socket.Connect(ipEndPoint);
  20.  
  21.     socket.Send(ntpData);
  22.     socket.Receive(ntpData);
  23.     socket.Close();
  24.  
  25.     //Offset to get to the "Transmit Timestamp" field (time at which the reply
  26.     //departed the server for the client, in 64-bit timestamp format."
  27.     const byte serverReplyTime = 40;
  28.  
  29.     //Get the seconds part
  30.     ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
  31.  
  32.     //Get the seconds fraction
  33.     ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
  34.  
  35.     //Convert From big-endian to little-endian
  36.     intPart = SwapEndianness(intPart);
  37.     fractPart = SwapEndianness(fractPart);
  38.  
  39.     var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
  40.  
  41.     //**UTC** time
  42.     var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
  43.  
  44.     return networkDateTime;
  45. }
  46.  
  47. // stackoverflow.com/a/3294698/162671
  48. static uint SwapEndianness(ulong x)
  49. {
  50.     return (uint) (((x & 0x000000ff) << 24) +
  51.                    ((x & 0x0000ff00) << 8) +
  52.                    ((x & 0x00ff0000) >> 8) +
  53.                    ((x & 0xff000000) >> 24));
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement