获取NodeJS服务器上的本地网络IP地址

问题描述 投票:0回答:2

我需要获取向 NodeJS 服务器发出请求的信息(私有 IP 地址和 MAC)。这是在内联网上运行的,所以我想我可以以某种方式获取MAC数据,而来自

os.networkinterfaces() or req.connection
的IP对我来说没有用,因为它们分别给了我服务器或公共IP。

node.js ip-address
2个回答
1
投票

本地设备

Npm

npm install local-devices

示例

// Using a transpiler
import find from 'local-devices'
// Without using a transpiler
const find = require('local-devices');
 
// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

0
投票

你可以试试

const os = require('os');

function getLocalIP() {
  const ifaces = os.networkInterfaces();
  let ipAddress;

  Object.keys(ifaces).forEach((ifname) => {
    ifaces[ifname].forEach((iface) => {
      if (iface.family === 'IPv4' && !iface.internal) {
        ipAddress = iface.address;
      }
    });
  });

  return ipAddress;
}

console.log(`Local IP Address: ${getLocalIP()}`);
© www.soinside.com 2019 - 2024. All rights reserved.