a simple ntp client package for go

Overview

Build Status GoDoc

ntp

The ntp package is an implementation of a Simple NTP (SNTP) client based on RFC5905. It allows you to connect to a remote NTP server and request information about the current time.

Querying the current time

If all you care about is the current time according to a remote NTP server, simply use the Time function:

time, err := ntp.Time("0.beevik-ntp.pool.ntp.org")

Querying time metadata

To obtain the current time as well as some additional metadata about the time, use the Query function:

response, err := ntp.Query("0.beevik-ntp.pool.ntp.org")
time := time.Now().Add(response.ClockOffset)

Alternatively, use the QueryWithOptions function if you want to change the default behavior used by the Query function:

options := ntp.QueryOptions{ Timeout: 30*time.Second, TTL: 5 }
response, err := ntp.QueryWithOptions("0.beevik-ntp.pool.ntp.org", options)
time := time.Now().Add(response.ClockOffset)

The Response structure returned by Query includes the following information:

  • Time: The time the server transmitted its response, according to its own clock.
  • ClockOffset: The estimated offset of the local system clock relative to the server's clock. For a more accurate time reading, you may add this offset to any subsequent system clock reading.
  • RTT: An estimate of the round-trip-time delay between the client and the server.
  • Precision: The precision of the server's clock reading.
  • Stratum: The server's stratum, which indicates the number of hops from the server to the reference clock. A stratum 1 server is directly attached to the reference clock. If the stratum is zero, the server has responded with the "kiss of death".
  • ReferenceID: A unique identifier for the consulted reference clock.
  • ReferenceTime: The time at which the server last updated its local clock setting.
  • RootDelay: The server's aggregate round-trip-time delay to the stratum 1 server.
  • RootDispersion: The server's estimated maximum measurement error relative to the reference clock.
  • RootDistance: An estimate of the root synchronization distance between the client and the stratum 1 server.
  • Leap: The leap second indicator, indicating whether a second should be added to or removed from the current month's last minute.
  • MinError: A lower bound on the clock error between the client and the server.
  • KissCode: A 4-character string describing the reason for a "kiss of death" response (stratum=0).
  • Poll: The maximum polling interval between successive messages to the server.

The Response structure's Validate method performs additional sanity checks to determine whether the response is suitable for time synchronization purposes.

err := response.Validate()
if err == nil {
    // response data is suitable for synchronization purposes
}

Using the NTP pool

The NTP pool is a shared resource used by people all over the world. To prevent it from becoming overloaded, please avoid querying the standard pool.ntp.org zone names in your applications. Instead, consider requesting your own vendor zone or joining the pool.

Issues
  • Add RFC5905 sanity checks for NTP packets

    Add RFC5905 sanity checks for NTP packets

    I suggest to add these sanity checks to sntp client library as it was suggested during IRC discussion of prometheus/node_exporter#655 that these checks may be useful to other users of the library.

    I also add code branch to discard packets with clock ticking backwards.

    If NTP server reports it's clock ticking backwards it's absolutely unsuitable as a time source (or just sends random data as a reply).

    If NTP client has clock ticking backwards, it should use monotonic clock, but monotonic clock are only available with Go 1.9 that is not released yet, so these packets are also dropped as time estimates are obviously wrong. It may be considered regression as Response.Time still may be usable, although Offset and RTT are obviously meaningless in this case. I think that the way to go is to drop these packets right now and upgrade to monotonic clock after Go 1.9 release.

    Also, I'm unsure if Time and TimeV should run IsUsable() sanity check before returning server time. I decided not to run it.

    opened by darkk 13
  • time.Duration to NtpTime

    time.Duration to NtpTime

    Any chance for you to add the reverse function of (t ntpTimeShort) Duration() time.Duration?

    like a toNtpTime(t time.Duration) NtpTime function?

    I can't figure the formula myself.

    Or can you provide any link where I can find the formula? Sorry but I can't contact you privately

    opened by traveltoaiur 6
  • Bring calculations into better alignment with RFC.

    Bring calculations into better alignment with RFC.

    RTT calculation can no longer yield a result less than the precision value. Account for minimum dispersion in the calculation of the root distance. Updated the comments for all calculated fields to better match the RFC. Removed casuality violation until I have a better understanding of how it's useful.

    opened by beevik 4
  • Support IPv6-only hosts

    Support IPv6-only hosts

    Hi,

    I have machines that have only IPv6 connectivity. Using net.ResolveUDPAddr with udp will always* return IPv4 if the DNS name has an IPv4 configured, regardless if the system can route it.

    Consider either giving the user a possibility of specifying "udp6" for IPv6, or better yet try with "udp" first, then "udp4" and then "udp6".

    Thanks! * See https://golang.org/src/net/ipsock.go line 85.

    enhancement 
    opened by bluecmd 3
  • Please license the code

    Please license the code

    Hi,

    I am packaging dependencies for prometheus.io for Debian, and since they use your package I need to package it too. The problem is that without an explicit license attached to the code it is not legal for Debian to include the package.

    Could you add that?

    opened by NightTsarina 3
  • KoD support?

    KoD support?

    Any plan on KoD support?

    In NTPv4 and SNTPv4, packets of this kind are called Kiss-o'-Death (KoD) packets, and the ASCII messages they convey are called kiss codes. The KoD packets got their name because an early use was to tell clients to stop sending packets that violate server access controls.

    opened by mengzhuo 2
  • Don't change stratum data

    Don't change stratum data

    It's confusing that stratum=0 gets changed to 16.

    I understand that implementations are suggested to do this, but I think it's "later" than "when processing packets". For my application I want to know what the server said.

    The RFC also says to process the referenceID separately if the stratum is 0, right now that's impossible to do correctly with the Go client because you can't know if the server said 16 or if it said 0 and it was changed.

    opened by abh 1
  • RFC5905 says that SNTP client should use transmit timestamp

    RFC5905 says that SNTP client should use transmit timestamp

    Difference between ReceiveTime and TransmitTime is usually <1ms, but RFC says that trivial SNTP client should use TransmitTime.

    I'm sorry for PR storm, I'm doing several reading passes through the RFC :-) It's probably the last one.

    opened by darkk 1
  • Add configurable query options: timeout, IP TTL, NTP Server port

    Add configurable query options: timeout, IP TTL, NTP Server port

    I need SetTTL(1) to limit my code talking to NTP servers within LAN as a precaution measure (to avoid overloading NTP pool in case of misconfiguration), so I convert bare timeout to structure of options and add it there.

    opened by darkk 1
  • Two test cases try to access the Internet

    Two test cases try to access the Internet

    Running the test cases during package build on Ubuntu fail [1]:

       dh_auto_test -O--builddirectory=_build -O--buildsystem=golang
    	cd _build && go test -vet=off -v -p 4 github.com/beevik/ntp
    === RUN   TestTime
        ntp_test.go:34: [0.beevik-ntp.pool.ntp.org] Query failed: lookup 0.beevik-ntp.pool.ntp.org: no such host
    --- FAIL: TestTime (0.02s)
    === RUN   TestTimeFailure
    --- PASS: TestTimeFailure (5.01s)
    === RUN   TestQuery
        ntp_test.go:77: [0.beevik-ntp.pool.ntp.org] ----------------------
        ntp_test.go:78: [0.beevik-ntp.pool.ntp.org] NTP protocol version 4
        ntp_test.go:34: [0.beevik-ntp.pool.ntp.org] Query failed: lookup 0.beevik-ntp.pool.ntp.org: no such host
    --- FAIL: TestQuery (0.00s)
    === RUN   TestValidate
    --- PASS: TestValidate (0.00s)
    === RUN   TestBadServerPort
    --- PASS: TestBadServerPort (0.00s)
    === RUN   TestTTL
    --- PASS: TestTTL (0.00s)
    === RUN   TestQueryTimeout
    --- PASS: TestQueryTimeout (0.00s)
    === RUN   TestShortConversion
    --- PASS: TestShortConversion (0.00s)
    === RUN   TestLongConversion
    --- PASS: TestLongConversion (0.00s)
    === RUN   TestOffsetCalculation
    --- PASS: TestOffsetCalculation (0.00s)
    === RUN   TestOffsetCalculationNegative
    --- PASS: TestOffsetCalculationNegative (0.00s)
    === RUN   TestMinError
    --- PASS: TestMinError (0.01s)
    === RUN   TestTimeConversions
    --- PASS: TestTimeConversions (0.00s)
    === RUN   TestKissCode
    --- PASS: TestKissCode (0.00s)
    FAIL
    FAIL	github.com/beevik/ntp	5.091s
    FAIL
    

    This is caused by the package build host having no Internet access. Please change the test cases to not require Internet access. The positive side effect will be that the test cases can't break by changes to the NTP host 0.beevik-ntp.pool.ntp.org.

    [1] Full log: https://launchpadlibrarian.net/575776629/buildlog_ubuntu-jammy-amd64.golang-github-beevik-ntp_0.3.0-2_BUILDING.txt.gz

    opened by bdrung 0
  • Support for querying clock discipline system variables?

    Support for querying clock discipline system variables?

    Hi,

    I wanted to use this package to monitor stratum 1 servers. There doesn't seem to be support for querying some fields useful for plotting the oscillator stability. I'm looking for in particular these fields reported by ntpq -c rv

    • time constant
    • frequency error
    • system jitter
    • clock jitter
    • clock wander

    Would you consider adding support for that?

    opened by tnn2 0
  • i/o timeout error and bogus values

    i/o timeout error and bogus values

    The following is the output of a program querying the ntp servers 0.centos.pool.ntp.org and 1.centos.pool.ntp.org while sleeping for a few seconds between queries.

    I've run into two kinds of errors

    1. Failed to reach NTP server: 1.centos.pool.ntp.org error: read udp 10.4.67.150:37627->171.66.97.126:123: i/o timeout. I've tried increasing the timeout to 10 seconds from the default of 5 but that hasn't helped. Please share any suggestions you might have.

    2. And the other is for invalid values Reached NTP server: 1.centos.pool.ntp.org offset: 3754691965.127657. Where the 3754691965.127657 is way higher than the expected offset.

    I've been using the 0.3 release but have experienced the same errors in the 0.2 release.

    Reached NTP server: 0.centos.pool.ntp.org offset: 19.631600
    Failed to reach NTP server: 1.centos.pool.ntp.org error: read udp 10.4.67.150:57557->104.155.144.4:123: i/o timeout
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.626120
    Reached NTP server: 1.centos.pool.ntp.org offset: 19.636507
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.631544
    Failed to reach NTP server: 1.centos.pool.ntp.org error: read udp 10.4.67.150:38249->104.155.144.4:123: i/o timeout
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.626148
    Failed to reach NTP server: 1.centos.pool.ntp.org error: read udp 10.4.67.150:34181->162.248.241.94:123: i/o timeout
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.631553
    Reached NTP server: 1.centos.pool.ntp.org offset: 19.636571
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.633790
    Reached NTP server: 1.centos.pool.ntp.org offset: 3754691965.127657
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.635017
    Reached NTP server: 1.centos.pool.ntp.org offset: 19.626531
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.626131
    Reached NTP server: 1.centos.pool.ntp.org offset: 19.634028
    Reached NTP server: 0.centos.pool.ntp.org offset: 19.631843
    Failure count: 6 bogus values: 4
    
    opened by mohdahmad17 5
Releases(v0.3.0)
  • v0.3.0(Mar 19, 2020)

    There have been no breaking changes or further deprecations since the previous release.

    Changes

    • Fixed a bug in the calculation of NTP timestamps. (https://github.com/beevik/ntp/commit/9bcd064241ee47911f6af536e6899047689c5f83)
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Oct 20, 2017)

  • v0.1.1(Oct 3, 2017)

    Breaking changes

    • Removed the MaxStratum constant.

    Deprecations

    • Officially deprecated the TimeV function.

    Internal changes

    • Removed minDispersion from the RootDistance calculation, since the value was arbitrary.
    • Moved some validation into main code path so that invalid TransmitTime and mode responses trigger an error even when Response.Validate is not called.
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Sep 30, 2017)

    This is the initial release of the ntp package. Currently it supports the following features:

    • Time() to query the current time according to a remote NTP server.
    • Query() to query multiple pieces of time-related information from a remote NTP server.
    • QueryWithOptions(), which is like Query() but with the ability to override default query options.

    Time-related information returned by the Query functions includes:

    • Time: the time the server transmitted its response, according to the server's clock.
    • ClockOffset: the estimated offset of the client's clock relative to the server's clock. You may apply this offset to any local system clock reading once the query is complete.
    • RTT: an estimate of the round-trip-time delay between the client and the server.
    • Precision: the precision of the server's clock reading.
    • Stratum: the "stratum" level of the server, where 1 indicates a server directly connected to a reference clock, and values greater than 1 indicating the number of hops from the reference clock.
    • ReferenceID: A unique identifier for the NTP server that was contacted.
    • ReferenceTime: The time at which the server last updated its local clock setting.
    • RootDelay: The server's round-trip delay to the reference clock.
    • RootDispersion: The server's total dispersion to the referenced clock.
    • RootDistance: An estimate of the root synchronization distance.
    • Leap: The leap second indicator.
    • MinError: A lower bound on the clock error between the client and the server.
    • Poll: the maximum polling interval between successive messages on the server.

    The Response structure returned by the Query functions also contains a Response.Validate() function that returns an error if any of the fields returned by the server are invalid.

    Source code(tar.gz)
    Source code(zip)
Owner
Brett Vickers
Code hacker. Game dev.
Brett Vickers
Prisma Client Go is an auto-generated and fully type-safe database client

Prisma Client Go Typesafe database access for Go Quickstart • Website • Docs • API reference • Blog • Slack • Twitter Prisma Client Go is an auto-gene

Prisma 1.2k Jul 2, 2022
The Dual-Stack Dynamic DNS client, the world's first dynamic DNS client built for IPv6.

dsddns DsDDNS is the Dual-Stack Dynamic DNS client. A dynamic DNS client keeps your DNS records in sync with the IP addresses associated with your hom

Ryan Young 10 Jun 20, 2022
Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Chino Chang 1 Nov 11, 2021
Server and client implementation of the grpc go libraries to perform unary, client streaming, server streaming and full duplex RPCs from gRPC go introduction

Description This is an implementation of a gRPC client and server that provides route guidance from gRPC Basics: Go tutorial. It demonstrates how to u

Joram Wambugu 0 Nov 24, 2021
Godaddy-domains-client-go - Godaddy domains api Client golang - Write automaticly from swagger codegen

Go API client for swagger Overview This API client was generated by the swagger-codegen project. By using the swagger-spec from a remote server, you c

Mickael Stanislas 0 Jan 9, 2022
Tailscale-client-go - A client implementation for the Tailscale HTTP API

tailscale-client-go A client implementation for the Tailscale HTTP API Example p

David Bond 9 Jun 8, 2022
Comunicación de envios de archivos entres cliente-servidor, client-client.

Client - Server - Client Estes es un proyecto simple de comunicacion de envios de archivos del cliente al servidor y viceversamente, y de cliente a cl

Melvin RB 0 Feb 11, 2022
FTP client package for Go

goftp A FTP client package for Go Install go get -u github.com/jlaffaye/ftp Documentation https://pkg.go.dev/github.com/jlaffaye/ftp?tab=doc Example

Julien Laffaye 950 Jun 30, 2022
A STOMP Client package for go developers, supporting all STOMP specification levels.

stompngo - A STOMP 1.0, 1.1 and 1.2 Client Package Features Full support of STOMP protocols: Protocol Level 1.0 Protocol Level 1.1 Protocol Level 1.2

Guy M. Allard 138 Mar 7, 2022
Full-featured BitTorrent client package and utilities

torrent This repository implements BitTorrent-related packages and command-line utilities in Go. The emphasis is on use as a library from other projec

Matt Joiner 4.4k Jul 1, 2022
An API Client package for Studyplus for School SYNC API

Studyplus for School SYNC API Client This project is currently alpha, possibility having breaking changes. studyplus_for_school_sync_go is a API clien

atomiyama 4 Aug 2, 2021
A minimal analytics package to start collecting traffic data without client dependencies.

go-web-analytics A minimal analytics package to start collecting traffic data without client dependencies. Logging incoming requests import "github.co

Jake Kalstad 0 Nov 23, 2021
Tscert - Minimal package for just the HTTPS cert fetching part of the Tailscale client API

tscert This is a stripped down version of the tailscale.com/client/tailscale Go

Tailscale 13 May 31, 2022
Fetch-npm-package - A small utility that can be used to fetch a given version of a NPM package

Use fetch-npm-package <package> <version> <output-dir> E.g. fetch-npm-package is

Bjørn Erik Pedersen 1 May 21, 2022
Simple mDNS client/server library in Golang

mdns Simple mDNS client/server library in Golang. mDNS or Multicast DNS can be used to discover services on the local network without the use of an au

HashiCorp 891 Jun 29, 2022
A simple non-official client for qvapay service with go, for our comunity

qvapay-go A simple non-official client for qvapay service with go, for our comunity Setup You can install this package by using the go get tool and in

Kenrique Ortega 8 Dec 26, 2021
Simple REST client library in Go

Simple REST client library in Go Context The goal was to make a minimal library that could be easily reused and expanded in other projects. It doesn't

okay_awright 0 Nov 5, 2021
go HTTP client that makes it plain simple to configure TLS, basic auth, retries on specific errors, keep-alive connections, logging, timeouts etc.

goat Goat, is an HTTP client built on top of a standard Go http package, that is extremely easy to configure; no googling required. The idea is simila

VSPAZ 1 Jun 25, 2022