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

8

67

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

Company answered 25/5, 2012 at 7:31 Comment(2)
https://mcmap.net/q/80617/-get-local-ip-address-in-node-jsAchromaticity
possible duplicate of Get local IP address in node.jsCraver
S
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);
Swaziland answered 25/5, 2012 at 14:42 Comment(5)
For those searching the interwebz, this is more commonly called the network IP.Disinfection
I took this technique and wrapped it up into a module called interface-addresses. Check it out here github.com/nisaacson/interface-addressesPatinated
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.Phlegm
can you please help me to solve this #52242299 @SwazilandAdsorbent
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.Joyajoyan
E
105

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

var ip = require("ip");
console.dir ( ip.address() );
Elyse answered 26/12, 2013 at 15:25 Comment(6)
This is the shortest solutionNewt
In fact if you only need the IP, this solution is ~380 lines longer than the accepted one, as you need to include node-ipHydrate
@Hydrate : 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.Jobe
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.Romola
I keep getting back ip 127.0.0.1 not the address?Delmydeloach
can you please help me to solve this #52242299 @JanjunaAdsorbent
K
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();
Kirwin answered 27/9, 2015 at 4:40 Comment(0)
P
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;
Photoflash answered 13/8, 2016 at 4:31 Comment(3)
Those loooooong 1-liners are killing me. Would prefer it multi-line & indented. Sexy solution tho.Tribromoethanol
@MarcusParsons: Have you tested it?Photoflash
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!Zena
B
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.

Berretta answered 16/6, 2015 at 9:57 Comment(0)
D
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"}
Dael answered 17/6, 2020 at 13:42 Comment(0)
B
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.

Burse answered 6/6, 2019 at 18:0 Comment(0)
R
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...'
Remarkable answered 15/12, 2020 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.