Каковы все поля в ответе Python ntplib и как они используются?

Я хотел бы измерить разницу между локальными часами и удаленным процессором, на котором работает NTP-сервер.

Я могу получить tx_time ответа, как показано ниже, но лучшая оценка будет включать в себя некоторую оценку сетевых задержек. В ответном сообщении NTP есть и другие поля, которые также следует использовать.

import ntplib
from time import ctime,time

addr_remote = '128.128.204.207'

c = ntplib.NTPClient()
remote = c.request(addr_remote)
local = time()
print("REMOTE: " + ctime(remote.tx_time) + "   <reference clock>   ") 
print("LOCAL:  " + ctime(local)        + "   delta: " + str(local - remote.tx_time ))

Если я посмотрю на "удаленное":

for attr in dir(remote):
    print("remote.%s = %r" % (attr, getattr(remote, attr)))

Я понимаю:

remote.delay = 0.0
remote.dest_time = 1531863145.9309998
remote.dest_timestamp = 3740851945.9309998
remote.from_data = <bound method NTPPacket.from_data of <ntplib.NTPStats object at 0x000000000265B2E8>>
remote.leap = 0
remote.mode = 4
remote.offset = -1.8789582252502441
remote.orig_time = 1531863145.9309998
remote.orig_timestamp = 3740851945.9309998
remote.poll = 0
remote.precision = -7
remote.recv_time = 1531863144.0520415
remote.recv_timestamp = 3740851944.0520415
remote.ref_id = 0
remote.ref_time = 0.0
remote.ref_timestamp = 2208988800.0
remote.root_delay = 0.0
remote.root_dispersion = 0.0
remote.stratum = 9
remote.to_data = <bound method NTPPacket.to_data of <ntplib.NTPStats object at 0x000000000265B2E8>>
remote.tx_time = 1531863144.0520415
remote.tx_timestamp = 3740851944.0520415

Итак, как мне их использовать:

  • время_назначения
  • исходное_время
  • время_получения
  • время_передачи

удалить задержки в сети и получить более точную оценку разницы часов?


person Matt    schedule 17.07.2018    source источник


Ответы (2)


Клиент NTP отправляет пакет со своим локальным временем orig_time, который сервер NTP получает в момент времени сервера recv_time. Затем сервер отвечает в серверное время tx_time, а клиент получает этот ответ в местное время dest_time.

Поездка туда и обратно delay рассчитывается как recv_time - orig_time + dest_time - tx_time, а смещение между часами равно offset = (recv_time - orig_time + tx_time - dest_time) / 2.

Предполагая, что два пакета NTP идут по согласованным путям, правильное скорректированное время будет просто dest_time + offset, что эквивалентно tx_time + delay/2.

person Vic    schedule 25.04.2019

Я нашел этот ответ, пытаясь синхронизировать клиентский компьютер с временем NTP и проверив, действительно ли он синхронизирован. На основе @Vic это означает, что часы клиента (по сравнению с часами сервера NTP) всегда выключены:

dest_time + offset = tx_time + delay/2
dest_time - tx_time = delay/2 - offset

i.e.

correction = delay/2 - offset

Как сказал @Vic, пакеты могут идти по разным маршрутам, входящим и исходящим, но в среднем correction должно дать вам смещение часов (я думаю). Даже при синхронизации с time.nist.gov с os.system('w32tm /resync/nowait') мой компьютер каким-то образом всегда отключается на 40 мс. Комментарии приветствуются!

Это мой код.

import ntplib
from datetime import datetime, timezone
def get_ntp_time():
    ntp_pool = ['pool.ntp.org', 'time.nist.gov']
    def call_ntp(serverAddress):
        call = ntplib.NTPClient()
        return call.request(server, version=3)
    for server in ntp_pool:
        response = call_ntp(server)
        print(f"server: {server}")
        print(f"request packet sent (as LOCAL client time, orig_time): {datetime.fromtimestamp(response.orig_time, timezone.utc)}")
        print(f"request packet received (as NTP server time, recv_time): {datetime.fromtimestamp(response.recv_time, timezone.utc)}")
        print(f"response packet sent (as NTP server time, tx_time): {datetime.fromtimestamp(response.tx_time, timezone.utc)}")
        print(f"response packet received (as LOCAL client time, dest_time): {datetime.fromtimestamp(response.dest_time, timezone.utc)}")
        print(f'round trip duration: {response.delay} s')
        print(f'* adjusted time, tx_time + delay/2: {datetime.fromtimestamp(response.tx_time + response.delay/2, timezone.utc)}')
        print(f'* adjusted time, dest_time + offset: {datetime.fromtimestamp(response.dest_time + response.offset, timezone.utc)}')
        print(f'correction to client: {response.delay/2 - response.offset} s\n')
        # for attr in dir(response):
            # if not attr .startswith('_'):
                # print("response.%s = %r" % (attr, getattr(response, attr)))
        print('-')
get_ntp_time()

Ответ:

server: pool.ntp.org
request packet sent (as LOCAL client time, orig_time): 2021-04-23 16:14:46.544797+00:00
request packet received (as NTP server time, recv_time): 2021-04-23 16:14:46.535852+00:00
response packet sent (as NTP server time, tx_time): 2021-04-23 16:14:46.535862+00:00
response packet received (as LOCAL client time, dest_time): 2021-04-23 16:14:46.579710+00:00
round trip duration: 0.03490257263183594 s
* adjusted time, tx_time + delay/2: 2021-04-23 16:14:46.553314+00:00
* adjusted time, dest_time + offset: 2021-04-23 16:14:46.553314+00:00
correction to client: 0.04384756088256836 s

-
server: time.nist.gov
request packet sent (as LOCAL client time, orig_time): 2021-04-23 16:14:46.642192+00:00
request packet received (as NTP server time, recv_time): 2021-04-23 16:14:46.641157+00:00
response packet sent (as NTP server time, tx_time): 2021-04-23 16:14:46.641158+00:00
response packet received (as LOCAL client time, dest_time): 2021-04-23 16:14:46.689054+00:00
round trip duration: 0.04686117172241211 s
* adjusted time, tx_time + delay/2: 2021-04-23 16:14:46.664588+00:00
* adjusted time, dest_time + offset: 2021-04-23 16:14:46.664588+00:00
correction to client: 0.0478968620300293 s

-
person Alfred Wallace    schedule 23.04.2021