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


当前回答

这些信息可以在os.networkInterfaces()中找到,这是一个对象,它将网络接口名称映射到它的属性(例如,一个接口可以有几个地址):

'use strict';

const { networkInterfaces } = require('os');

const nets = networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object

for (const name of Object.keys(nets)) {
    for (const net of nets[name]) {
        // Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
        // 'IPv4' is in Node <= 17, from 18 it's a number 4 or 6
        const familyV4Value = typeof net.family === 'string' ? 'IPv4' : 4
        if (net.family === familyV4Value && !net.internal) {
            if (!results[name]) {
                results[name] = [];
            }
            results[name].push(net.address);
        }
    }
}
// 'results'
{
  "en0": [
    "192.168.1.101"
  ],
  "eth0": [
    "10.0.0.101"
  ],
  "<network name>": [
    "<ip>",
    "<ip alias>",
    "<ip alias>",
    ...
  ]
}
// results["en0"][0]
"192.168.1.101"

其他回答

根据注释,以下是当前版本Node.js的工作原理:

var os = require('os');
var _ = require('lodash');

var ip = _.chain(os.networkInterfaces())
  .values()
  .flatten()
  .filter(function(val) {
    return (val.family == 'IPv4' && val.internal == false)
  })
  .pluck('address')
  .first()
  .value();

上面一个答案的注释缺少对values()的调用。看起来os.networkInterfaces()现在返回一个对象而不是数组。

我可能在这个问题上迟到了,但如果有人想要一个一行ES6解决方案来获得IP地址数组,那么这应该会帮助你:

Object.values(require("os").networkInterfaces())
    .flat()
    .filter(({ family, internal }) => family === "IPv4" && !internal)
    .map(({ address }) => address)

As

Object.values(require("os").networkInterfaces())

将返回一个数组的数组,所以flat()是用来将其平展为单个数组

.filter(({ family, internal }) => family === "IPv4" && !internal)

将过滤数组只包括IPv4地址,如果它不是内部

最后

.map(({ address }) => address)

是否只返回过滤数组的IPv4地址

所以结果是['192.168.xx。xx ']

然后,如果您想要或更改筛选条件,您可以获得该数组的第一个索引

操作系统为Windows

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

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

下面是一个允许你获取本地IP地址的变体(在Mac和Windows上测试):


var
    // Local IP address that we're trying to calculate
    address
    // Provides a few basic operating-system related utility functions (built-in)
    ,os = require('os')
    // Network interfaces
    ,ifaces = os.networkInterfaces();


// Iterate over interfaces ...
for (var dev in ifaces) {

    // ... and find the one that matches the criteria
    var iface = ifaces[dev].filter(function(details) {
        return details.family === 'IPv4' && details.internal === false;
    });

    if(iface.length > 0)
        address = iface[0].address;
}

// Print the result
console.log(address); // 10.25.10.147
var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress