@@ -15,17 +15,17 @@ module.exports = (port, callback) => {
15
15
}
16
16
debug ( 'detect free port between [%s, %s)' , port , maxPort ) ;
17
17
if ( typeof callback === 'function' ) {
18
- return tryListen ( port , maxPort , callback ) ;
18
+ return tryListen ( port , maxPort , null , callback ) ;
19
19
}
20
20
// promise
21
21
return new Promise ( resolve => {
22
- tryListen ( port , maxPort , ( _ , realPort ) => {
22
+ tryListen ( port , maxPort , null , ( _ , realPort ) => {
23
23
resolve ( realPort ) ;
24
24
} ) ;
25
25
} ) ;
26
26
} ;
27
27
28
- function tryListen ( port , maxPort , callback ) {
28
+ function tryListen ( port , maxPort , hostname , callback ) {
29
29
const server = new net . Server ( ) ;
30
30
31
31
server . on ( 'error' , err => {
@@ -41,13 +41,19 @@ function tryListen(port, maxPort, callback) {
41
41
maxPort = 0 ;
42
42
}
43
43
server . close ( ) ;
44
- return tryListen ( port , maxPort , callback ) ;
44
+ return tryListen ( port , maxPort , hostname , callback ) ;
45
45
} ) ;
46
46
47
- server . listen ( { port } , ( ) => {
47
+ // check 0.0.0.0 first
48
+ server . listen ( port , hostname , ( ) => {
48
49
port = server . address ( ) . port ;
49
50
server . close ( ) ;
50
- debug ( 'get free port: %s' , port ) ;
51
- callback ( null , port ) ;
51
+ debug ( 'get %s free port: %s' , hostname , port ) ;
52
+ if ( hostname === 'localhost' ) {
53
+ return callback ( null , port ) ;
54
+ }
55
+
56
+ // check localhost second
57
+ tryListen ( port , maxPort , 'localhost' , callback ) ;
52
58
} ) ;
53
59
}
0 commit comments