我有一个简单的Node.js程序在我的机器上运行,我想获得我的程序正在运行的PC的本地IP地址。我如何在Node.js中获得它?


当前回答

对上面答案的改进,原因如下:

Code should be as self-explanatory as possible. Enumerating over an array using for...in... should be avoided. for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available. var os = require('os'), interfaces = os.networkInterfaces(), address, addresses = [], i, l, interfaceId, interfaceArray; for (interfaceId in interfaces) { if (interfaces.hasOwnProperty(interfaceId)) { interfaceArray = interfaces[interfaceId]; l = interfaceArray.length; for (i = 0; i < l; i += 1) { address = interfaceArray[i]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } } console.log(addresses);

其他回答

我使用的是Node.js 0.6.5:

$ node -v
v0.6.5

我是这样做的:

var util = require('util');
var exec = require('child_process').exec;

function puts(error, stdout, stderr) {
        util.puts(stdout);
}

exec("hostname -i", puts);

下面是前面例子的一个变种。它会小心过滤掉VMware接口等。如果你不传递索引,它会返回所有地址。否则,您可能希望将其默认值设置为0,然后传递null以获取所有值,但您将整理这些。如果想要添加的话,还可以为regex过滤器传入另一个参数。

function getAddress(idx) {

    var addresses = [],
        interfaces = os.networkInterfaces(),
        name, ifaces, iface;

    for (name in interfaces) {
        if(interfaces.hasOwnProperty(name)){
            ifaces = interfaces[name];
            if(!/(loopback|vmware|internal)/gi.test(name)){
                for (var i = 0; i < ifaces.length; i++) {
                    iface = ifaces[i];
                    if (iface.family === 'IPv4' &&  !iface.internal && iface.address !== '127.0.0.1') {
                        addresses.push(iface.address);
                    }
                }
            }
        }
    }

    // If an index is passed only return it.
    if(idx >= 0)
        return addresses[idx];
    return addresses;
}

下面是我获取本地IP地址的实用方法,假设您正在寻找一个IPv4地址,而机器只有一个真实的网络接口。可以很容易地对其进行重构,以返回多接口机器的IP地址数组。

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';
}

对于Underscore.js和Lodash,正确的一行代码是:

var ip = require('underscore')
    .chain(require('os').networkInterfaces())
    .values()
    .flatten()
    .find({family: 'IPv4', internal: false})
    .value()
    .address;

对于任何对简洁感兴趣的人来说,这里有一些“一行程序”,它们不需要不是标准Node.js安装的一部分的插件/依赖项:

eth0的公共IPv4、IPv6地址为阵列:

var ips = require('os').networkInterfaces().eth0.map(function(interface) {
    return interface.address;
});

eth0的第一个公网IP地址(一般为IPv4):

var ip = require('os').networkInterfaces().eth0[0].address;