Skip to content

Instantly share code, notes, and snippets.

@lotas
Created May 24, 2024 14:05
Show Gist options
  • Save lotas/4c3aac1ff00d46b9c32d1a2d487c2fe7 to your computer and use it in GitHub Desktop.
Save lotas/4c3aac1ff00d46b9c32d1a2d487c2fe7 to your computer and use it in GitHub Desktop.
time client NIST
use std::net::TcpStream;
use std::io::{self, Read};
use std::time::{SystemTime, UNIX_EPOCH};
fn get_current_unix_timestamp() -> u64 {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Ehmmm..");
// Adjust for the difference between 1900 and 1970
let seconds_since_1900 = 2208988800;
seconds_since_1900 + since_the_epoch.as_secs()
}
fn get_nist_time(host: &str, port: u16) -> Result<u32, io::Error> {
let address = format!("{}:{}", host, port);
let mut stream = TcpStream::connect(&address)?;
let mut buffer = [0; 4];
stream.read(&mut buffer)?;
let number = u32::from_be_bytes(buffer);
Ok(number)
}
fn main() {
let host = "time.nist.gov";
let port = 37;
match get_nist_time(host, port) {
Ok(nist_time) => {
println!("NIST time: {}", nist_time);
let local = get_current_unix_timestamp();
println!("Syst time: {}", local);
println!("Diff: {}", local - nist_time as u64);
}
Err(e) => {
println!("Failed to read NIST time: {}", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment