From 569906856208b0f15abbe885bc34ee48322bd4d1 Mon Sep 17 00:00:00 2001 From: ikaven1024 Date: Wed, 12 Apr 2023 00:38:46 +0800 Subject: [PATCH] fix get port used --- pkg/utils/net/unused_port.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) 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 }