Home > Mobile >  Bind Node http to 127.0.0.1 with dynamic port
Bind Node http to 127.0.0.1 with dynamic port

Time:09-17

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" });

CodePudding user response:

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', ...)
  • Related