I am asking this question for learning purposes.
Take a look at this udp packet I just captured on wireshark:
(That is what time.windows.com replies in order to give the time to my computer)
Anyways my question is regarding the last 8 bytes that are highlighted. Note how Wireshark parses the date correctly. How did time.windows.com generated those 8 bytes? How can I go from DateTime.NowUtc
to something wireshark will parse as the correct date?
I have tried:
long dateTime = DateTime.Now.ToFileTimeUtc();
var bytes = BitConverter.GetBytes(dateTime);
but when I send those 8 bytes wireshark parses that date as "4/15/1998 11:27:52 AM" which is way off.
I have also tried adding milliseconds since 1970 but that still shows an incorrect date.
Edit
Here is example on how to parse the response: http://davidnakoko.com/2013/07/c-get-network-time-from-ntp-server/
But where can I find an example on how to create it?
Solution
Thanks to @adjan and @RayFischer answer I came up with a solution. Here it is:
public static byte[] ConvertToNtp(DateTime datetime)
{
ulong milliseconds = (ulong)((datetime - new DateTime(1900, 1, 1)).TotalMilliseconds);
ulong intpart = 0, fractpart = 0;
var ntpData = new byte[8];
intpart = milliseconds / 1000;
fractpart = ((milliseconds % 1000) * 0x100000000L) / 1000;
//Debug.WriteLine("intpart: " + intpart);
//Debug.WriteLine("fractpart: " + fractpart);
//Debug.WriteLine("milliseconds: " + milliseconds);
var temp = intpart;
for (var i = 3; i >= 0; i--)
{
ntpData[i] = (byte)(temp % 256);
temp = temp / 256;
}
temp = fractpart;
for (var i = 7; i >= 4; i--)
{
ntpData[i] = (byte)(temp % 256);
temp = temp / 256;
}
return ntpData;
}