How to get local IP address in Node.js?

Sometimes, we want to get local IP address in Node.js.

In this article, we’ll look at how to get local IP address in Node.js.

How to get local IP address in Node.js?

To get local IP address in Node.js, we can use the os.networkInterfaces method.

For instance, we write

const {
  networkInterfaces
} = require('os');

const nets = networkInterfaces();
const results = Object.create(null);

for (const name of Object.keys(nets)) {
  for (const net of nets[name]) {
    if (net.family === 'IPv4' && !net.internal) {
      if (!results[name]) {
        results[name] = [];
      }
      results[name].push(net.address);
    }
  }
}

to call networkInterfaces to return an object with some network data.

Then we loop through the nets[name] properties to get the IPv4 address from the nets object.

We use !net.internal to ignore network addresses that are local.

Conclusion

To get local IP address in Node.js, we can use the os.networkInterfaces method.