a very simple NTP client in D
I am quite a fan of the D programming language and I think it deserves more attention, even if since a few months it’s becoming more and more popular, as it gained top20 in the TIOBE Index for February 2020.
As an experiment in network programming, I took this simple NTP client written in C and translated to D ; in my opinion while it’s keeping the low-level nature, it’s shorter, clearer and more effective. It’s only a dozen lines of code, but full program is available on my github; stars and contributions are welcome!
Starting from the top, we find the needed imports and then the packet structure, as is specified in the reference implementation (it’s a matter of copy-paste). Notice that in D we can initialize the structure field with tne value we need.
when the main function begins, we create a new UDP socket, with protocol IPV4, and allocate on the stack. Then we tell the socket to connect to a NTP server of the ‘europe’ pool. Of course you can change it to any address you prefer :)
Here it comes the trickiest part: the send method of the UdpSocket class requires a slice, and returns the number of bytes effectively transferred; but we have to send a struct, so we need to cast our packet as a 1-element slice:
The last piece is straightforward, thanks also to Phobos, the powerful D standard library: we convert the received bytes to our native bit-order representation (notice the template syntax) and translate from unix Epoch to human-readable date and time. Every variable type is inferred automagically for us :)