Skip to content

Commit 14e60ad

Browse files
authored
Merge pull request #479 from wzshiming/automated-cherry-pick-of-#475-upstream-release-0.1
Automated cherry pick of #475: fix get port used
2 parents a96ddbc + 5699068 commit 14e60ad

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

pkg/utils/net/unused_port.go

+14-8
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,25 @@ var (
2929

3030
// GetUnusedPort returns an unused port on the local machine.
3131
func GetUnusedPort(ctx context.Context) (port uint32, err error) {
32-
var listener net.Listener
3332
for lastUsedPort > 10000 && ctx.Err() == nil {
3433
lastUsedPort--
35-
listener, err = net.Listen("tcp", fmt.Sprintf(":%d", lastUsedPort))
36-
if err == nil {
37-
break
34+
if isPortUnused(lastUsedPort) {
35+
return lastUsedPort, nil
3836
}
3937
}
4038

41-
if listener == nil {
42-
return 0, fmt.Errorf("%w: %v", errGetUnusedPort, err)
43-
}
39+
return 0, fmt.Errorf("%w: %v", errGetUnusedPort, err)
40+
}
4441

42+
func isPortUnused(port uint32) bool {
43+
return isHostPortUnused("127.0.0.1", port) && isHostPortUnused("", port)
44+
}
45+
46+
func isHostPortUnused(host string, port uint32) bool {
47+
listener, err := net.Listen("tcp", fmt.Sprintf("%v:%d", host, port))
48+
if err != nil {
49+
return false
50+
}
4551
_ = listener.Close()
46-
return lastUsedPort, nil
52+
return true
4753
}

0 commit comments

Comments
 (0)