Get local IP address in node.js

2019-01-03 04:02发布

I have a simple node.js program running on my machine and I want to get local IP address of PC on which is my program running. How do I get it with node.js?

30条回答
来,给爷笑一个
2楼-- · 2019-01-03 04:34

Here's my utility method for getting the local IP address, assuming you are looking for an IPv4 address and the machine only has one real network interface. It could easily be refactored to return an array of IPs for multi-interface machines.

function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];

    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
        return alias.address;
    }
  }

  return '0.0.0.0';
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-03 04:34

Google directed me to this question while searching for "node.js get server ip", so let's give an alternative answer for those who are trying to achieve this in their node.js server program (may be the case of the original poster).

In the most trivial case where the server is bound to only one IP address, there should be no need to determine the IP address since we already know to which address we bound it (eg. second parameter passed to the listen() function).

In the less trivial case where the server is bound to multiple IPs addresses, we may need to determine the IP address of the interface to which a client connected. And as briefly suggested by Tor Valamo, nowadays, we can easily get this information from the connected socket and its localAddress property.

For example, if the program is a web server:

var http = require("http")

http.createServer(function (req, res) {
    console.log(req.socket.localAddress)
    res.end(req.socket.localAddress)
}).listen(8000)

And if it's a generic TCP server:

var net = require("net")

net.createServer(function (socket) {
    console.log(socket.localAddress)
    socket.end(socket.localAddress)
}).listen(8000)

When running a server program, this solution offers very high portability, accuracy and efficiency.

For more details, see:

查看更多
地球回转人心会变
4楼-- · 2019-01-03 04:35

Here's a simplified version in vanilla javascript to obtain a single ip:

function getServerIp() {

  var os = require('os');
  var ifaces = os.networkInterfaces();
  var values = Object.keys(ifaces).map(function(name) {
    return ifaces[name];
  });
  values = [].concat.apply([], values).filter(function(val){ 
    return val.family == 'IPv4' && val.internal == false; 
  });

  return values.length ? values[0].address : '0.0.0.0';
}
查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-03 04:35

I wrote a Node.js module that determines your local IP address by looking at which network interface contains your default gateway.

This is more reliable than picking an interface from os.networkInterfaces() or DNS lookups of the hostname. It is able to ignore VMware virtual interfaces, loopback, and VPN interfaces, and it works on Windows, Linux, Mac OS, and FreeBSD. Under the hood, it executes route.exe or netstat and parses the output.

var localIpV4Address = require("local-ipv4-address");

localIpV4Address().then(function(ipAddress){
    console.log("My IP address is " + ipAddress);
    // My IP address is 10.4.4.137 
});
查看更多
看我几分像从前
6楼-- · 2019-01-03 04:37

The correct one liner for both underscore and lodash is:

var ip = require('underscore')
    .chain(require('os').networkInterfaces())
    .values()
    .flatten()
    .find({family: 'IPv4', internal: false})
    .value()
    .address;
查看更多
Anthone
7楼-- · 2019-01-03 04:37

I was able to do this using just node js

As Node JS

var os = require( 'os' );
var networkInterfaces = Object.values(os.networkInterfaces())
    .reduce((r,a)=>{
        r = r.concat(a)
        return r;
    }, [])
    .filter(({family, address}) => {
        return family.toLowerCase().indexOf('v4') >= 0 &&
            address !== '127.0.0.1'
    })
    .map(({address}) => address);
var ipAddresses = networkInterfaces.join(', ')
console.log(ipAddresses);

As bash script (needs node js installed)

function ifconfig2 ()
{
    node -e """
        var os = require( 'os' );
        var networkInterfaces = Object.values(os.networkInterfaces())
            .reduce((r,a)=>{
                r = r.concat(a)
                return r;
            }, [])
            .filter(({family, address}) => {
                return family.toLowerCase().indexOf('v4') >= 0 &&
                    address !== '127.0.0.1'
            })
            .map(({address}) => address);
        var ipAddresses = networkInterfaces.join(', ')
        console.log(ipAddresses);
    """
}
查看更多
登录 后发表回答