[PATCH 1/1] lib/socket: randomize the generated local port
Thomas Haller
thaller at redhat.com
Mon Apr 7 11:26:51 PDT 2014
Instead of always trying the same order of ports when
looking for an unused port, randomize the order (naively).
As libnl-1 uses the same function, it is likely that two applications
that are using both libraries generate the same ports. By chossing a
different order how to select the local port, the chances are smaller
for this to happen.
Signed-off-by: Thomas Haller <thaller at redhat.com>
---
lib/socket.c | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/lib/socket.c b/lib/socket.c
index 00d8d6a..c12817e 100644
--- a/lib/socket.c
+++ b/lib/socket.c
@@ -61,12 +61,18 @@ static NL_RW_LOCK(port_map_lock);
static uint32_t generate_local_port(void)
{
- int i, n;
+ int i, j, n;
+ static int8_t idx_state = -1;
uint32_t pid = getpid() & 0x3FFFFF;
nl_write_lock(&port_map_lock);
- for (i = 0; i < 32; i++) {
+ if (idx_state < 0)
+ idx_state = ((unsigned) time(NULL)) % 32;
+
+ for (j = 0; j < 32; j++) {
+ i = idx_state = (idx_state + 7) % 32;
+
if (used_ports_map[i] == 0xFFFFFFFF)
continue;
--
1.9.0
More information about the libnl
mailing list