Skip to content

Commit

Permalink
fix get port used
Browse files Browse the repository at this point in the history
  • Loading branch information
ikaven1024 authored and wzshiming committed Apr 12, 2023
1 parent 3f11a3c commit 5699068
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 5699068

Please sign in to comment.