@@ -36,16 +36,11 @@ var disallowedPorts = map[int]string{
36
36
37
37
func getAvailablePort () (int , error ) {
38
38
get := func () (int , error ) {
39
- addr , err := net . ResolveTCPAddr ( "tcp" , "localhost:0" )
39
+ port , err := isPortAvailable ( 0 )
40
40
if err != nil {
41
41
return 0 , errors .WithStack (err )
42
42
}
43
-
44
- if isPortAvailable (addr .Port ) != nil {
45
- return 0 , errors .WithStack (err )
46
- }
47
-
48
- return addr .Port , nil
43
+ return port , nil
49
44
}
50
45
51
46
for range 1000 {
@@ -64,7 +59,7 @@ func getAvailablePort() (int, error) {
64
59
65
60
func selectPort (configPort int ) (int , error ) {
66
61
if configPort != 0 {
67
- return configPort , isPortAvailable (configPort )
62
+ return isPortAvailable (configPort )
68
63
}
69
64
70
65
if portStr , exists := os .LookupEnv ("DEVBOX_PC_PORT_NUM" ); exists {
@@ -75,7 +70,7 @@ func selectPort(configPort int) (int, error) {
75
70
if port <= 0 {
76
71
return 0 , fmt .Errorf ("invalid DEVBOX_PC_PORT_NUM environment variable: ports cannot be less than 0" )
77
72
}
78
- return port , isPortAvailable (port )
73
+ return isPortAvailable (port )
79
74
}
80
75
81
76
return getAvailablePort ()
@@ -85,11 +80,11 @@ func isAllowed(port int) bool {
85
80
return port > 1024 && disallowedPorts [port ] == ""
86
81
}
87
82
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 ))
90
85
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 )
92
87
}
93
- ln .Close ()
94
- return nil
88
+ defer ln .Close ()
89
+ return ln . Addr ().( * net. TCPAddr ). Port , nil
95
90
}
0 commit comments