Browse Source

correct NTP request

pull/697/merge
orignal 8 years ago
parent
commit
44af5e04e4
  1. 19
      Timestamp.cpp
  2. 2
      Timestamp.h

19
Timestamp.cpp

@ -1,6 +1,7 @@
#include <inttypes.h> #include <inttypes.h>
#include <string.h> #include <string.h>
#include <boost/asio.hpp> #include <boost/asio.hpp>
#include "Log.h"
#include "I2PEndian.h" #include "I2PEndian.h"
#include "Timestamp.h" #include "Timestamp.h"
@ -8,7 +9,7 @@ namespace i2p
{ {
namespace util 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) void SyncTimeWithNTP (const std::string& address)
{ {
@ -23,25 +24,25 @@ namespace util
socket.open (boost::asio::ip::udp::v4 (), ec); socket.open (boost::asio::ip::udp::v4 (), ec);
if (!ec) if (!ec)
{ {
uint8_t request[48];// 48 bytes NTP request uint8_t buf[48];// 48 bytes NTP request/response
memset (request, 0, 48); memset (buf, 0, 48);
request[0] = 0x80; // client mode, version 0 htobe32buf (buf, (3 << 27) | (3 << 24)); // RFC 4330
uint8_t * response = new uint8_t[1500]; // MTU
size_t len = 0; size_t len = 0;
try try
{ {
socket.send_to (boost::asio::buffer (request, 48), ep); socket.send_to (boost::asio::buffer (buf, 48), ep);
len = socket.receive_from (boost::asio::buffer (response, 1500), ep); len = socket.receive_from (boost::asio::buffer (buf, 48), ep);
} }
catch (std::exception& e) catch (std::exception& e)
{ {
} }
if (len >= 8) 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 if (ts > 2208988800U) ts -= 2208988800U; // 1/1/1970 from 1/1/1900
g_TimeOffset = std::chrono::seconds(ts) - std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch());
LogPrint (eLogInfo, address, " time offset from system time is ", g_TimeOffset.count (), " seconds");
} }
delete[] response;
} }
} }
} }

2
Timestamp.h

@ -8,7 +8,7 @@ namespace i2p
{ {
namespace util namespace util
{ {
extern std::chrono::system_clock::duration g_TimeOffset; extern std::chrono::seconds g_TimeOffset;
inline uint64_t GetMillisecondsSinceEpoch () inline uint64_t GetMillisecondsSinceEpoch ()
{ {

Loading…
Cancel
Save