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


当前回答

这里有一个可能是最干净、最简单的答案,没有依赖关系,而且适用于所有平台。

const { lookup } = require('dns').promises;
const { hostname } = require('os');

async function getMyIPAddress(options) {
  return (await lookup(hostname(), options))
    .address;
}

其他回答

一行程序只用于macOS的第一个本地主机地址。

当在macOS上开发应用程序时,你想在手机上测试它,并且需要你的应用程序自动选择本地主机IP地址。

require('os').networkInterfaces().en0.find(elm => elm.family=='IPv4').address

这只是提到如何自动查找ip地址。 要测试这个,你可以去终端点击

node
os.networkInterfaces().en0.find(elm => elm.family=='IPv4').address

输出将是您的本地主机IP地址。

这些信息可以在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"

对于Linux和macOS,如果你想通过同步方式获取你的IP地址,试试这个:

var ips = require('child_process').execSync("ifconfig | grep inet | grep -v inet6 | awk '{gsub(/addr:/,\"\");print $2}'").toString().trim().split("\n");
console.log(ips);

结果会是这样的:

['192.168.3.2', '192.168.2.1']

使用npm ip模块:

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'

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

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