NtpClient class

A socket-based implementation of an NTP (Network Time Protocol) client.

This implementation communicates directly with an NTP server over UDP to retrieve the current UTC time. It is intended for platforms where raw sockets are available (e.g., mobile or desktop) and cannot be used in browser environments.

By default, it queries the public NTP pool (pool.ntp.org) on port 123, but the server, port, and timeout parameters can be customized via the constructor.

Inheritance

Constructors

NtpClient({String server = 'pool.ntp.org', int port = 123, int timeout = 5, String? apiUrl, DateTime parseResponse(Response)?, bool isUtc = false})
Creates a new NtpClient instance with optional configuration parameters.
const

Properties

apiUrl → String?
The URL of the API endpoint to query for time (Web only).
finalinherited
hashCode → int
The hash code for this object.
no setterinherited
isUtc → bool
Whether to return the time in UTC (true) or local time (false).
finalinherited
parseResponse → DateTime Function(Response)?
A function to parse the response from the API endpoint (Web only).
finalinherited
port → int
The UDP port used to communicate with the NTP server.
finalinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
server → String
The hostname or IP address of the NTP server to query.
finalinherited
timeout → int
The timeout in seconds for the time retrieval operation.
finalinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
now() → Future<DateTime>
Retrieves the current DateTime from the configured NTP server.
override
query({int samples = 1}) → Future<NtpResponse>
Queries the configured NTP server and returns a full NtpResponse with RFC 5905 telemetry.
override
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Methods

buildNtpPacket(DateTime originateTime) → Uint8List
Builds a 48-byte NTP request packet according to the protocol specification (RFC 5905).
matchesOriginTimestamp(Uint8List response, Uint8List request) → bool
Verifies that the Origin Timestamp in the response (bytes 24-31) matches the Transmit Timestamp sent in the request (bytes 40-47).
parseNtpTimestamps(Uint8List data) → ({DateTime originTimestamp, DateTime receiveTimestamp, DateTime transmitTimestamp})
Parses the NTP server's response and extracts the Origin (T1), Receive (T2), and Transmit (T3) timestamps, with RFC 4330 Era 1 (2036 rollover) support.
writeNtpTimestamp(ByteData data, int offset, DateTime time) → void
Writes an NTP 64-bit timestamp into data starting at offset using pure 64-bit integer arithmetic.