Skip to content

Instantly share code, notes, and snippets.

@rdeioris
Created March 18, 2019 18:58
Show Gist options
  • Save rdeioris/cd541d5e87dd5a68744f08c7be762687 to your computer and use it in GitHub Desktop.
Save rdeioris/cd541d5e87dd5a68744f08c7be762687 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace NtpClient2B
{
class Program
{
static uint ParseBigEndianUint32(byte[] data, int offset)
{
uint value = 0;
uint byte0 = data[offset + 3];
uint byte1 = data[offset + 2];
uint byte2 = data[offset + 1];
uint byte3 = data[offset];
value = (byte3 << 24) | (byte2 << 16) | (byte1 << 8) | byte0;
return value;
}
static DateTime GetUTC(byte[] data, int offset)
{
DateTime baseUTC = new DateTime(1900, 1, 1);
uint seconds = ParseBigEndianUint32(data, offset);
ulong fraction = ParseBigEndianUint32(data, offset + 4);
// convert to milliseconds
fraction *= 1000;
// get the true fraction
fraction /= uint.MaxValue;
return baseUTC.AddSeconds(seconds).AddMilliseconds(fraction);
}
static void Main(string[] args)
{
byte[] packet = new byte[48];
const byte leap = 0;
const byte version = 3;
const byte mode = 3;
packet[0] = (leap << 6) | (version << 3) | mode;
Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("216.239.35.8"), 123);
socket.SendTo(packet, endPoint);
int rlen = socket.Receive(packet);
Console.WriteLine(rlen);
Console.WriteLine("leap: {0} version: {1} mode: {2}", packet[0] >> 6, (packet[0] >> 3) & 7, packet[0] & 7);
Console.WriteLine("stratum: {0}", packet[1]);
Console.WriteLine("refid: {0}", Encoding.ASCII.GetString(packet, 12, 4));
DateTime reference = GetUTC(packet, 16);
DateTime origin = GetUTC(packet, 24);
DateTime receive = GetUTC(packet, 32);
DateTime transmit = GetUTC(packet, 40);
Console.WriteLine("reference TS: {0} {1}", reference, reference.Millisecond);
Console.WriteLine("origin TS: {0} {1}", origin, origin.Millisecond);
Console.WriteLine("receive TS: {0} {1}", receive, receive.Millisecond);
Console.WriteLine("transmit TS: {0} {1}", transmit, transmit.Millisecond);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment