Skip to content

Commit d3a46eb

Browse files
author
Teemu Kultala
committed
more effective port randomisation
1 parent b7bad77 commit d3a46eb

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

features/cellular/framework/common/CellularUtil.cpp

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,17 @@
1515
* limitations under the License.
1616
*/
1717
#include "CellularUtil.h"
18-
#include "randLIB.h"
1918
#include <string.h>
2019
#include <stdlib.h>
2120

21+
22+
#include "randLIB.h"
23+
#define RANDOM_PORT_NUMBER_START 49152
24+
#define RANDOM_PORT_NUMBER_END 65535
25+
#define RANDOM_PORT_NUMBER_COUNT (RANDOM_PORT_NUMBER_END - RANDOM_PORT_NUMBER_START + 1)
26+
#define RANDOM_PORT_NUMBER_MAX_STEP 100
27+
28+
2229
namespace mbed_cellular_util {
2330

2431
void convert_ipv6(char* ip)
@@ -316,9 +323,19 @@ int char_str_to_hex_str(const char* str, uint16_t len, char *buf, bool omit_lead
316323

317324
uint16_t get_dynamic_ip_port()
318325
{
319-
randLIB_seed_random();
326+
static uint16_t port_counter = RANDOM_PORT_NUMBER_COUNT;
327+
328+
if (port_counter == RANDOM_PORT_NUMBER_COUNT) {
329+
randLIB_seed_random();
330+
port_counter = randLIB_get_random_in_range(0, RANDOM_PORT_NUMBER_COUNT - 1);
331+
}
320332

321-
return (randLIB_get_16bit() | 0xC000);
333+
port_counter += randLIB_get_random_in_range(1, RANDOM_PORT_NUMBER_MAX_STEP);
334+
if (port_counter >= RANDOM_PORT_NUMBER_COUNT) {
335+
port_counter -= RANDOM_PORT_NUMBER_COUNT;
336+
}
337+
338+
return (RANDOM_PORT_NUMBER_START + port_counter);
322339
}
323340

324341
} // namespace mbed_cellular_util

0 commit comments

Comments
 (0)