Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check all local hosts for port availability #56

Merged
merged 12 commits into from Oct 3, 2021
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/main.yml
Expand Up @@ -4,11 +4,15 @@ on:
- pull_request
jobs:
test:
name: Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
name: Node.js ${{ matrix.node-version }} on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- windows-latest
- macos-latest
node-version:
- 14
- 12
Expand Down
62 changes: 51 additions & 11 deletions index.js
@@ -1,5 +1,6 @@
'use strict';
const net = require('net');
const os = require('os');

class Locked extends Error {
constructor(port) {
Expand All @@ -20,17 +21,54 @@ const releaseOldLockedPortsIntervalMs = 1000 * 15;
// Lazily create interval on first use
let interval;

const getAvailablePort = options => new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(options, () => {
const {port} = server.address();
server.close(() => {
resolve(port);
const getLocalHosts = () => {
const interfaces = os.networkInterfaces();
const results = new Set();

for (const _interface of Object.values(interfaces)) {
for (const config of _interface) {
results.add(config.address);
}
}

// Add undefined value for createServer function to use default host,
// and default IPv4 host in case createServer defaults to IPv6.
results.add(undefined);
mihkeleidast marked this conversation as resolved.
Show resolved Hide resolved
results.add('0.0.0.0');

return results;
};

const checkAvailablePort = options =>
new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(options, () => {
const {port} = server.address();
server.close(() => {
resolve(port);
});
});
});
});

const getAvailablePort = async (options, hosts) => {
if (options.host || options.port === 0) {
return checkAvailablePort(options);
}

for (const host of hosts) {
try {
await checkAvailablePort({port: options.port, host}); // eslint-disable-line no-await-in-loop
} catch (error) {
if (!['EADDRNOTAVAIL', 'EINVAL'].includes(error.code)) {
throw error;
}
}
}

return options.port;
};

const portCheckSequence = function * (ports) {
if (ports) {
Expand Down Expand Up @@ -59,15 +97,17 @@ module.exports = async options => {
}
}

const hosts = getLocalHosts();

for (const port of portCheckSequence(ports)) {
try {
let availablePort = await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
let availablePort = await getAvailablePort({...options, port}, hosts); // eslint-disable-line no-await-in-loop
while (lockedPorts.old.has(availablePort) || lockedPorts.young.has(availablePort)) {
if (port !== 0) {
throw new Locked(port);
}

availablePort = await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
availablePort = await getAvailablePort({...options, port}, hosts); // eslint-disable-line no-await-in-loop
}

lockedPorts.young.add(availablePort);
Expand Down
4 changes: 3 additions & 1 deletion readme.md
@@ -1,6 +1,8 @@
# get-port

> Get an available [TCP port](https://en.wikipedia.org/wiki/Port_(computer_networking))
> Get an available [TCP port](https://en.wikipedia.org/wiki/Port_(computer_networking)).
>
> Checks availability on all local addresses defined in [OS network interfaces](https://nodejs.org/api/os.html#os_os_networkinterfaces).
mihkeleidast marked this conversation as resolved.
Show resolved Hide resolved

## Install

Expand Down
18 changes: 18 additions & 0 deletions test.js
Expand Up @@ -153,3 +153,21 @@ test('ports are locked for up to 30 seconds', async t => {
t.is(port3, port);
global.setInterval = setInterval;
});

const bindPort = async ({port, host}) => {
const server = net.createServer();
await promisify(server.listen.bind(server))({port, host});
return server;
};

test('preferred ports is bound up with different hosts', async t => {
const desiredPorts = [10990, 10991, 10992, 10993];

await bindPort({port: desiredPorts[0]});
await bindPort({port: desiredPorts[1], host: '0.0.0.0'});
await bindPort({port: desiredPorts[2], host: '127.0.0.1'});

const port = await getPort({port: desiredPorts});

t.is(port, desiredPorts[3]);
});