try random ports for randokm port mapping

This commit is contained in:
Christian Ulrich 2020-11-18 17:47:15 +01:00
parent ee3ab4564d
commit 9b3196d8a0
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
1 changed files with 13 additions and 17 deletions

View File

@ -1,5 +1,6 @@
import algorithm import algorithm
import net import net
import random
import sequtils import sequtils
import unittest import unittest
@ -82,15 +83,17 @@ proc predictPortRange*(localPort: Port, probedPorts: seq[Port]): seq[Port] =
result.add(Port(maxPort.subtractOffset(i))) result.add(Port(maxPort.subtractOffset(i)))
return return
# assume symmetric NAT with random port mapping # assume symmetric NAT with random port mapping
let portRange = maxPort - minPort randomize()
let first = if portRange > RandomPortCount: let first = if minPort >= 1024 + 5000:
minPort minPort - 5000
else: else:
let notCovered = RandomPortCount - portRange 1024
max(minPort - notCovered shr 1, 1024) let last = if maxPort <= uint16.high - 5000:
let last = first + RandomPortCount maxPort + 5000
for i in first .. last: else:
result.add(Port(i)) uint16.high
for _ in 1 .. RandomPortCount:
result.add(Port(rand(first .. last)))
suite "port prediction tests": suite "port prediction tests":
test "single port": test "single port":
@ -153,13 +156,6 @@ suite "port prediction tests":
let predicted = predictPortRange(Port(1234), @[Port(1039), Port(1030)]) let predicted = predictPortRange(Port(1234), @[Port(1039), Port(1030)])
check(predicted == @[Port(65533)]) check(predicted == @[Port(65533)])
test "random mapping, distance > RandomPortCount": test "random mapping":
let predicted = predictPortRange(Port(1234), @[Port(3546), Port(7624)]) let predicted = predictPortRange(Port(1234), @[Port(3546), Port(7624)])
check(predicted == toSeq(countup(3546'u16, 3546'u16 + RandomPortCount)).map(toPort)) check(predicted.len == RandomPortCount)
test "random mapping, distance < RandomPortCount":
let centerPort = 30000'u16
let minPort = centerPort - RandomPortCount.uint16 shr 1 + 1
let maxPort = centerPort + RandomPortCount.uint16 shr 1 - 1
let predicted = predictPortRange(Port(centerPort), @[Port(minPort), Port(maxPort)])
check(predicted == toSeq(countup(minPort - 1, maxPort + 1)).map(toPort))