From 44af5e04e421e7730ec63126cf72e36dbd5d1fa1 Mon Sep 17 00:00:00 2001 From: orignal Date: Tue, 1 Nov 2016 16:27:44 -0400 Subject: [PATCH] correct NTP request --- Timestamp.cpp | 19 ++++++++++--------- Timestamp.h | 2 +- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Timestamp.cpp b/Timestamp.cpp index fbe51ea1..cd17af05 100644 --- a/Timestamp.cpp +++ b/Timestamp.cpp @@ -1,6 +1,7 @@ #include #include #include +#include "Log.h" #include "I2PEndian.h" #include "Timestamp.h" @@ -8,7 +9,7 @@ namespace i2p { namespace util { - std::chrono::system_clock::duration g_TimeOffset = std::chrono::system_clock::duration::zero (); + std::chrono::seconds g_TimeOffset (0); void SyncTimeWithNTP (const std::string& address) { @@ -23,25 +24,25 @@ namespace util socket.open (boost::asio::ip::udp::v4 (), ec); if (!ec) { - uint8_t request[48];// 48 bytes NTP request - memset (request, 0, 48); - request[0] = 0x80; // client mode, version 0 - uint8_t * response = new uint8_t[1500]; // MTU + uint8_t buf[48];// 48 bytes NTP request/response + memset (buf, 0, 48); + htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330 size_t len = 0; try { - socket.send_to (boost::asio::buffer (request, 48), ep); - len = socket.receive_from (boost::asio::buffer (response, 1500), ep); + socket.send_to (boost::asio::buffer (buf, 48), ep); + len = socket.receive_from (boost::asio::buffer (buf, 48), ep); } catch (std::exception& e) { } if (len >= 8) { - uint32_t ts = bufbe32toh (response + 4); + uint32_t ts = bufbe32toh (buf + 32); if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900 + g_TimeOffset = std::chrono::seconds(ts) - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); + LogPrint (eLogInfo, address, " time offset from system time is ", g_TimeOffset.count (), " seconds"); } - delete[] response; } } } diff --git a/Timestamp.h b/Timestamp.h index 2e61d856..5f38c8da 100644 --- a/Timestamp.h +++ b/Timestamp.h @@ -8,7 +8,7 @@ namespace i2p { namespace util { - extern std::chrono::system_clock::duration g_TimeOffset; + extern std::chrono::seconds g_TimeOffset; inline uint64_t GetMillisecondsSinceEpoch () {