Listening on Same Host and Port Twice Does Not Trigger an Error

Viewed 210
const http  = require("http");

function createServer(
  name,
  hostname
)
{
  const server = http.createServer(
    (
      request,
      response
    ) =>
    {
      console.log("request on", name);
      response.end(name);
    }
  );

  server.on(
    "error",
    (error) => console.log(`${name} error`, error)
  );

  server.on(
    "close",
    () => console.log(`${name} closed`)
  );

  server.listen(4321, hostname, () => console.log(`${name} listening (${server.listening}) on address`, server.address()));
}

createServer(
  "Server 1",
  "localhost"
);

createServer(
  "Server 2",
  "127.0.0.1"
);

createServer(
  "Server 3",
  "127.0.1.1"
);

createServer(
  "Server 4",
  "localhost"
);

createServer(
  "Server 5",
  "10.9.129.49"
);

createServer(
  "Server 6",
  "localhost"
);

Using Node v6.15.1, v8.14.1, and v10.15.0 the above code prints this on my computer:

Server 2 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 3 listening (true) on address { address: '127.0.1.1', family: 'IPv4', port: 4321 }
Server 5 listening (true) on address { address: '10.9.129.49', family: 'IPv4', port: 4321 }
Server 1 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 4 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }
Server 6 listening (true) on address { address: '127.0.0.1', family: 'IPv4', port: 4321 }

How is this possible? I would have expected an EADDRINUSE error to be triggered.

EDIT A previous version of this question only showed two servers using the host name localhost. The code has been updated to demonstrate that the issue seems to persist regardless of the server count or host.

UPDATE

I tried mixing different host names that point to my computer (localhost, 127.0.0.1, my local IP, etc.), and even though the address object printed shows different values for address() no errors occur.

I am curious if it relates Node.js's server.listen method allowing itself to be called multiple times. Maybe Node.js detects that all of the host names I used bind to the same device and port, so it just "re-opens" as the documentation says it would.

0 Answers
Related