Robert's blog
Robert Važan

GuerrillaNtp: App-embedded NTP client for .NET

Perform simple NTP queries from C# code. GuerillaNtp provides accurate NTP time for applications running on broken clients.

Recently, I needed to embed NTP client in a time-sensitive C# application. I couldn't use system-wide NTP time, because this particular application had to be deployed on numerous computers that I didn't control. After looking around for existing solutions, I decided to patch up one of them and publish it as opensource GuerrillaNtp library on NuGet.

GuerrillaNtp allows you to embed NTP client in your application without touching the system clock. You can have accurate NTP time within your application while the rest of the system uses the unsynchronized system clock.

You can perform queries against selected NTP servers (e.g. pool.ntp.org or your private NTP servers). GuerrillaNtp calculates delta between local time and NTP time. Here's a short example:

// perform only one query to get the offset
TimeSpan offset;
using (var ntp = new NtpClient("pool.ntp.org"))
{
    ntp.Timeout = TimeSpan.FromSeconds(5);
    var ntpResponse = ntp.Query();
    offset = ntpResponse.CorrectionOffset;
}
// use the offset throughout your app
var accurateTime = DateTime.UtcNow + offset;

You can perform more queries against the NTP server throughout the lifetime of your application or use multiple servers depending on your needs. GuerrillaNtp also calculates round-trip time to the NTP server for you.

GuerrillaNtp is licensed under permissive MIT license. You can download it from NuGet.

GuerrillaNtp is based on Netduino NTP client that I have found on NuGet. I've ported it to desktop .NET Framework and added numerous patches. Some of the patches are based on SNTP client from Valer Bocan that has numerous mutations circulating around the Internet. Platform.NET contains fairly competent NTP client, which I have discovered after creating GuerrillaNtp.

Even after my patches, GuerrillaNtp is still a bare bones SNTP client. If you are interested in improving it, your patches to GuerrillaNtp source code are welcome.