Skip to content

Commit 94de247

Browse files
committed
Somtimes got times from 2036
* added some more checks for plausibility [no-ticket]
1 parent a8eab3f commit 94de247

File tree

1 file changed

+26
-14
lines changed

1 file changed

+26
-14
lines changed

Diff for: NTPClient.cpp

+26-14
Original file line numberDiff line numberDiff line change
@@ -101,20 +101,32 @@ bool NTPClient::forceUpdate() {
101101
if (timeout > 100) return false; // timeout after 1000 ms
102102
timeout++;
103103
} while (cb == 0);
104-
105-
this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
106-
107-
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
108-
109-
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
110-
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
111-
// combine the four bytes (two words) into a long integer
112-
// this is NTP time (seconds since Jan 1 1900):
113-
unsigned long secsSince1900 = highWord << 16 | lowWord;
114-
115-
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
116-
117-
return true; // return true after successful update
104+
unsigned long newLastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
105+
106+
int len = this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
107+
if (len == 48) {
108+
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
109+
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
110+
// combine the four bytes (two words) into a long integer
111+
// this is NTP time (seconds since Jan 1 1900):
112+
unsigned long secsSince1900 = highWord << 16 | lowWord;
113+
if (secsSince1900 > 0x8000000UL) {
114+
this->_lastUpdate = newLastUpdate;
115+
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
116+
return true; // return true after successful update
117+
}
118+
else {
119+
#ifdef DEBUG_NTPClient
120+
Serial.println("NTP Server time too far in the past");
121+
#endif
122+
}
123+
}
124+
else {
125+
#ifdef DEBUG_NTPClient
126+
Serial.println("NTP Server message lenght not 48");
127+
#endif
128+
}
129+
return false;
118130
}
119131

120132
bool NTPClient::update() {

0 commit comments

Comments
 (0)