Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Sockets;
  8.  
  9. namespace NtpClient2B
  10. {
  11. class Program
  12. {
  13. static uint ParseBigEndianUint32(byte[] data, int offset)
  14. {
  15. uint value = 0;
  16. uint byte0 = data[offset + 3];
  17. uint byte1 = data[offset + 2];
  18. uint byte2 = data[offset + 1];
  19. uint byte3 = data[offset];
  20. value = (byte3 << 24) | (byte2 << 16) | (byte1 << 8) | byte0;
  21. return value;
  22. }
  23.  
  24. static DateTime GetUTC(byte[] data, int offset)
  25. {
  26. DateTime baseUTC = new DateTime(1900, 1, 1);
  27. uint seconds = ParseBigEndianUint32(data, offset);
  28. ulong fraction = ParseBigEndianUint32(data, offset + 4);
  29. // convert to milliseconds
  30. fraction *= 1000;
  31. // get the true fraction
  32. fraction /= uint.MaxValue;
  33. return baseUTC.AddSeconds(seconds).AddMilliseconds(fraction);
  34. }
  35.  
  36. static void Main(string[] args)
  37. {
  38. byte[] packet = new byte[48];
  39. const byte leap = 0;
  40. const byte version = 3;
  41. const byte mode = 3;
  42. packet[0] = (leap << 6) | (version << 3) | mode;
  43.  
  44. Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
  45. IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("216.239.35.8"), 123);
  46.  
  47. socket.SendTo(packet, endPoint);
  48.  
  49. int rlen = socket.Receive(packet);
  50. Console.WriteLine(rlen);
  51.  
  52. Console.WriteLine("leap: {0} version: {1} mode: {2}", packet[0] >> 6, (packet[0] >> 3) & 7, packet[0] & 7);
  53. Console.WriteLine("stratum: {0}", packet[1]);
  54. Console.WriteLine("refid: {0}", Encoding.ASCII.GetString(packet, 12, 4));
  55.  
  56. DateTime reference = GetUTC(packet, 16);
  57. DateTime origin = GetUTC(packet, 24);
  58. DateTime receive = GetUTC(packet, 32);
  59. DateTime transmit = GetUTC(packet, 40);
  60.  
  61. Console.WriteLine("reference TS: {0} {1}", reference, reference.Millisecond);
  62. Console.WriteLine("origin TS: {0} {1}", origin, origin.Millisecond);
  63. Console.WriteLine("receive TS: {0} {1}", receive, receive.Millisecond);
  64. Console.WriteLine("transmit TS: {0} {1}", transmit, transmit.Millisecond);
  65.  
  66. Console.ReadLine();
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement