Skip to content

Commit e49e1de

Browse files
aentingerchrisy
authored andcommitted
Merge pull request arduino-libraries#116 from luigigubello/random_local_port
Added method to set random local port
1 parent 8391b17 commit e49e1de

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);
@@ -146,7 +146,7 @@ bool NTPClient::forceUpdate() {
146146
bool NTPClient::update() {
147147
if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval
148148
|| this->_lastUpdate == 0) { // Update if there was no update yet.
149-
if (!this->_udpSetup) this->begin(); // setup the UDP client if needed
149+
if (!this->_udpSetup || this->_port != NTP_DEFAULT_LOCAL_PORT) this->begin(this->_port); // setup the UDP client if needed
150150
return this->forceUpdate();
151151
}
152152
this->_packetSent = false;
@@ -224,6 +224,7 @@ void NTPClient::sendNTPPacket() {
224224
memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
225225
// Initialize values needed to form NTP request
226226
// (see URL above for details on the packets)
227+
227228
this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode
228229
this->_packetBuffer[1] = 0; // Stratum, or type of clock
229230
this->_packetBuffer[2] = 6; // Polling Interval
@@ -244,3 +245,8 @@ void NTPClient::sendNTPPacket() {
244245
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
245246
this->_udp->endPacket();
246247
}
248+
249+
void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) {
250+
randomSeed(analogRead(0));
251+
this->_port = random(minValue, maxValue);
252+
}

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
bool _fractionalTime = false;
2121

@@ -48,6 +48,11 @@ class NTPClient {
4848
*/
4949
void setPoolServerName(const char* poolServerName);
5050

51+
/**
52+
* Set random local port
53+
*/
54+
void setRandomPort(unsigned int minValue, unsigned int maxValue);
55+
5156
/**
5257
* Starts the underlying UDP client with the default local port
5358
*/
@@ -56,7 +61,7 @@ class NTPClient {
5661
/**
5762
* Starts the underlying UDP client with the specified local port
5863
*/
59-
void begin(int port);
64+
void begin(unsigned int port);
6065

6166
/**
6267
* 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)