Skip to content

.listen(0) on net.Server can return a port that's in use on OSX 15.5 #58609

Closed as not planned
@josephjunker

Description

@josephjunker

Version

v22.15.1

Platform

Darwin Mac 24.5.0 Darwin Kernel Version 24.5.0: Tue Apr 22 19:54:29 PDT 2025; root:xnu-11417.121.6~2/RELEASE_ARM64_T6030 arm64

Subsystem

net

What steps will reproduce the bug?

I selected a port that's currently in use (found via sudo lsof -i -P | grep LISTEN | grep :$PORT) and put it in this script. In my case, DBeaver is listening on port localhost:55197. When I run this script, server.listen(0) is called and eventually returns a server that is listening on port 55197. No error is thrown or emitted.

const net = require('node:net');
const server = new net.Server()
server.on('error', e => { console.log("An error occurred, yay!"); console.dir(e); process.exit(0) })

function doAgain() {
  const port = server.address().port;

  console.log(`port ${port}`);

  // Choose a port that's already in use according to lsof
  if (port === 55197) {
    console.log("Collision!");
    process.exit(1);
  }

  server.close();
  server.listen(0);
}

server.on("listening", doAgain);
server.listen(0);

How often does it reproduce? Is there a required condition?

I do not know what logic is behind server.listen(0) so I don't know whether it's deterministic or not, but so far it's occurred within a second of me running the script.

What is the expected behavior? Why is that the expected behavior?

The expected behavior is that server.listen(0) will return a port which is not currently in use. This is expected because the documentation says the following:

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.

What do you see instead?

server.listen(0) results in a server listening on a port which is already in use. No error is emitted or thrown.

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    libuvIssues and PRs related to the libuv dependency or the uv binding.macosIssues and PRs related to the macOS platform / OSX.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions