Hemanth's Scribes

node

Current Interface and Random Port with Node.js

Author Photo

Hemanth HM

Thumbnail

Picking a random port and current interface for a Node.js server is pretty easy!

Getting the IPv4 Address

Loop through the OS interfaces and get the IPv4:

var IPv4 = (function() {
  var interfaces = require('os').networkInterfaces();
  var IP;
  
  for (var iface in interfaces) {
    interfaces[iface].forEach(function(addr) {
      if (addr.family == 'IPv4') {
        IP = addr.address;
      }
    });
  }
  return IP;
}());

Fetching a Random Port

The trick is server.listen(0, IPv4) - this makes the server listen on a random available port:

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

Note: In a cluster, each worker will receive the same “random” port on subsequent listen(0) calls after the first.

#node#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.