@@ -169,13 +169,36 @@ export function stopNetworkUtilizationComputation() {
169169}
170170
171171
172+ /**
173+ * Tries to connect to a given server over TCP.
174+ *
175+ * @param port Port number to connect to.
176+ * @param host Hostname or IP address of the server (default '127.0.0.1').
177+ * @returns True if the connection was successful, false otherwise.
178+ */
179+ export async function canConnect(port: number, host: string = '127.0.0.1'): Promise<boolean> {
180+ return new Promise<boolean>((resolve) => {
181+ const socket = net.connect(port, host, () => {
182+ socket.end();
183+ resolve(true);
184+ });
185+ socket.on('error', () => {
186+ resolve(false);
187+ });
188+ });
189+ }
190+
172191/**
173192 * Checks if a process is listening on a given port.
193+ *
194+ * @warning If a Docker proxy is involved multiple processes can bind to the same port.
195+ * Use canConnect() as an alternative to check if a port is already being listened on.
196+ *
174197 * @param port Port number to check.
175198 * @param bindAddress Address of the interface to bind to (default '0.0.0.0' which binds to all interfaces).
176199 * @returns Promise that resolves to true if the port is in use, false otherwise.
177200 */
178- export async function isPortInUse (port: number, bindAddress: string = '0.0.0.0'): Promise<boolean> {
201+ export async function isPortListendedOn (port: number, bindAddress: string = '0.0.0.0'): Promise<boolean> {
179202 const server = net.createServer();
180203 return new Promise((resolve) => {
181204 server.unref();
@@ -195,6 +218,22 @@ export async function isPortInUse(port: number, bindAddress: string = '0.0.0.0')
195218}
196219
197220
221+ /**
222+ * Uses isPortListenedOn() and canConnect() to determine if a port is in use.
223+ * @param port Port number to check.
224+ * @param bindAddress Address of the interface to bind to (default '0.0.0.0').
225+ */
226+ export async function isPortInUse(port: number, bindAddress: string = '0.0.0.0'): Promise<boolean> {
227+ let canConn = false;
228+ let isListened = false;
229+ await Promise.allSettled([
230+ canConnect(port, bindAddress).then(res => canConn = res),
231+ isPortListendedOn(port, bindAddress).then(res => isListened = res)
232+ ])
233+ return canConn || isListened;
234+ }
235+
236+
198237/**
199238 * Returns information about the network interfaces on the system.
200239 *
0 commit comments