In the Node.js docs for server.listen, it states
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.
https://nodejs.org/api/net.html#net_server_listen
However, I've noticed that ports which other applications are listening on are being assigned e.g. ports that Slack and Spotify are listening on.
From looking at a previous question How does Node.js choose random ports?, it appeared that macOS may have just been allocating ephemeral ports sequentially without checking if they were in use. However, running the following script (index.js) in a loop (for i in {1..1000}; do node index.js; done;) shows the certain ports are being skipped over.
const http = require('http');
http.createServer(function (req, res) {
res.write("Testing ephemeral port allocation.");
res.end();
})
.listen(0, function () {
console.log(`server is listening on port ${this.address().port}`);
this.close();
});
It would be great to understand why this is occurring, or if there is anything I'm missing to prevent ports that other applications are listening on from being allocated?
Background: I first became aware of this when a superagent test suite (using server.listen(0)) was randomly failing (macOS Mojave, Node 10). Tracking down the failures, showed that the tests were failing when the allocated port already had another application listening on it (e.g. Slack and Spotify).