|SNTP Time Class|
|Written by Harry Fairhead|
|Tuesday, 23 December 2014|
Page 3 of 3
Getting The Time
Now we can wait for the time server to send a datagram back to us. First we need to initialise a new IPEndPoint object and a new SNTPpacket for the reply. We could reuse the old SNTP packet if you are trying to save time and storage.
Again for simplicity we use the blocking form of the receive method. Notice that this will hang forever if no packets are recieved back from the time server. In practice a much better idea is to use the non-blocking BeginRecieve method:
Now we can process the data in the buffer, assuming that a datagram was received and place the results in the SNTPpacket properties, again using a method we have yet to write:
We have to now write the ConvertFromBuffer method and this is slightly more complicated than the ConvertToBuffer method. However converting the first four bytes is easy enough and more or less just a reversal of the ConverToBuffer method.
The next three 32bit values are also easy enough as we do not attempt any data conversions to more sophisticated data types:
Next we have to convert the 64 bit time values and transfer them to the DateTime properties. Again it is simpler to suppose that we have a method that does the job and solve the problem of writing it later:
where the ConvertFromSNTPTime(start) method converts the 8 bytes starting the "start" position in the buffer.
Finally we need to write the ConvertFromSNTPTime method.
Again this is complicated by the need to reverse the byte order as we unpack the buffer into two temporary arrays one for the high value i.e. the integer number of seconds and one for the low value the fractional seconds:
Now that the byte order is reversed we can use BitConverter to get the high and low 32bits into unsigned 32 bit integers:
To convert this raw second count into a DateTime we can make things easy by first converting to a double that represents the total number of seconds, including any fractional portion since 1 Jan 1900:
Now we can convert this to a DateTime object and add the appropriate number of seconds to the start of the SNTP time count i.e. 1 Jan 1990:
This completes the unpacking and all of the methods we have assumed were available have been written - time to try it all out.
Trying it out
Now we can try out the control. Add a command button the Form project and enter the following code:
pool.,ntp.org uses a public server from the pool using a round robin algorithm. You can use any server you care to.
If you need to know more, or find a more local server, look at http://www.ntp.org/ .
Code for this project is available from the CodeBin.
or email your comment to: firstname.lastname@example.org
|Last Updated ( Sunday, 16 September 2018 )|