const int nServersCount = 147;
-std::string NtpServers[147] = {
+const std::string NtpServers[147] = {
// Microsoft
"time.windows.com",
// ... To be continued
};
-bool InitWithHost(std::string &strHostName, SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr) {
+bool InitWithHost(const std::string &strHostName, SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr) {
sockfd = -1;
std::vector<CNetAddr> vIP;
return nTime;
}
-int64_t NtpGetTime(std::string &strHostName)
+int64_t NtpGetTime(const std::string &strHostName)
{
struct sockaddr cliaddr;
// Maximum offset is 2 hours.
const int64_t nMaxOffset = 7200;
+ printf("Trying to find NTP server at localhost...\n");
+
+ const std::string strLocalHost = "127.0.0.1";
+ if (NtpGetTime(strLocalHost) == GetTime()) {
+ printf("There is NTP server active at localhost, we don't need NTP thread.\n");
+
+ nNtpOffset = 0;
+ return;
+ }
+
printf("ThreadNtpSamples started\n");
vnThreadsRunning[THREAD_NTP]++;
CMedianFilter<int64_t> vTimeOffsets(200,0);
while (!fShutdown) {
- if (strTrustedUpstream != "localhost") {
+ if (strTrustedUpstream != strLocalHost) {
// Trying to get new offset sample from trusted NTP server.
int64_t nClockOffset = NtpGetTime(strTrustedUpstream) - GetTime();
nNtpOffset = nClockOffset;
}
else {
- // Something went wrong. Disable trusted offset sampling and wait 600 seconds.
+ // Something went wrong, disable trusted offset sampling.
nNtpOffset = INT64_MAX;
- strTrustedUpstream = "localhost";
+ strTrustedUpstream = strLocalHost;
- for (int i = 0; i < 600 && !fShutdown; i++) // Sleep for 5 minutes
+ int nSleepMinutes = 1 + GetRandInt(9); // Sleep for 1-10 minutes.
+ for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++)
Sleep(1000);
continue;
nNtpOffset = vTimeOffsets.median();
}
else {
- // Not enough offsets yet, try again 300 seconds later.
+ // Not enough offsets yet, try again later.
nNtpOffset = INT64_MAX;
- for (int i = 0; i < 300 && !fShutdown; i++)
+ int nSleepMinutes = 1 + GetRandInt(4); // Sleep for 1-5 minutes.
+ for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++)
Sleep(1000);
continue;
}
printf("nNtpOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nNtpOffset, nNtpOffset/60);
- for (int i = 0; i < 43200 && !fShutdown; i++) // Sleep for 12 hours
+ int nSleepHours = 1 + GetRandInt(5); // Sleep for 1-6 hours.
+ for (int i = 0; i < nSleepHours * 3600 && !fShutdown; i++)
Sleep(1000);
}