feat(smartnetwork): Add exclude option to findFreePort and skip excluded ports during search

This commit is contained in:
2025-09-12 18:26:56 +00:00
parent 6e59f0f5c0
commit 0f79773985
4 changed files with 37 additions and 1 deletions

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartnetwork',
version: '4.3.0',
version: '4.4.0',
description: 'A toolkit for network diagnostics including speed tests, port availability checks, and more.'
}

View File

@@ -31,6 +31,8 @@ export interface Hop {
export interface IFindFreePortOptions {
/** If true, selects a random available port within the range instead of the first one */
randomize?: boolean;
/** Array of port numbers to exclude from the search */
exclude?: number[];
}
export class SmartNetwork {
@@ -169,12 +171,20 @@ export class SmartNetwork {
throw new NetworkError('Start port must be less than or equal to end port', 'EINVAL');
}
// Create a set of excluded ports for efficient lookup
const excludedPorts = new Set(options?.exclude || []);
// If randomize option is true, collect all available ports and select randomly
if (options?.randomize) {
const availablePorts: number[] = [];
// Scan the range to find all available ports
for (let port = startPort; port <= endPort; port++) {
// Skip excluded ports
if (excludedPorts.has(port)) {
continue;
}
const isUnused = await this.isLocalPortUnused(port);
if (isUnused) {
availablePorts.push(port);
@@ -192,6 +202,11 @@ export class SmartNetwork {
} else {
// Default behavior: return the first available port (sequential search)
for (let port = startPort; port <= endPort; port++) {
// Skip excluded ports
if (excludedPorts.has(port)) {
continue;
}
const isUnused = await this.isLocalPortUnused(port);
if (isUnused) {
return port;