在 Node.js 中获取本地 IP 地址 [英] Get local IP address in Node.js
本文介绍了在 Node.js 中获取本地 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的机器上运行了一个简单的 Node.js 程序,我想获取运行我的程序的 PC 的本地 IP 地址.我如何使用 Node.js 获取它?
I have a simple Node.js program running on my machine and I want to get the local IP address of a PC on which my program is running. How do I get it with Node.js?
推荐答案
此信息可在 中找到os.networkInterfaces()
, — 一个对象,将网络接口名称映射到其属性(例如,一个接口可以有多个地址):
This information can be found in os.networkInterfaces()
, — an object, that maps network interface names to its properties (so that one interface can, for example, have several addresses):
'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"
这篇关于在 Node.js 中获取本地 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文