Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions features/cellular/framework/common/CellularUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/
#include "CellularUtil.h"
#include "randLIB.h"
#include <string.h>
#include <stdlib.h>

Expand Down Expand Up @@ -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();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you're not tracking which ports you've already chosen or are still using, I think it would probably be better to keep a cycling algorithm to maximise time before reuse in one session.

Using some random online birthday paradox calculator, I find the above has a 50% chance of reuse in 150 calls.

If you want to start digging deeper into changing strategies, read https://tools.ietf.org/html/rfc6056, but for now I suggest sticking with the same cycling strategy and just making sure you start at a random point. Nanostack uses algorithm 5 from that paper, but it knows what the current ports in use are:

#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 500
static uint16_t port_counter;
port_counter = randLIB_get_random_in_range(0, RANDOM_PORT_NUMBER_COUNT - 1);


uint16_t count = RANDOM_PORT_NUMBER_COUNT;

do {
    port_counter += randLIB_get_random_in_range(1, RANDOM_PORT_NUMBER_MAX_STEP);
    while (port_counter >= RANDOM_PORT_NUMBER_COUNT) {
        port_counter -= RANDOM_PORT_NUMBER_COUNT;
    }
    uint16_t port = RANDOM_PORT_NUMBER_START + port_counter;
    if (socket_port_validate(port, protocol) == eOK) {
        return port;
    }
} while (--count > 0);

You could use that, but you'd probably want a smaller MAX_STEP unless you can add a validate.


return (randLIB_get_16bit() | 0xC000);
}

} // namespace mbed_cellular_util