Time Shield Library
C++ library for working with time
Loading...
Searching...
No Matches
ntp_client.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _TIME_SHIELD_NTP_CLIENT_HPP_INCLUDED
3#define _TIME_SHIELD_NTP_CLIENT_HPP_INCLUDED
4
13
14#if defined(_WIN32)
15
17#include "time_utils.hpp"
18
19#include <cstdint>
20#include <cstring>
21#include <string>
22#include <mutex>
23#include <atomic>
24#include <functional>
25#include <chrono>
26
27namespace time_shield {
28
31 class NtpClient {
32 public:
34 NtpClient(std::string server = "pool.ntp.org", int port = 123)
35 : m_host(std::move(server)), m_port(port) {
37 }
38
41 bool query() {
43 if (!WsaGuard::instance().success()) {
44 m_is_success = false;
45 throw std::runtime_error("WSAStartup failed with error: " + std::to_string(WsaGuard::instance().ret_code()));
46 }
47
48 SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
49 if (sock == INVALID_SOCKET) {
50 m_is_success = false;
51 return false;
52 }
53
54 struct sockaddr_in addr{};
55 addr.sin_family = AF_INET;
56 addr.sin_port = htons(static_cast<u_short>(m_port));
57
58 addrinfo hints{}, *res = nullptr;
59 hints.ai_family = AF_INET; // IPv4
60 hints.ai_socktype = SOCK_DGRAM;
61 hints.ai_protocol = IPPROTO_UDP;
62
63 if (getaddrinfo(m_host.c_str(), nullptr, &hints, &res) != 0 || !res) {
64 s_last_error_code = WSAGetLastError();
65 closesocket(sock);
66 m_is_success = false;
67 return false;
68 }
69
70 sockaddr_in* resolved = reinterpret_cast<sockaddr_in*>(res->ai_addr);
71 addr.sin_addr = resolved->sin_addr;
72 freeaddrinfo(res);
73
74 ntp_packet pkt;
75 fill_packet(pkt);
76
77 int timeout_ms = 5000;
78 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout_ms), sizeof(timeout_ms));
79 if (sendto(sock, reinterpret_cast<const char*>(&pkt), sizeof(pkt), 0,
80 reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
81 s_last_error_code = WSAGetLastError();
82 closesocket(sock);
83 m_is_success = false;
84 return false;
85 }
86
87 sockaddr_in from;
88 int from_len = sizeof(from);
89 if (recvfrom(sock, reinterpret_cast<char*>(&pkt), sizeof(pkt), 0,
90 reinterpret_cast<sockaddr*>(&from), &from_len) < 0) {
91 s_last_error_code = WSAGetLastError();
92 closesocket(sock);
93 m_is_success = false;
94 return false;
95 }
96
97 closesocket(sock);
98
99 int64_t result_offset;
100 if (parse_packet(pkt, result_offset)) {
101 m_offset_us = result_offset;
102 m_is_success = true;
103 return true;
104 }
105
106 m_is_success = false;
107 return false;
108 }
109
112 bool success() const noexcept {
113 return m_is_success.load();
114 }
115
117 int64_t get_offset_us() const noexcept {
118 return m_offset_us;
119 }
120
123 int64_t get_utc_time_us() const noexcept {
124 const int64_t offset = m_offset_us.load();
125 return now_realtime_us() + offset;
126 }
127
130 int64_t get_utc_time_ms() const noexcept {
131 return get_utc_time_us() / 1000;
132 }
133
136 time_t get_utc_time() const noexcept {
137 return static_cast<time_t>(get_utc_time_us() / 1000000);
138 }
139
141 int get_last_error_code() const noexcept {
142 return s_last_error_code;
143 }
144
145 private:
146 static constexpr int64_t NTP_TIMESTAMP_DELTA = 2208988800ll;
147
150 struct ntp_packet {
151 uint8_t li_vn_mode; // Eight bits. li, vn, and mode.
152 // li. Two bits. Leap indicator.
153 // vn. Three bits. Version number of the protocol.
154 // mode. Three bits. Client will pick mode 3 for client.
155 uint8_t stratum; // Eight bits. Stratum level of the local clock.
156 uint8_t poll; // Eight bits. Maximum interval between successive messages.
157 uint8_t precision; // Eight bits. Precision of the local clock.
158 uint32_t root_delay; // 32 bits. Total round trip delay time.
159 uint32_t root_dispersion; // 32 bits. Max error aloud from primary clock source.
160 uint32_t ref_id; // 32 bits. Reference clock identifier.
161 uint32_t ref_ts_sec; // 32 bits. Reference time-stamp seconds.
162 uint32_t ref_ts_frac; // 32 bits. Reference time-stamp fraction of a second.
163 uint32_t orig_ts_sec; // 32 bits. Originate time-stamp seconds.
164 uint32_t orig_ts_frac; // 32 bits. Originate time-stamp fraction of a second.
165 uint32_t recv_ts_sec; // 32 bits. Received time-stamp seconds.
166 uint32_t recv_ts_frac; // 32 bits. Received time-stamp fraction of a second.
167 uint32_t tx_ts_sec; // 32 bits and the most important field the client cares about. Transmit time-stamp seconds.
168 uint32_t tx_ts_frac; // 32 bits. Transmit time-stamp fraction of a second.
169 };
170
171 std::string m_host;
172 int m_port = 123;
173 std::atomic<int64_t> m_offset_us{0};
174 std::atomic<bool> m_is_success{false};
175 static thread_local int s_last_error_code;
176
178 void fill_packet(ntp_packet& pkt) const {
179 std::memset(&pkt, 0, sizeof(pkt));
180 pkt.li_vn_mode = (0 << 6) | (3 << 3) | 3; // LI=0, VN=3, Mode=3 (client)
181
182 const uint64_t now_us = time_shield::now_realtime_us();
183 const uint64_t sec = now_us / 1000000 + NTP_TIMESTAMP_DELTA;
184 const uint64_t frac = ((now_us % 1000000) * 0x100000000ULL) / 1000000;
185
186 pkt.tx_ts_sec = htonl(static_cast<uint32_t>(sec));
187 pkt.tx_ts_frac = htonl(static_cast<uint32_t>(frac));
188 }
189
191 bool parse_packet(const ntp_packet& pkt, int64_t& result_offset_us) const {
192 const uint64_t arrival_us = time_shield::now_realtime_us();
193
194 const uint64_t originate_us = ((static_cast<uint64_t>(ntohl(pkt.orig_ts_sec)) - NTP_TIMESTAMP_DELTA) * 1000000) +
195 (static_cast<uint64_t>(ntohl(pkt.orig_ts_frac)) * 1000000 / 0xFFFFFFFFull);
196 const uint64_t receive_us = ((static_cast<uint64_t>(ntohl(pkt.recv_ts_sec)) - NTP_TIMESTAMP_DELTA) * 1000000) +
197 (static_cast<uint64_t>(ntohl(pkt.recv_ts_frac)) * 1000000 / 0xFFFFFFFFull);
198 const uint64_t transmit_us = ((static_cast<uint64_t>(ntohl(pkt.tx_ts_sec)) - NTP_TIMESTAMP_DELTA) * 1000000) +
199 (static_cast<uint64_t>(ntohl(pkt.tx_ts_frac)) * 1000000 / 0xFFFFFFFFull);
200
201 // RFC 5905
202 result_offset_us = ((static_cast<int64_t>(receive_us) - static_cast<int64_t>(originate_us))
203 + (static_cast<int64_t>(transmit_us) - static_cast<int64_t>(arrival_us))) / 2;
204 return true;
205 }
206 };
207
208 thread_local int NtpClient::s_last_error_code = 0;
209
210} // namespace time_shield
211
212#else // !_WIN32
213
214# warning "NtpClient is only supported on Windows for now."
215
216namespace time_shield {
217
218 class NtpClient {
219 static_assert(sizeof(void*) == 0, "time_shield::NtpClient is only supported on Windows.");
220 };
221
222}
223
224#endif // _WIN32
225
226#endif // _TIME_SHIELD_NTP_CLIENT_HPP_INCLUDED
Simple Windows-only NTP client for measuring time offset.
void fill_packet(ntp_packet &pkt) const
Converts local time to NTP timestamp format.
bool success() const noexcept
Returns whether the last NTP query was successful.
NtpClient(std::string server="pool.ntp.org", int port=123)
Constructs NTP client with specified host and port.
bool parse_packet(const ntp_packet &pkt, int64_t &result_offset_us) const
Parses response and calculates offset.
int64_t get_utc_time_us() const noexcept
Returns current UTC time in microseconds based on last NTP offset.
static constexpr int64_t NTP_TIMESTAMP_DELTA
Seconds between 1900 and 1970 epochs.
time_t get_utc_time() const noexcept
Returns current UTC time as time_t (seconds since Unix epoch).
int64_t get_offset_us() const noexcept
Returns the last measured offset in microseconds.
int64_t get_utc_time_ms() const noexcept
Returns current UTC time in milliseconds based on last NTP offset.
int get_last_error_code() const noexcept
Returns last WinSock error code (if any).
std::atomic< int64_t > m_offset_us
std::atomic< bool > m_is_success
bool query()
Queries the NTP server and updates the local offset.
static thread_local int s_last_error_code
static const WsaGuard & instance()
Returns the singleton instance, initializing WSA if needed.
Definition wsa_guard.hpp:22
int64_t now_realtime_us()
Get current real time in microseconds using a hybrid method.
Main namespace for the Time Shield library.
Структура пакета NTP Total: 384 bits or 48 bytes.
Header file with time-related utility functions.
Singleton guard for WinSock initialization.