我有一个简单的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;
}
其他回答
对于任何对简洁感兴趣的人来说,这里有一些“一行程序”,它们不需要不是标准Node.js安装的一部分的插件/依赖项:
eth0的公共IPv4、IPv6地址为阵列:
var ips = require('os').networkInterfaces().eth0.map(function(interface) {
return interface.address;
});
eth0的第一个公网IP地址(一般为IPv4):
var ip = require('os').networkInterfaces().eth0[0].address;
我写了一个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
});
我可能在这个问题上迟到了,但如果有人想要一个一行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
安装一个名为ip的模块,如下:
npm install ip
然后使用下面的代码:
var ip = require("ip");
console.log(ip.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);