Skip to content

Commit aff9c6b

Browse files
authored
Merge pull request #116 from luigigubello/random_local_port
Added method to set random local port
2 parents 894b21d + f567329 commit aff9c6b

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

NTPClient.cpp

+8-2
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ void NTPClient::begin() {
7373
this->begin(NTP_DEFAULT_LOCAL_PORT);
7474
}
7575

76-
void NTPClient::begin(int port) {
76+
void NTPClient::begin(unsigned int port) {
7777
this->_port = port;
7878

7979
this->_udp->begin(this->_port);
@@ -120,7 +120,7 @@ bool NTPClient::forceUpdate() {
120120
bool NTPClient::update() {
121121
if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval
122122
|| this->_lastUpdate == 0) { // Update if there was no update yet.
123-
if (!this->_udpSetup) this->begin(); // setup the UDP client if needed
123+
if (!this->_udpSetup || this->_port != NTP_DEFAULT_LOCAL_PORT) this->begin(this->_port); // setup the UDP client if needed
124124
return this->forceUpdate();
125125
}
126126
return false; // return false if update does not occur
@@ -182,6 +182,7 @@ void NTPClient::sendNTPPacket() {
182182
memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
183183
// Initialize values needed to form NTP request
184184
// (see URL above for details on the packets)
185+
185186
this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode
186187
this->_packetBuffer[1] = 0; // Stratum, or type of clock
187188
this->_packetBuffer[2] = 6; // Polling Interval
@@ -202,3 +203,8 @@ void NTPClient::sendNTPPacket() {
202203
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
203204
this->_udp->endPacket();
204205
}
206+
207+
void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) {
208+
randomSeed(analogRead(0));
209+
this->_port = random(minValue, maxValue);
210+
}

NTPClient.h

+7-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class NTPClient {
1515

1616
const char* _poolServerName = "pool.ntp.org"; // Default time server
1717
IPAddress _poolServerIP;
18-
int _port = NTP_DEFAULT_LOCAL_PORT;
18+
unsigned int _port = NTP_DEFAULT_LOCAL_PORT;
1919
long _timeOffset = 0;
2020

2121
unsigned long _updateInterval = 60000; // In ms
@@ -44,6 +44,11 @@ class NTPClient {
4444
*/
4545
void setPoolServerName(const char* poolServerName);
4646

47+
/**
48+
* Set random local port
49+
*/
50+
void setRandomPort(unsigned int minValue, unsigned int maxValue);
51+
4752
/**
4853
* Starts the underlying UDP client with the default local port
4954
*/
@@ -52,7 +57,7 @@ class NTPClient {
5257
/**
5358
* Starts the underlying UDP client with the specified local port
5459
*/
55-
void begin(int port);
60+
void begin(unsigned int port);
5661

5762
/**
5863
* This should be called in the main loop of your application. By default an update from the NTP Server is only

0 commit comments

Comments
 (0)