Peter Wone
Peter Wone

Reputation: 18739

Bind Node http to 127.0.0.1 with dynamic port

If you create a webserver and you don't specify any parameters to listen, it binds to all interfaces and picks a random port.

server = http.createServer(async (request, response) => { ... });
server.listen();

I'd like to bind my embedded webserver strictly to the loopback interface so it's not accessible from other hosts, but I'd like to retain the random port selection behaviour.

I tried using an options object to specify just the host, but this resulted in an exception. Is there any way to bind to the loopback interface on a random port?

server.listen({ host: "127.0.0.1" });

Upvotes: 0

Views: 325

Answers (1)

robertklep
robertklep

Reputation: 203231

At least for UNIX-like operating systems, you'll get a random port if you pass 0 as a port number:

server.listen(0, '127.0.0.1', ...)

Upvotes: 1

Related Questions