123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 |
- "use strict";
- const net = require("net");
- const os = require("os");
- const minPort = 1024;
- const maxPort = 65_535;
- const getLocalHosts = () => {
- const interfaces = os.networkInterfaces();
-
-
-
- const results = new Set([undefined, "0.0.0.0"]);
- for (const _interface of Object.values(interfaces)) {
- if (_interface) {
- for (const config of _interface) {
- results.add(config.address);
- }
- }
- }
- return results;
- };
- const checkAvailablePort = (basePort, host) =>
- new Promise((resolve, reject) => {
- const server = net.createServer();
- server.unref();
- server.on("error", reject);
- server.listen(basePort, host, () => {
-
- const { port } = (
- server.address()
- );
- server.close(() => {
- resolve(port);
- });
- });
- });
- const getAvailablePort = async (port, hosts) => {
-
- const nonExistentInterfaceErrors = new Set(["EADDRNOTAVAIL", "EINVAL"]);
-
- for (const host of hosts) {
- try {
- await checkAvailablePort(port, host);
- } catch (error) {
-
- if (
- !nonExistentInterfaceErrors.has(
- (error).code
- )
- ) {
- throw error;
- }
- }
- }
- return port;
- };
- async function getPorts(basePort, host) {
- if (basePort < minPort || basePort > maxPort) {
- throw new Error(`Port number must lie between ${minPort} and ${maxPort}`);
- }
- let port = basePort;
- const localhosts = getLocalHosts();
- let hosts;
- if (host && !localhosts.has(host)) {
- hosts = new Set([host]);
- } else {
-
- hosts = localhosts;
- }
-
- const portUnavailableErrors = new Set(["EADDRINUSE", "EACCES"]);
- while (port <= maxPort) {
- try {
- const availablePort = await getAvailablePort(port, hosts);
- return availablePort;
- } catch (error) {
-
- if (
- !portUnavailableErrors.has(
- (error).code
- )
- ) {
- throw error;
- }
- port += 1;
- }
- }
- throw new Error("No available ports found");
- }
- module.exports = getPorts;
|