Skip to content

Commit b3e3c11

Browse files
committed
Fix port availability check
1 parent 34625e9 commit b3e3c11

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

internal/services/ports.go

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,11 @@ var disallowedPorts = map[int]string{
3636

3737
func getAvailablePort() (int, error) {
3838
get := func() (int, error) {
39-
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
39+
port, err := isPortAvailable(0)
4040
if err != nil {
4141
return 0, errors.WithStack(err)
4242
}
43-
44-
if isPortAvailable(addr.Port) != nil {
45-
return 0, errors.WithStack(err)
46-
}
47-
48-
return addr.Port, nil
43+
return port, nil
4944
}
5045

5146
for range 1000 {
@@ -64,7 +59,7 @@ func getAvailablePort() (int, error) {
6459

6560
func selectPort(configPort int) (int, error) {
6661
if configPort != 0 {
67-
return configPort, isPortAvailable(configPort)
62+
return isPortAvailable(configPort)
6863
}
6964

7065
if portStr, exists := os.LookupEnv("DEVBOX_PC_PORT_NUM"); exists {
@@ -75,7 +70,7 @@ func selectPort(configPort int) (int, error) {
7570
if port <= 0 {
7671
return 0, fmt.Errorf("invalid DEVBOX_PC_PORT_NUM environment variable: ports cannot be less than 0")
7772
}
78-
return port, isPortAvailable(port)
73+
return isPortAvailable(port)
7974
}
8075

8176
return getAvailablePort()
@@ -85,11 +80,11 @@ func isAllowed(port int) bool {
8580
return port > 1024 && disallowedPorts[port] == ""
8681
}
8782

88-
func isPortAvailable(port int) error {
89-
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
83+
func isPortAvailable(port int) (int, error) {
84+
ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
9085
if err != nil {
91-
return fmt.Errorf("port %d is already in use", port)
86+
return 0, fmt.Errorf("port %d is already in use", port)
9287
}
93-
ln.Close()
94-
return nil
88+
defer ln.Close()
89+
return ln.Addr().(*net.TCPAddr).Port, nil
9590
}

0 commit comments

Comments
 (0)