Skip to content

Commit

Permalink
Merge pull request #479 from wzshiming/automated-cherry-pick-of-#475-…
Browse files Browse the repository at this point in the history
…upstream-release-0.1

Automated cherry pick of #475: fix get port used
  • Loading branch information
wzshiming authored Apr 17, 2023
2 parents a96ddbc + 5699068 commit 14e60ad
Showing 1 changed file with 14 additions and 8 deletions.
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
}

0 comments on commit 14e60ad

Please sign in to comment.