Giter Club home page Giter Club logo

sntpc's Introduction

sntpc test

Simple Rust SNTP client


This crate provides a method for sending requests to NTP servers and process responses, extracting received timestamp.

Supported SNTP protocol versions:

Documentation


https://docs.rs/sntpc

Installation


This crate works with Cargo and is on crates.io. Add it to your Cargo.toml like so:

[dependencies]
sntpc = "0.3.7"

By calling the get_time() method and providing a proper NTP pool or server you should get a valid synchronization timestamp:

use std::net::UdpSocket;
use std::time::Duration;

fn main() {
    let socket =
        UdpSocket::bind("0.0.0.0:0").expect("Unable to create UDP socket");
    socket
       .set_read_timeout(Some(Duration::from_secs(2)))
       .expect("Unable to set UDP socket read timeout");
    let result =
        sntpc::simple_get_time("time.google.com:123", socket);

    match result {
       Ok(time) => {
           let microseconds = sntpc::fraction_to_microseconds(time.sec_fraction());
           println!("Got time: {}.{}", time.sec(), microseconds);
       }
       Err(err) => println!("Err: {:?}", err),
    }
 }

no_std support


Currently, there are basic no_std support available, thanks to no-std-net crate. There is an example available on how to use smoltcp stack and that should provide general idea on how to bootstrap no_std networking and timestamping tools for sntpc library usage

async support


Feature async_tokio allows to use crate together with tokio. There is an example: examples/tokio.rs.

There is also no_std support with feature async, but it requires Rust >= 1.75-nightly version. The example can be found in separate repository.

Examples


You can find several examples that shows how to use the library in details under [examples/] folder. Currently, there are examples that show:

  • usage of SNTP library in std environment
  • usage of SNTP library with smoltcp TCP/IP stack. Some std dependencies required only due to smoltcp available interfaces

Contribution


Contributions are always welcome! If you have an idea, it's best to float it by me before working on it to ensure no effort is wasted. If there's already an open issue for it, knock yourself out. See the contributing section for additional details

Thanks

  1. Frank A. Stevenson: for implementing stricter adherence to RFC4330 verification scheme
  2. Timothy Mertz: for fixing possible overflow in offset calculation
  3. HannesH: for fixing a typo in the README.md
  4. Richard Penney: for adding two indicators of the NTP server's accuracy into the NtpResult structure
  5. Vitali Pikulik: for adding async support
  6. tsingwong: for fixing invalid link in the README.md

Really appreciate all your efforts! Please let me know if I forgot someone.

License


This project is licensed under:

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in time by you, as defined in the 3-Clause BSD license, shall be licensed as above, without any additional terms or conditions.

sntpc's People

Contributors

hannesgith avatar mertzt89 avatar rwpenney avatar tsingwong avatar vpetrigo avatar vpikulik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sntpc's Issues

[BUG] Incorrect offset calculation

  • OS and version used: Fedora 35
  • Library version used: 0.2

Description of the issue:

Library returns invalid offset/roundtrip values

Code sample exhibiting the issue:

N/A

Console log of the issue:

N/A

[Doc bug] Units of `NtpResult.seconds_fraction` ambiguous

Thanks for a really helpful library! Though I ran into an issue trying to parse NtpResult.seconds_fraction (resp. NtpResult.sec_fraction()):

  1. This states that the value is in microseconds: https://github.com/vpetrigo/sntpc/blob/master/src/lib.rs#L280
  2. This states nanoseconds: https://github.com/vpetrigo/sntpc/blob/master/src/lib.rs#L292
  3. In the example it's in units of 1/u32::MAX of a second (if my reading is right) - i.e. about a quarter of a nanosecond: https://github.com/vpetrigo/sntpc/blob/master/examples/simple_request.rs#L87

I gather that (1) is definitely not the case (since the values are too large), and I suspect that (3) is the real answer, but it would be good to have this clear in the docs. Or perhaps convert the result to micro or nanoseconds, since 1/u32::MAX is a bit awkward to deal with.

Also - and this is minor - but I think in the example using time.sec_fraction() as u64 * 1_000_000 / u32::MAX as u64 to get the decimal points will show the wrong value if the result has fewer than 6 digits. E.g. it would show 1.23 instead of 1.000023. Might be better to just convert to float, e.g.

println!("Got time: {}", time.sec() as f64 + time.sec_fraction() as f64 / u32::MAX as f64);

Add method that supply SocketAddr instead of IP string/domain name

Consider adding a method with the following signature:

pub fn request(ntp_server: &net::SocketAddr, port: u32) -> io::Result<u32>

That allows an user to manually supply the addresses of interest as sometimes DNS resolution may supply "dead"/"irresponsive" server's IP address in a row. So it might be a good idea to traverse other addresses and try to use them instead.

Fix timesync warning

See build output below:

warning: use of deprecated associated function `std::error::Error::description`: use the Display impl or to_string()
  --> src\bin\timesync.rs:44:21
   |
44 |                 err.description()
   |                     ^^^^^^^^^^^
   |
   = note: `#[warn(deprecated)]` on by default

warning: 1 warning emitted

[BUG] Annoying logs

Hi.

I have been using SNTPC in a small library I'm developing and noticed the following logs related to sntpc-0.1.1:

[C:\Users\duall\.cargo\registry\src\github.com-1ecc6299db9ec823\sntpc-0.1.1\src\lib.rs:179] pool = "pool.ntp.org"
[C:\Users\duall\.cargo\registry\src\github.com-1ecc6299db9ec823\sntpc-0.1.1\src\lib.rs:191] &addr = V4(
    212.69.166.153:123,
)
[C:\Users\duall\.cargo\registry\src\github.com-1ecc6299db9ec823\sntpc-0.1.1\src\lib.rs:216] response.0 = 48

My library was compiled using RUSTFLAGS="-C link-arg=-s" cargo build --release, but those logs still showing in the terminal.

So, is there any configuration to remove/disable those logs?

Thank you!

what does offset mean? |offset| always equal to roundtrip/2 in my results.

I ran the example you gave:

use sntpc;

let result = sntpc::request("pool.ntp.org", 123);
if let Ok(sntpc::NtpResult {
    sec, nsec, roundtrip, offset
}) = result {
    println!("NTP server time: {}.{}", sec, nsec);
    println!("Roundtrip time: {}, offset: {}", roundtrip, offset);
}

and in the outputs , |offset|(absolute value of offset) always equal to roundtrip/2.
In my impression, offset generally refers to the difference in time between an external timing reference and time on a local machine. Is this what your offset mean, or does it have another meaning?
Thanks!

[BUG] Wrong SNTP origin timestamp reported

  • OS and version used: Windows 10 1809
  • Library version used: 0.1.1

Description of the issue:

In the debug output it might be noticed that the origin timestamp reported by a NTP server is incorrect (see logs below)

Console log of the issue:

[src\lib.rs:179] pool = "pool.ntp.org"
[src\lib.rs:191] &addr = V4(
    80.240.216.155:123
)
[src\lib.rs:216] response.0 = 48
====================================================
| Mode:		4
| Version:	4
| Leap:		0
| Poll:		3
| Precision:		-24
| Root delay:		297
| Root dispersion:	1226
| Reference ID:		
| Reference timestamp:	16149940269256115971
| Origin timestamp:		9487534654782240553 // <--- !!!
| Receive timestamp:	16149941105786494829
| Transmit timestamp:	16149941105786612562
====================================================
Got time: 1551212382

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.