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


当前回答

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

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

其他回答

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

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);

使用内部ip:

const internalIp = require("internal-ip")

console.log(internalIp.v4.sync())

使用npm ip模块:

var ip = require('ip');

console.log(ip.address());

> '192.168.0.117'

我写了一个Node.js模块,通过查看包含默认网关的网络接口来确定您的本地IP地址。

这比从os.networkInterfaces()或DNS查找主机名更可靠。它可以忽略VMware虚拟接口、环回接口和VPN接口,它可以在Windows、Linux、Mac OS和FreeBSD上工作。在底层,它执行route.exe或netstat并解析输出。

var localIpV4Address = require("local-ipv4-address");

localIpV4Address().then(function(ipAddress){
    console.log("My IP address is " + ipAddress);
    // My IP address is 10.4.4.137 
});

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

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

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