NTP에서 시간의 의미

  • NTP의 Response Time은 아래와 같은 의미를 가진다

    1. orig_timestamp(Originate Timestamp)-T1: Time at the client when the request departed for the server, in NTP timestamp format.
    2. recv_timestamp(Receive Timestamp)-T2: Time at the server when the request arrived from the client, in NTP timestamp format.
    3. tx_timestamp(Transmit Timestamp)-T3: Time at the server when the response left for the client, in NTP timestamp format.
    4. dest_timestamp(Destination Timestamp)-T4: Time at the client when the reply arrived from the server, in NTP timestamp format.
    • ref_timestamp(Reference Timestamp): Time when the system clock was last set or corrected, in NTP timestamp format

    • offset: NTP 서버의 시간과 local 시간의 차이

      offset = ((recv_timestamp - orig_timestamp) + (tx_timestamp - dest_timestamp))/2

      offset = ((T2 - T1) + (T3 - T4))/2

NTP 서버 및 로컬시간 정보 구하기

  • Local Machine의 현재시간 알아보기(Python)

    python3 -c 'import datetime; print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))'
    
  • NTP Server 정보 확인 (Python)

    import ntplib
    from datetime import datetime
    
    
    client = ntplib.NTPClient()
    server = 'time.bora.net'
    
    resp = client.request(server, version=3)
    
    print("offset", resp.offset)
    print("delay", resp.delay)
    
    # timestamps are converted to native "UNIX" timestamps
    print(resp.orig_time)
    
    print("orig_time:", datetime.utcfromtimestamp(resp.orig_time))
    print("recv_time:", datetime.utcfromtimestamp(resp.recv_time))
    print("tx_time  :", datetime.utcfromtimestamp(resp.tx_time))
    print("dest_time:", datetime.utcfromtimestamp(resp.dest_time))
    

    NTP Server 정보 확인결과

  • NTP Server 정보 확인 ver.2 (Python)

    # UTC version
    import ntplib
    from datetime import datetime, timezone
    def get_ntp_time():
        # ntp_pool = ['time.bora.net', 'pool.ntp.org', 'time.nist.gov']
        ntp_pool = ['time.bora.net']
        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()
    
  • NTP Server 정보 확인 ver.3 (Python)

    # KST version
    import ntplib
    import pytz
    from datetime import datetime, timezone, timedelta
    
    
    def get_ntp_time():
        # ntp_pool = ['time.bora.net', 'pool.ntp.org', 'time.nist.gov']
        ntp_pool = ['time.bora.net']
        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, pytz.timezone('Asia/Seoul'))}")
            print(f"request packet received (as NTP server time, recv_time): {datetime.fromtimestamp(response.recv_time, pytz.timezone('Asia/Seoul'))}")
            print(f"response packet sent (as NTP server time, tx_time): {datetime.fromtimestamp(response.tx_time, pytz.timezone('Asia/Seoul'))}")
            print(f"response packet received (as LOCAL client time, dest_time): {datetime.fromtimestamp(response.dest_time, pytz.timezone('Asia/Seoul'))}")
            print(f"round trip duration: {response.delay} s")
            print(f"* adjusted time, tx_time + delay/2: {datetime.fromtimestamp(response.tx_time + response.delay/2, pytz.timezone('Asia/Seoul'))}")
            print(f"* adjusted time, dest_time + offset: {datetime.fromtimestamp(response.dest_time + response.offset, pytz.timezone('Asia/Seoul'))}")
            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()
    

    adjust_time

  • NTP Server에 맞추어 시간을 설정하기(macOS)

    sudo sntp -sS time.bora.net
    

    SNTP

  • NTP 서버의 시간정보를 받아와 로컬머신의 시간으로 세팅하기

    import ntplib
    import pytz
    from datetime import datetime, timezone, timedelta
    
    
    def get_ntp_time():
        # ntp_pool = ['time.bora.net', 'pool.ntp.org', 'time.nist.gov']
        ntp_pool = ['time.bora.net']
        def call_ntp(serverAddress):
            call = ntplib.NTPClient()
            return call.request(server, version=3)
        for server in ntp_pool:
            response = call_ntp(server)
            print(str(datetime.fromtimestamp(response.tx_time + response.delay/2, pytz.timezone('Asia/Seoul')))[:-6])
            # print(datetime.fromtimestamp(response.tx_time + response.delay/2, pytz.timezone('Asia/Seoul')))
            # 2022-07-21 00:33:23.541585
    
    
    get_ntp_time()
    
    sudo gdate --set="$(python set_time_by_ntp.py)"
    

    실험결과, SNTP로 직접 세팅하는 것이 offset 측면에서 더 좋은 성능을 보임

References

  • What time from an NTP time server should be used to set my clock? link

  • Support boundary for high-accuracy time link