From b7bad775697d6abcb952c65cb1a259a366b0ea05 Mon Sep 17 00:00:00 2001 From: Teemu Kultala Date: Fri, 1 Jun 2018 13:17:09 +0300 Subject: [PATCH 1/2] random socket port number --- features/cellular/framework/common/CellularUtil.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/features/cellular/framework/common/CellularUtil.cpp b/features/cellular/framework/common/CellularUtil.cpp index 97ba9d7db92..2fc68053972 100644 --- a/features/cellular/framework/common/CellularUtil.cpp +++ b/features/cellular/framework/common/CellularUtil.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ #include "CellularUtil.h" +#include "randLIB.h" #include #include @@ -315,12 +316,9 @@ int char_str_to_hex_str(const char* str, uint16_t len, char *buf, bool omit_lead uint16_t get_dynamic_ip_port() { - static uint16_t port; - port++; - if (port < 49152) { - port = 49152; - } - return port; + randLIB_seed_random(); + + return (randLIB_get_16bit() | 0xC000); } } // namespace mbed_cellular_util From d3a46eb7cde1e14086fb8cb7f3fa1c6c783155d4 Mon Sep 17 00:00:00 2001 From: Teemu Kultala Date: Tue, 5 Jun 2018 13:25:59 +0300 Subject: [PATCH 2/2] more effective port randomisation --- .../framework/common/CellularUtil.cpp | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/features/cellular/framework/common/CellularUtil.cpp b/features/cellular/framework/common/CellularUtil.cpp index 2fc68053972..a49cd1c787f 100644 --- a/features/cellular/framework/common/CellularUtil.cpp +++ b/features/cellular/framework/common/CellularUtil.cpp @@ -15,10 +15,17 @@ * limitations under the License. */ #include "CellularUtil.h" -#include "randLIB.h" #include #include + +#include "randLIB.h" +#define RANDOM_PORT_NUMBER_START 49152 +#define RANDOM_PORT_NUMBER_END 65535 +#define RANDOM_PORT_NUMBER_COUNT (RANDOM_PORT_NUMBER_END - RANDOM_PORT_NUMBER_START + 1) +#define RANDOM_PORT_NUMBER_MAX_STEP 100 + + namespace mbed_cellular_util { 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 uint16_t get_dynamic_ip_port() { - randLIB_seed_random(); + static uint16_t port_counter = RANDOM_PORT_NUMBER_COUNT; + + if (port_counter == RANDOM_PORT_NUMBER_COUNT) { + randLIB_seed_random(); + port_counter = randLIB_get_random_in_range(0, RANDOM_PORT_NUMBER_COUNT - 1); + } - return (randLIB_get_16bit() | 0xC000); + port_counter += randLIB_get_random_in_range(1, RANDOM_PORT_NUMBER_MAX_STEP); + if (port_counter >= RANDOM_PORT_NUMBER_COUNT) { + port_counter -= RANDOM_PORT_NUMBER_COUNT; + } + + return (RANDOM_PORT_NUMBER_START + port_counter); } } // namespace mbed_cellular_util