diff --git a/pkg/utils/net/unused_port.go b/pkg/utils/net/unused_port.go index a368631c0..02f5bc9dc 100644 --- a/pkg/utils/net/unused_port.go +++ b/pkg/utils/net/unused_port.go @@ -29,19 +29,25 @@ var ( // GetUnusedPort returns an unused port on the local machine. func GetUnusedPort(ctx context.Context) (port uint32, err error) { - var listener net.Listener for lastUsedPort > 10000 && ctx.Err() == nil { lastUsedPort-- - listener, err = net.Listen("tcp", fmt.Sprintf(":%d", lastUsedPort)) - if err == nil { - break + if isPortUnused(lastUsedPort) { + return lastUsedPort, nil } } - if listener == nil { - return 0, fmt.Errorf("%w: %v", errGetUnusedPort, err) - } + return 0, fmt.Errorf("%w: %v", errGetUnusedPort, err) +} +func isPortUnused(port uint32) bool { + return isHostPortUnused("127.0.0.1", port) && isHostPortUnused("", port) +} + +func isHostPortUnused(host string, port uint32) bool { + listener, err := net.Listen("tcp", fmt.Sprintf("%v:%d", host, port)) + if err != nil { + return false + } _ = listener.Close() - return lastUsedPort, nil + return true }