Time Shield Library
C++ library for working with time
Loading...
Searching...
No Matches
ntp_client_example.cpp
Go to the documentation of this file.
1
7
8#include <iostream>
9#include <iomanip>
10#include <chrono>
11#include <ctime>
12#if defined(_WIN32)
15
16int main() {
17 using namespace time_shield;
18
19 init();
20
21 NtpClient client; // uses pool.ntp.org by default
22
23 std::cout << "Querying NTP server..." << std::endl;
24 if (!client.query()) {
25 std::cerr << "Failed to query NTP server. Error code: "
26 << client.get_last_error_code() << std::endl;
27 return 1;
28 }
29
30 const int64_t offset_us = client.get_offset_us();
31
32 // Current local system time
33 auto now = std::chrono::system_clock::now();
34 auto now_time_t = std::chrono::system_clock::to_time_t(now);
35 std::cout << "Local time: "
36 << std::put_time(std::gmtime(&now_time_t), "%Y-%m-%d %H:%M:%S")
37 << std::endl;
38
39 // Corrected time using the offset from the NTP server
40 auto corrected = std::chrono::system_clock::time_point(
41 std::chrono::microseconds(client.get_utc_time_us()));
42 auto corrected_time_t = std::chrono::system_clock::to_time_t(corrected);
43 std::cout << "Corrected time: "
44 << std::put_time(std::gmtime(&corrected_time_t), "%Y-%m-%d %H:%M:%S")
45 << std::endl;
46
47 std::cout << "Offset (us): " << offset_us << std::endl;
48
49 std::cout << "Press Enter to exit..." << std::endl;
50 std::cin.get();
51 return 0;
52}
53
54#else
55int main() {
56 std::cout << "NtpClient is supported only on Windows." << std::endl;
57 return 0;
58}
59#endif
60
Simple Windows-only NTP client for measuring time offset.
int64_t get_utc_time_us() const noexcept
Returns current UTC time in microseconds based on last NTP offset.
int64_t get_offset_us() const noexcept
Returns the last measured offset in microseconds.
int get_last_error_code() const noexcept
Returns last WinSock error code (if any).
bool query()
Queries the NTP server and updates the local offset.
void init()
Initializes the Time Shield library.
const ts_ms_t now() noexcept
Get the current UTC timestamp in milliseconds.
Initialization helpers for the Time Shield library.
Main namespace for the Time Shield library.
Simple NTP client for querying time offset from NTP servers.
int main()