From ea98c50fc08c0462cf782c62440f9a84e081e00d Mon Sep 17 00:00:00 2001 From: Liran Funaro Date: Tue, 11 Apr 2023 11:16:54 +0300 Subject: [PATCH] Test if port available before using it for testing. Signed-off-by: Liran Funaro --- internal/test/ports.go | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/internal/test/ports.go b/internal/test/ports.go index 4e122e6c..590962bd 100644 --- a/internal/test/ports.go +++ b/internal/test/ports.go @@ -3,20 +3,38 @@ package test -import "sync" +import ( + "fmt" + "net" + "sync" +) var portMutex sync.Mutex var nodePortBase uint32 = 32000 var peerPortBase uint32 = 33000 +const PortLimit = 1 << 16 + +func testPort(port uint32) bool { + l, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + _ = l.Close() + return err == nil +} + func GetPorts() (nodePort, peerPort uint32) { portMutex.Lock() defer portMutex.Unlock() - nodePort = nodePortBase - peerPort = peerPortBase - nodePortBase++ - peerPortBase++ + for nodePortBase < PortLimit && peerPortBase < PortLimit { + nodePort = nodePortBase + peerPort = peerPortBase + nodePortBase++ + peerPortBase++ + + if testPort(nodePort) && testPort(peerPort) { + return + } + } - return + panic("Could not find available port for testing") }