我的计算机上运行了一个简单的Node.js程序,我想获取运行该程序的PC的本地IP地址。如何使用Node.js来获得它?
最佳答案
可以在 os.networkInterfaces()
中找到此信息,ojit_a是一个对象,该对象将网络接口(interface)名称映射到其属性(例如,一个接口(interface)可以具有多个地址):
'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
if (net.family === 'IPv4' && !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"
关于javascript - 在Node.js中获取本地IP地址,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3653065/