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
27#include <winsock2.h>
28#include <ws2tcpip.h>
29
30namespace time_shield {
31
34 class NtpClient {
35 public:
37 NtpClient(std::string server = "pool.ntp.org", int port = 123)
38 : m_host(std::move(server)), m_port(port) {
40 }
41
44 bool query() {
46 if (!WsaGuard::instance().success()) {
47 m_is_success = false;
48 throw std::runtime_error("WSAStartup failed with error: " + std::to_string(WsaGuard::instance().ret_code()));
49 }
50
51 SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
52 if (sock == INVALID_SOCKET) {
53 m_is_success = false;
54 return false;
55 }
56
57 struct sockaddr_in addr{};
58 addr.sin_family = AF_INET;
59 addr.sin_port = htons(static_cast<u_short>(m_port));
60
61 addrinfo hints{}, *res = nullptr;
62 hints.ai_family = AF_INET; // IPv4
63 hints.ai_socktype = SOCK_DGRAM;
64 hints.ai_protocol = IPPROTO_UDP;
65
66 if (getaddrinfo(m_host.c_str(), nullptr, &hints, &res) != 0 || !res) {
67 s_last_error_code = WSAGetLastError();
68 closesocket(sock);
69 m_is_success = false;
70 return false;
71 }
72
73 sockaddr_in* resolved = reinterpret_cast<sockaddr_in*>(res->ai_addr);
74 addr.sin_addr = resolved->sin_addr;
75 freeaddrinfo(res);
76
77 ntp_packet pkt;
78 fill_packet(pkt);
79
80 int timeout_ms = 5000;
81 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout_ms), sizeof(timeout_ms));
82 if (sendto(sock, reinterpret_cast<const char*>(&pkt), sizeof(pkt), 0,
83 reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
84 s_last_error_code = WSAGetLastError();
85 closesocket(sock);
86 m_is_success = false;
87 return false;
88 }
89
90 sockaddr_in from;
91 int from_len = sizeof(from);
92 if (recvfrom(sock, reinterpret_cast<char*>(&pkt), sizeof(pkt), 0,
93 reinterpret_cast<sockaddr*>(&from), &from_len) < 0) {
94 s_last_error_code = WSAGetLastError();
95 closesocket(sock);
96 m_is_success = false;
97 return false;
98 }
99
100 closesocket(sock);
101
102 int64_t result_offset;
103 if (parse_packet(pkt, result_offset)) {
104 m_offset_us = result_offset;
105 m_is_success = true;
106 return true;
107 }
108
109 m_is_success = false;
110 return false;
111 }
112
115 bool success() const noexcept {
116 return m_is_success.load();
117 }
118
120 int64_t get_offset_us() const noexcept {
121 return m_offset_us;
122 }
123
126 int64_t get_utc_time_us() const noexcept {
127 const int64_t offset = m_offset_us.load();
128 return now_realtime_us() + offset;
129 }
130
133 int64_t get_utc_time_ms() const noexcept {
134 return get_utc_time_us() / 1000;
135 }
136
139 time_t get_utc_time() const noexcept {
140 const int64_t utc_us = get_utc_time_us();
141 return static_cast<time_t>(get_utc_time_us() / 1000000);
142 }
143
145 int get_last_error_code() const noexcept {
146 return s_last_error_code;
147 }
148
149 private:
150 static constexpr int64_t NTP_TIMESTAMP_DELTA = 2208988800ll;
151
154 struct ntp_packet {
155 uint8_t li_vn_mode; // Eight bits. li, vn, and mode.
156 // li. Two bits. Leap indicator.
157 // vn. Three bits. Version number of the protocol.
158 // mode. Three bits. Client will pick mode 3 for client.
159 uint8_t stratum; // Eight bits. Stratum level of the local clock.
160 uint8_t poll; // Eight bits. Maximum interval between successive messages.
161 uint8_t precision; // Eight bits. Precision of the local clock.
162 uint32_t root_delay; // 32 bits. Total round trip delay time.
163 uint32_t root_dispersion; // 32 bits. Max error aloud from primary clock source.
164 uint32_t ref_id; // 32 bits. Reference clock identifier.
165 uint32_t ref_ts_sec; // 32 bits. Reference time-stamp seconds.
166 uint32_t ref_ts_frac; // 32 bits. Reference time-stamp fraction of a second.
167 uint32_t orig_ts_sec; // 32 bits. Originate time-stamp seconds.
168 uint32_t orig_ts_frac; // 32 bits. Originate time-stamp fraction of a second.
169 uint32_t recv_ts_sec; // 32 bits. Received time-stamp seconds.
170 uint32_t recv_ts_frac; // 32 bits. Received time-stamp fraction of a second.
171 uint32_t tx_ts_sec; // 32 bits and the most important field the client cares about. Transmit time-stamp seconds.
172 uint32_t tx_ts_frac; // 32 bits. Transmit time-stamp fraction of a second.
173 };
174
175 std::string m_host;
176 int m_port = 123;
177 std::atomic<int64_t> m_offset_us{0};
178 std::atomic<bool> m_is_success{false};
179 static thread_local int s_last_error_code;
180
182 void fill_packet(ntp_packet& pkt) const {
183 std::memset(&pkt, 0, sizeof(pkt));
184 pkt.li_vn_mode = (0 << 6) | (3 << 3) | 3; // LI=0, VN=3, Mode=3 (client)
185
186 const uint64_t now_us = time_shield::now_realtime_us();
187 const uint64_t sec = now_us / 1000000 + NTP_TIMESTAMP_DELTA;
188 const uint64_t frac = ((now_us % 1000000) * 0x100000000ULL) / 1000000;
189
190 pkt.tx_ts_sec = htonl(static_cast<uint32_t>(sec));
191 pkt.tx_ts_frac = htonl(static_cast<uint32_t>(frac));
192 }
193
195 bool parse_packet(const ntp_packet& pkt, int64_t& result_offset_us) const {
196 const uint64_t arrival_us = time_shield::now_realtime_us();
197
198 const uint64_t originate_us = ((static_cast<uint64_t>(ntohl(pkt.orig_ts_sec)) - NTP_TIMESTAMP_DELTA) * 1000000) +
199 (static_cast<uint64_t>(ntohl(pkt.orig_ts_frac)) * 1000000 / 0xFFFFFFFFull);
200 const uint64_t receive_us = ((static_cast<uint64_t>(ntohl(pkt.recv_ts_sec)) - NTP_TIMESTAMP_DELTA) * 1000000) +
201 (static_cast<uint64_t>(ntohl(pkt.recv_ts_frac)) * 1000000 / 0xFFFFFFFFull);
202 const uint64_t transmit_us = ((static_cast<uint64_t>(ntohl(pkt.tx_ts_sec)) - NTP_TIMESTAMP_DELTA) * 1000000) +
203 (static_cast<uint64_t>(ntohl(pkt.tx_ts_frac)) * 1000000 / 0xFFFFFFFFull);
204
205 // RFC 5905
206 result_offset_us = ((static_cast<int64_t>(receive_us) - static_cast<int64_t>(originate_us))
207 + (static_cast<int64_t>(transmit_us) - static_cast<int64_t>(arrival_us))) / 2;
208 return true;
209 }
210 };
211
212 thread_local int NtpClient::s_last_error_code = 0;
213
214} // namespace time_shield
215
216#else // !_WIN32
217
218# warning "NtpClient is only supported on Windows for now."
219
220namespace time_shield {
221
222 class NtpClient {
223 static_assert(sizeof(void*) == 0, "time_shield::NtpClient is only supported on Windows.");
224 };
225
226}
227
228#endif // _WIN32
229
230#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.