Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix get port used #475

Merged
merged 1 commit into from
Apr 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions pkg/utils/net/unused_port.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}