Skip to content

Commit f6336f8

Browse files
committed
Use crypto.randomInt()
1 parent d6c36f9 commit f6336f8

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

source/index.ts

+8-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import crypto from 'node:crypto';
22
import net from 'node:net';
33
import os from 'node:os';
4+
import util from 'node:util';
45
import {SharedContext} from '@ava/cooperate';
56

67
const context = new SharedContext(import.meta.url);
@@ -11,14 +12,15 @@ const localHosts = new Set([
1112
...Object.values(os.networkInterfaces()).flatMap(interfaces => interfaces?.map(info => info.address)),
1213
]);
1314

15+
const minPort = 1024;
16+
const maxPort = 65_535;
17+
const size = 16;
18+
const randomInt = util.promisify(crypto.randomInt) as (max: number) => Promise<number>;
19+
1420
// Reserve a range of 16 addresses at a random offset.
1521
const reserveRange = async (): Promise<number[]> => {
16-
let from: number;
17-
do {
18-
from = crypto.randomBytes(2).readUInt16BE(0);
19-
} while (from < 1024 || from > 65_520);
20-
21-
const range = Array.from({length: 16}, (_, index) => from + index);
22+
const from = await randomInt(maxPort - minPort - size + 1);
23+
const range = Array.from({length: size}, (_, index) => minPort + from + index);
2224
return context.reserve(...range);
2325
};
2426

0 commit comments

Comments
 (0)