Get Time from NTP Server


SUBMITTED BY: Guest

DATE: Nov. 11, 2013, 9:12 p.m.

FORMAT: Text only

SIZE: 1.9 kB

HITS: 1005

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

comments powered by Disqus