Documentation ¶
Overview ¶
Package ntp provides an implementation of a Simple NTP (SNTP) client capable of querying the current time from a remote NTP server. See RFC 5905 (https://tools.ietf.org/html/rfc5905) for more details.
This approach grew out of a go-nuts post by Michael Hofmann: https://groups.google.com/forum/?fromgroups#!topic/golang-nuts/FlcdMU5fkLQ
Index ¶
- Constants
- Variables
- func ClockOffsetChan(ctx context.Context, interval time.Duration, hosts ...string) chan time.Duration
- func Time(address string) (time.Time, error)
- func TimeChan(ctx context.Context, interval time.Duration, hosts ...string) chan time.Time
- type AuthOptions
- type AuthType
- type Extension
- type HostResponse
- type LeapIndicator
- type QueryOptions
- type Response
Constants ¶
const ( // LeapNoWarning indicates no impending leap second. LeapNoWarning LeapIndicator = 0 // LeapAddSecond indicates the last minute of the day has 61 seconds. LeapAddSecond = 1 // LeapDelSecond indicates the last minute of the day has 59 seconds. LeapDelSecond = 2 // LeapNotInSync indicates an unsynchronized leap second. LeapNotInSync = 3 )
Variables ¶
var ( ErrAuthFailed = errors.New("authentication failed") ErrInvalidAuthKey = errors.New("invalid authentication key") ErrInvalidDispersion = errors.New("invalid dispersion in response") ErrInvalidLeapSecond = errors.New("invalid leap second in response") ErrInvalidMode = errors.New("invalid mode in response") ErrInvalidProtocolVersion = errors.New("invalid protocol version requested") ErrInvalidStratum = errors.New("invalid stratum in response") ErrInvalidTime = errors.New("invalid time reported") ErrInvalidTransmitTime = errors.New("invalid transmit time in response") ErrKissOfDeath = errors.New("kiss of death received") ErrServerClockFreshness = errors.New("server clock not fresh") ErrServerResponseMismatch = errors.New("server response didn't match request") ErrServerTickedBackwards = errors.New("server clock ticked backwards") )
Functions ¶
func ClockOffsetChan ¶ added in v0.3.1
func ClockOffsetChan(ctx context.Context, interval time.Duration, hosts ...string) chan time.Duration
ClockOffsetChan 启动 Simple NTP (SNTP), 周期性获取时钟偏移值
func Time ¶
Time returns the current, corrected local time using information returned from the remote NTP server. On error, Time returns the uncorrected local system time.
The server address is of the form "host", "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port". The host may contain an IPv4, IPv6 or domain name address. When specifying both a port and an IPv6 address, one of the bracket formats must be used. If no port is included, NTP default port 123 is used.
Types ¶
type AuthOptions ¶ added in v0.3.1
type AuthOptions struct { // Type determines the cryptographic hash algorithm used to compute the // authentication digest or CMAC. Type AuthType // The cryptographic key used by the client to perform authentication. The // key may be hex-encoded or ascii-encoded. To use a hex-encoded key, // prefix it by "HEX:". To use an ascii-encoded key, prefix it by // "ASCII:". For example, "HEX:6931564b4a5a5045766c55356b30656c7666316c" // or "ASCII:cvuZyN4C8HX8hNcAWDWp". Key string // The identifier used by the NTP server to identify which key to use // for authentication purposes. KeyID uint16 }
AuthOptions contains fields used to configure symmetric key authentication for an NTP query.
type AuthType ¶ added in v0.3.1
type AuthType int
AuthType specifies the cryptographic hash algorithm used to generate a symmetric key authentication digest (or CMAC) for an NTP message. Please note that MD5 and SHA1 are no longer considered secure; they appear here solely for compatibility with existing NTP server implementations.
type Extension ¶ added in v0.3.1
type Extension interface { // ProcessQuery is called when the client is about to send a query to the // NTP server. The buffer contains the NTP header. It may also contain // extension fields added by extensions processed prior to this one. ProcessQuery(buf *bytes.Buffer) error // ProcessResponse is called after the client has received the server's // NTP response. The buffer contains the entire message returned by the // server. ProcessResponse(buf []byte) error }
An Extension adds custom behaviors capable of modifying NTP packets before being sent to the server and processing packets after being received by the server.
type HostResponse ¶ added in v0.3.1
func HostPreferred ¶ added in v0.3.1
func HostPreferred(hosts []string) *HostResponse
HostPreferred 选择最快的 NTP Host
type LeapIndicator ¶
type LeapIndicator uint8
The LeapIndicator is used to warn if a leap second should be inserted or deleted in the last minute of the current month.
type QueryOptions ¶
type QueryOptions struct { // Timeout determines how long the client waits for a response from the // server before failing with a timeout error. Defaults to 5 seconds. Timeout time.Duration // Version of the NTP protocol to use. Defaults to 4. Version int // LocalAddress contains the local IP address to use when creating a // connection to the remote NTP server. This may be useful when the local // system has more than one IP address. This address should not contain // a port number. LocalAddress string // TTL specifies the maximum number of IP hops before the query datagram // is dropped by the network. Defaults to the local system's default value. TTL int // Auth contains the settings used to configure NTP symmetric key // authentication. See RFC 5905 for further details. Auth AuthOptions // Extensions may be added to modify NTP queries before they are // transmitted and to process NTP responses after they arrive. Extensions []Extension // Dialer is a callback used to override the default UDP network dialer. // The localAddress is directly copied from the LocalAddress field // specified in QueryOptions. It may be the empty string or a host address // (without port number). The remoteAddress is the "host:port" string // derived from the first parameter to QueryWithOptions. The // remoteAddress is guaranteed to include a port number. Dialer func(localAddress, remoteAddress string) (net.Conn, error) // Dial is a callback used to override the default UDP network dialer. // // DEPRECATED. Use Dialer instead. Dial func(laddr string, lport int, raddr string, rport int) (net.Conn, error) // Port indicates the port used to reach the remote NTP server. // // DEPRECATED. Embed the port number in the query address string instead. Port int }
QueryOptions contains configurable options used by the QueryWithOptions function.
type Response ¶
type Response struct { // Time is the transmit time reported by the server just before it // responded to the client's NTP query. You should not use this value // for time synchronization purposes. Use the ClockOffset instead. Time time.Time // ClockOffset is the estimated offset of the local system clock relative // to the server's clock. Add this value to subsequent local system time // measurements in order to obtain a more accurate time. ClockOffset time.Duration // RTT is the measured round-trip-time delay estimate between the client // and the server. RTT time.Duration // Precision is the reported precision of the server's clock. Precision time.Duration // Version is the NTP protocol version number reported by the server. Version int // Stratum is the "stratum level" of the server. The smaller the number, // the closer the server is to the reference clock. Stratum 1 servers are // attached directly to the reference clock. A stratum value of 0 // indicates the "kiss of death," which typically occurs when the client // issues too many requests to the server in a short period of time. Stratum uint8 // ReferenceID is a 32-bit integer identifying the server or reference // clock. For stratum 1 servers, this is typically a meaningful // zero-padded ASCII-encoded string assigned to the clock. For stratum 2+ // servers, this is a reference identifier for the server and is either // the server's IPv4 address or a hash of its IPv6 address. For // kiss-of-death responses (stratum 0), this is the ASCII-encoded "kiss // code". ReferenceID uint32 // ReferenceTime is the time when the server's system clock was last // set or corrected. ReferenceTime time.Time // RootDelay is the server's estimated aggregate round-trip-time delay to // the stratum 1 server. RootDelay time.Duration // RootDispersion is the server's estimated maximum measurement error // relative to the stratum 1 server. RootDispersion time.Duration // RootDistance is an estimate of the total synchronization distance // between the client and the stratum 1 server. RootDistance time.Duration // Leap indicates whether a leap second should be added or removed from // the current month's last minute. Leap LeapIndicator // MinError is a lower bound on the error between the client and server // clocks. When the client and server are not synchronized to the same // clock, the reported timestamps may appear to violate the principle of // causality. In other words, the NTP server's response may indicate // that a message was received before it was sent. In such cases, the // minimum error may be useful. MinError time.Duration // KissCode is a 4-character string describing the reason for a // "kiss of death" response (stratum=0). For a list of standard kiss // codes, see https://tools.ietf.org/html/rfc5905#section-7.4. KissCode string // Poll is the maximum interval between successive NTP query messages to // the server. Poll time.Duration // contains filtered or unexported fields }
A Response contains time data, some of which is returned by the NTP server and some of which is calculated by this client.
func GetResponse ¶ added in v0.3.1
GetResponse 获取 NTP 响应, 无效值返回 nil
func Query ¶
Query requests time data from a remote NTP server. The response contains information from which a more accurate local time can be inferred.
The server address is of the form "host", "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port". The host may contain an IPv4, IPv6 or domain name address. When specifying both a port and an IPv6 address, one of the bracket formats must be used. If no port is included, NTP default port 123 is used.
func QueryWithOptions ¶
func QueryWithOptions(address string, opt QueryOptions) (*Response, error)
QueryWithOptions performs the same function as Query but allows for the customization of certain query behaviors. See the comments for Query and QueryOptions for further details.
func (*Response) IsKissOfDeath ¶ added in v0.3.1
IsKissOfDeath returns true if the response is a "kiss of death" from the remote server. If this function returns true, you may examine the response's KissCode value to determine the reason for the kiss of death.
func (*Response) ReferenceString ¶ added in v0.3.1
ReferenceString returns the response's ReferenceID value formatted as a string. If the response's stratum is zero, then the "kiss o' death" string is returned. If stratum is one, then the server is a reference clock and the reference clock's name is returned. If stratum is two or greater, then the ID is either an IPv4 address or an MD5 hash of the IPv6 address; in either case the reference string is reported as 4 dot-separated decimal-based integers.