From c1a01c14907629a5dfe3de3bffdbe52c85b9a507 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Mon, 23 Sep 2024 14:30:24 +1000 Subject: [PATCH] fix: avoid race when allocating ports (#2781) The port can change between when we increment and when we return the value. This can cause ports to not be unique when calling `Next()`. --- internal/bind/bind_allocator.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/bind/bind_allocator.go b/internal/bind/bind_allocator.go index 88337a4c15..5bc8932a98 100644 --- a/internal/bind/bind_allocator.go +++ b/internal/bind/bind_allocator.go @@ -34,15 +34,15 @@ func (b *BindAllocator) NextPort() int { var l *net.TCPListener var err error for { - b.port.Add(1) - l, err = net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP(b.baseURL.Hostname()), Port: int(b.port.Load())}) + port := int(b.port.Add(1)) + l, err = net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP(b.baseURL.Hostname()), Port: port}) if err != nil { continue } _ = l.Close() - return int(b.port.Load()) + return port } }