Getting started
editInstall the packages
dotnet package add Meziantou.Framework.NtpClient
dotnet package add Meziantou.Framework.NtpServerQuery a server
This example starts a server on a free port of the loopback interface, then queries it. To query a time server of your network or of the internet, pass its host name to NtpClient and leave the default port, 123:
using var server = new NtpServer(new NtpServerOptions { Port = 0, BindAddress = IPAddress.Loopback });
await server.StartAsync();
var client = new NtpClient("127.0.0.1", new NtpClientOptions { Port = server.Port });
var response = await client.QueryAsync();
// The difference between the clock of the server and the local clock
var localTimeCorrected = DateTimeOffset.UtcNow + response.ClockOffset;
Assert.Equal(NtpVersion.V4, response.Version);
Assert.Equal(2, response.Stratum);
Assert.True(response.RoundTripDelay >= TimeSpan.Zero);Port = 0lets the system choose a free port;server.Portis the port it chose.- QueryAsync sends one request and returns an NtpResponse. See Querying a server.
- ClockOffset is what to add to the local clock to get the time of the server.
- NtpClient holds no resource: there is nothing to dispose. The server is disposable: disposing it stops it.
Next steps
- Querying a server: the fields of the response, the options, timeouts.
- Running a server: addresses, time source, stratum, rate limiting.