在 ubuntu 中使用套接字查询 NTP 数据

在 ubuntu 中使用套接字查询 NTP 数据

我已将 ntp 配置为使用 gpsd 作为我机器上的参考服务器。我使用 udp 套接字直接从 ntp 查询数据。对于 ip 地址,我使用localhostport_number = 123。我使用的数据包结构是:

typedef struct {
  uint8_t li_vn_mode;  // Eight bits. li, vn, and mode.
                       // li.   Two bits.   Leap indicator.
                       // vn.   Three bits. Version number of the protocol.
                       // mode. Three bits. Client will pick mode 3 for client.

  uint8_t stratum;  // Eight bits. Stratum level of the local clock.
  uint8_t poll;     // Eight bits. Maximum interval between successive messages.
  uint8_t precision;  // Eight bits. Precision of the local clock.

  uint32_t rootDelay;  // 32 bits. Total round trip delay time.
  uint32_t
      rootDispersion;  // 32 bits. Max error aloud from primary clock source.
  uint32_t refId;      // 32 bits. Reference clock identifier.

  uint32_t refTm_s;  // 32 bits. Reference time-stamp seconds.
  uint32_t refTm_f;  // 32 bits. Reference time-stamp fraction of a second.

  uint32_t origTm_s;  // 32 bits. Originate time-stamp seconds.
  uint32_t origTm_f;  // 32 bits. Originate time-stamp fraction of a second.

  uint32_t rxTm_s;  // 32 bits. Received time-stamp seconds.
  uint32_t rxTm_f;  // 32 bits. Received time-stamp fraction of a second.

  uint32_t txTm_s;  // 32 bits and the most important field the client cares
                    // about. Transmit time-stamp seconds.
  uint32_t txTm_f;  // 32 bits. Transmit time-stamp fraction of a second.

} ntp_packet;  // Total: 384 bits or 48 bytes.

通过这个,我使用公式计算偏移量,

0.5 * ((server_receivetime - client_sendtime) + (server_sendtime - client_receivetime));

现在我手动停止 gpsd 服务并运行此程序ntpq -pntpq命令显示偏移量超过 10 秒,而我的程序始终给出 0.008 毫秒的偏移量。看来我的程序对客户端和服务器使用相同的时钟。而 ntpq 正在从其他地方查询。我如何才能获得与ntpq命令相同的偏移量?

如果我使用 ip_address 作为服务器 ="us.pool.ntp.org"我会得到大约 12 毫秒的偏移量。

相关内容