Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Current Interface and Random Port With Nodejs

| Comments

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
var IPv4 = (function(){
  var interfaces = require('os').networkInterfaces(),
  IP;
  for (var iface in interfaces) {
      interfaces[iface].forEach(function(addr) {
          if (addr.family == 'IPv4') {
              IP = addr.address;
          }
     });
  }
  return IP;
}());

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
var http = require('http');
var server = http.createServer();
server.listen(0,IPv4);
server.on('listening', function() {
    console.log('Server is running on: '+IPv4+':'+ server.address().port);
})

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.

Comments