66

I'm not referring to

127.0.0.1

But rather the one that other computers would use to access the machine e.g.

192.168.1.6

deltanovember
  • 42,611
  • 64
  • 162
  • 244

8 Answers8

128

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);
Eric Lagergren
  • 501
  • 2
  • 7
  • 18
seppo0010
  • 15,184
  • 5
  • 31
  • 30
  • 8
    For those searching the interwebz, this is more commonly called the network IP. – jonathanberi Dec 26 '12 at 15:57
  • 2
    I took this technique and wrapped it up into a module called interface-addresses. Check it out here https://github.com/nisaacson/interface-addresses – Noah Jul 12 '13 at 21:36
  • 2
    Just to understand, why are there more than one IP address? When I run it with gulp I get: `en0`, `vnic0`, `vnic01`. `en0` is the one browsersync displays to me. – Andi Giga Nov 14 '15 at 11:04
  • can you please help me to solve this https://stackoverflow.com/questions/52241799/failed-to-compile-node-modules-macaddress-lib-windows-js-in-angular-5 @seppo0010 – Zhu Sep 09 '18 at 06:13
  • Hey you might want to make a comment about how this filters out valid non-internal ipv6 addresses. Great answer to the question though, thank you. – Llama D'Attore Oct 07 '20 at 23:03
105

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

var ip = require("ip");
console.dir ( ip.address() );
Jan Jůna
  • 4,965
  • 3
  • 21
  • 27
  • 1
    This is the shortest solution – Manolo Carrasco Moñino Feb 27 '15 at 10:21
  • 11
    In fact if you only need the IP, this solution is ~380 lines longer than the accepted one, as you need to include `node-ip` – wacko Apr 08 '15 at 00:49
  • 3
    @wacko : so what, it's testet and provides a concise api. As it runs on the server 380 loc in a library are realy not worth mentioning. Also it has no dependecies itself which is nice. – Blank Chisui May 14 '15 at 13:08
  • 1
    This is cool but won't work in the case of vagrant boxes that have a private network set. You'll get the eth0 address when you really want the eth1 address. – HeadCode May 27 '16 at 00:23
  • 1
    I keep getting back ip 127.0.0.1 not the address? – ALM Jun 14 '16 at 23:49
  • can you please help me to solve this https://stackoverflow.com/questions/52241799/failed-to-compile-node-modules-macaddress-lib-windows-js-in-angular-5 @Janjuna – Zhu Sep 09 '18 at 06:13
10
$ npm install --save quick-local-ip

follwed by

var myip = require('quick-local-ip');

//getting ip4 network address of local system
myip.getLocalIP4();

//getting ip6 network address of local system
myip.getLocalIP6();
Alok G.
  • 1,388
  • 3
  • 15
  • 26
10

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;
Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81
  • Those loooooong 1-liners are killing me. Would prefer it multi-line & indented. Sexy solution tho. – The Qodesmith Oct 06 '16 at 16:01
  • 1
    @MarcusParsons: Have you tested it? – Ebrahim Byagowi Mar 10 '22 at 23:53
  • 1
    I have removed my comment. In fact, the `.filter(x => x)` removes the undefined entries which I didn't see. I did test it, but I had no undefined entries. I tested it on a REPL server after that, though, and had undefined entries. Thanks, Ebrahim! – Marcus Parsons Mar 11 '22 at 00:16
6

https://github.com/dominictarr/my-local-ip

$ npm install -g my-local-ip
$ my-local-ip

or

$ npm install --save my-local-ip
$ node
> console.log(require('my-local-ip')())

A very small module that does just this.

theram
  • 5,503
  • 2
  • 13
  • 14
1

savage one-liner incoming

based on accepted answer, this one will build an array of objects with conditional entries depending on address properties

[{name: {interface name}, ip: {ip address}}, ...]
const ips = Object.entries(require("os").networkInterfaces()).reduce((acc, iface) => [...acc, ...(iface[1].reduce((acc, address) => acc || (address.family === "IPv4" && !address.internal), false) ? [{name: iface[0], ip: iface[1].filter(address => address.family === "IPv4" && !address.internal).map(address => address.address)[0]}] : [])], []);
console.log(ips);

Explained :

const ips = Object.entries(require("os").networkInterfaces()) // fetch network interfaces
.reduce((acc, iface) => [ // reduce to build output object
    ...acc, // accumulator
    ...(
        iface[1].reduce((acc, address) => acc || (address.family === "IPv4" && !address.internal), false) ? // conditional entry
        [ // validate, insert it in output
            { // create {name, ip} object
                name: iface[0], // interface name
                ip: iface[1] // interface IP
                .filter(address => address.family === "IPv4" && !address.internal) // check is IPv4 && not internal
                .map(address => address.address)[0] // get IP
            }
        ] 
        : 
        [] // ignore interface && ip
    )
], []);

Output example :

Array(4) [Object, Object, Object, Object]
length:4
__proto__:Array(0) [, …]
0:Object {name: "vEthernet (WSL)", ip: "172.31.xxx.x"}
1:Object {name: "Ethernet", ip: "10.0.x.xx"}
2:Object {name: "VMware Network Adapter VMnet1", ip: "192.168.xxx.x"}
3:Object {name: "VMware Network Adapter VMnet8", ip: "192.168.xx.x"}
nicopowa
  • 459
  • 3
  • 11
0

Ever since Node version 0.9.6 there is a simple way to get the server's IP address based on each request. This could be important if your machine has multiple IP addresses or even if you are doing something on localhost.

req.socket.localAddress will return the address of the machine node is running on based on the current connection.

If you have a public IP address of 1.2.3.4 and someone hits your node server from the outside then the value for req.socket.localAddress will be "1.2.3.4".

If you hit the same server from localhost then the address will be "127.0.0.1"

If your server has multiple public addresses then the value of req.socket.localAddress will be the correct address of the socket connection.

Intervalia
  • 10,248
  • 2
  • 30
  • 60
0

Modified a bit Ebrahim's answer with some es6 and module syntax, for leaner code:

import { networkInterfaces } from "os";
const netInterfaces = networkInterfaces();
const [{ address }] = Object.values(netInterfaces).flatMap((netInterface) =>
  netInterface.filter((prop) => prop.family === "IPv4" && !prop.internal)
);
console.log(address) // -> '192.168...'
Tzahi Leh
  • 2,002
  • 1
  • 15
  • 27