【问题标题】:Getting the ip address of the computer Node.JS获取计算机Node.JS的ip地址
【发布时间】:2019-04-26 12:18:49
【问题描述】:

我有一个问题,但是如何获取在 Node.JS 上运行我的应用程序的计算机的 IP 地址?重要的是,IP 地址不能是本地的(127.0.0.1 或 192.168.1.1)。提前谢谢你

【问题讨论】:

标签: javascript node.js ip node-modules


【解决方案1】:

您可以使用os.networkInterfaces()获取所有IP地址信息并排除本地地址。

根据 Node.js document:

os.networkInterfaces() 方法返回一个对象,该对象仅包含已分配网络地址的网络接口。

返回对象上的每个键标识一个网络接口。关联的值是一个对象数组,每个对象描述一个分配的网络地址。

这是一个代码示例:

'use strict';

const os = require('os');

let networkInterfaces = os.networkInterfaces();

let nonLocalInterfaces = {};
for (let inet in networkInterfaces) {
  let addresses = networkInterfaces[inet];
  for (let i=0; i<addresses.length; i++) {
    let address = addresses[i];
    if (!address.internal) {
      if (!nonLocalInterfaces[inet]) {
        nonLocalInterfaces[inet] = [];
      }
      nonLocalInterfaces[inet].push(address);
    }
  }
}

console.log(nonLocalInterfaces);

【讨论】:

    猜你喜欢
    • 2012-09-01
    • 2010-09-12
    • 2011-06-14
    • 1970-01-01
    • 2012-10-21
    • 2011-09-11
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多