feat(smartnetwork): Add exclude option to findFreePort and skip excluded ports during search
This commit is contained in:
@@ -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;
|
||||
|
Reference in New Issue
Block a user