"Rust in Action" reading notes - Chapter 9, NTP understands the same formula from different angles
[Copy link]
Many network devices need to obtain network time for time adjustment, and the protocol used is NTP. The rust implementation process is very simple, that is, sending udp, obtaining the return value interpretation and calculation:
fn ntp_roundtrip(
host: &str,
port: u16,
) -> Result<NTPResult, std::io::Error> {
let destination = format!("{}:{}", host, port);
let timeout = Duration::from_secs(1);
let request = NTPMessage::client();
let mut response = NTPMessage::new();
let message = request.data;
let udp = UdpSocket::bind(LOCAL_ADDR)?;
udp.connect(&destination).expect("unable to connect");
let t1 = Utc::now();
udp.send(&message)?;
udp.set_read_timeout(Some(timeout))?;
udp.recv_from(&mut response.data)?;
let t4 = Utc::now();
let t2: DateTime<Utc> =
response
.rx_time()
.unwrap()
.into();
let t3: DateTime<Utc> =
response
.tx_time()
.unwrap()
.into();
Ok(NTPResult {
t1: t1,
t2: t2,
t3: t3,
t4: t4,
})
}
The key point to understand is the calculation of T1, T2, T3, and T4. According to the definition:
There are two formulas for the use of these four ts:
It seems that the first formula divided by 2 is the second one, but why is there so much trouble?
Because of their different meanings, the first formula represents the difference between the time calculated on the client and the time calculated on the server (the difference between the two gray boxes in the figure above), and the second formula is the sum of the time it takes to send the request and the time it takes to receive it back (the sum of the two red dashed arrows in the figure above).
|