How can I get the local IP address in Node.js?

http://nodejs.org/api/os.html#os_os_networkinterfaces

var os = require('os');

var interfaces = os.networkInterfaces();
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}

console.log(addresses);

My version which was needed for a compact and single file script, hope to be useful for others:

var ifs = require('os').networkInterfaces();
var result = Object.keys(ifs)
  .map(x => [x, ifs[x].filter(x => x.family === 'IPv4')[0]])
  .filter(x => x[1])
  .map(x => x[1].address);

Or to answer the original question:

var ifs = require('os').networkInterfaces();
var result = Object.keys(ifs)
  .map(x => ifs[x].filter(x => x.family === 'IPv4' && !x.internal)[0])
  .filter(x => x)[0].address;

https://github.com/indutny/node-ip

var ip = require("ip");
console.dir ( ip.address() );

Tags:

Node.Js