Picking up the random port and current interface for a node.js server is pretty easy!
Fetching the address from the interface:
Just loop through the interfaces of the OS and get the IPv4 from them.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Fetching a random port:
There are few node modules out there for getting random free ports, but there is a easier way:
1 2 3 4 5 6 |
|
The trick is all about server.listen(0,IPv4)
this will cause the server to listen on a random port unless in a cluster where each worker will receive the same "random" port each time they do a listen(0)
i.e the port is random for the first time and there after it's predictable.
Well, there might be more better ways of doing this, but this was a quick hack I need to make for something I was working on.