356 views|1 replies

183

Posts

12

Resources
The OP
 

"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:

\delta = (T_{4}-T_{1}) -(T_{3}-T_{2})

\theta = \frac{ (T_{2}-T_{1}) +(T_{4}-T_{3})}{2}

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).

This post is from Programming Basics

Latest reply

The author is very careful in reading. Thank you for sharing NTP's different perspectives on understanding the same formula.   Details Published on 2024-6-19 07:31
 

6593

Posts

0

Resources
2
 

The author is very careful in reading. Thank you for sharing NTP's different perspectives on understanding the same formula.

This post is from Programming Basics
 
 
 

Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list