@@ -186,16 +186,29 @@ export function stopNetworkUtilizationComputation() {
186186 *
187187 * @param port Port number to connect to.
188188 * @param host Hostname or IP address of the server (default '127.0.0.1').
189+ * @param timeout Connection timeout in milliseconds (default 3000 ms).
189190 * @returns True if the connection was successful, false otherwise.
190191 */
191- export async function canConnect ( port : number , host : string = '127.0.0.1' ) : Promise < boolean > {
192+ export async function canConnect (
193+ port : number ,
194+ host : string = '127.0.0.1' ,
195+ timeout : number | undefined = 3000 ,
196+ ) : Promise < boolean > {
192197 return new Promise < boolean > ( ( resolve ) => {
193- const socket = net . connect ( port , host , ( ) => {
198+ let resolved = false ;
199+ const socket = net . connect ( { host, port, timeout } , ( ) => {
194200 socket . end ( ) ;
195- resolve ( true ) ;
201+ if ( ! resolved ) resolve ( true ) ;
202+ resolved = true ;
203+ } ) ;
204+ socket . on ( 'timeout' , ( ) => {
205+ socket . destroy ( ) ;
206+ if ( ! resolved ) resolve ( false ) ;
207+ resolved = true ;
196208 } ) ;
197209 socket . on ( 'error' , ( ) => {
198- resolve ( false ) ;
210+ if ( ! resolved ) resolve ( false ) ;
211+ resolved = true ;
199212 } ) ;
200213 } ) ;
201214}
@@ -259,14 +272,19 @@ export async function isPortListendedOn(port: number, bindAddress: string = '0.0
259272 * Uses isPortListenedOn() and canConnect() to determine if a port is in use.
260273 * @param port Port number to check.
261274 * @param bindAddress Address of the interface to bind to (default '0.0.0.0').
275+ * @param timeout Connection timeout in milliseconds (default 100 ms).
262276 */
263- export async function isPortInUse ( port : number , bindAddress : string = '0.0.0.0' ) : Promise < boolean > {
277+ export async function isPortInUse (
278+ port : number ,
279+ bindAddress : string = '0.0.0.0' ,
280+ timeout : number | undefined = 100 ,
281+ ) : Promise < boolean > {
264282 // check first if port can be listened on (way faster if port is really used because just a kernel check needed).
265283 const isListenedOn = await isPortListendedOn ( port , bindAddress ) ;
266284 if ( isListenedOn ) return true ;
267285
268286 // as backup check if can connect
269- const canConn = await canConnect ( port , bindAddress ) ;
287+ const canConn = await canConnect ( port , bindAddress , timeout ) ;
270288 if ( canConn ) return true ;
271289
272290 return false ;
0 commit comments