From fc4f7a1a7dd2c703e579ef2c0247bce70bef996d Mon Sep 17 00:00:00 2001 From: Stanimir Genov Date: Thu, 30 Jan 2020 11:18:27 +0200 Subject: [PATCH] Close UDP socket after communicating with NTPServer We should close the socket after using it. There is no reason to keep it open. If we want to destroy the first EasyNTPClient instance and then create another one later on, the socket will be taken. This will result in a failure to "ntp->begin(123)", which make getServerTime return 0 This change cleans after the call is done. --- src/EasyNTPClient.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/EasyNTPClient.cpp b/src/EasyNTPClient.cpp index 22a2620..0147f48 100644 --- a/src/EasyNTPClient.cpp +++ b/src/EasyNTPClient.cpp @@ -46,8 +46,10 @@ unsigned long EasyNTPClient::getServerTime () { const long ntpFirstFourBytes = 0xEC0600E3; // NTP request header // Fail if WiFiUdp.begin() could not init a socket - if (! udpInited) - return 0; + if (! udpInited) { + this->mUdp->stop(); + return 0; + } // Clear received data from possible stray received packets this->mUdp->flush(); @@ -55,8 +57,11 @@ unsigned long EasyNTPClient::getServerTime () { // Send an NTP request if (! (this->mUdp->beginPacket(this->mServerPool, 123) // 123 is the NTP port && this->mUdp->write((byte *)&ntpFirstFourBytes, 48) == 48 - && this->mUdp->endPacket())) - return 0; // sending request failed + && this->mUdp->endPacket())) { + this->mUdp->stop(); + return 0; // sending request failed + } + // Wait for response; check every pollIntv ms up to maxPoll times const int pollIntv = 150; // poll every this many ms @@ -67,8 +72,10 @@ unsigned long EasyNTPClient::getServerTime () { break; delay(pollIntv); } - if (pktLen != 48) - return 0; // no correct packet received + if (pktLen != 48) { + this->mUdp->stop(); + return 0; // no correct packet received + } // Read and discard the first useless bytes // Set useless to 32 for speed; set to 40 for accuracy. @@ -91,6 +98,7 @@ unsigned long EasyNTPClient::getServerTime () { // Discard the rest of the packet this->mUdp->flush(); + this->mUdp->stop(); return time + this->mOffset - 2208988800ul; // convert NTP time to Unix time }