Node.js 中获取本机 IP 地址可以通过多种方式实现,以下是几种常见的方法:
IP 地址是互联网协议地址,用于在网络中唯一标识一台设备。本机 IP 地址指的是设备在本地网络中的地址。
os
模块Node.js 的内置 os
模块提供了获取网络接口信息的功能。
const os = require('os');
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name in interfaces) {
const iface = interfaces[name];
for (let i = 0; i < iface.length; i++) {
const alias = iface[i];
if (alias.family === 'IPv4' && !alias.internal) {
return alias.address;
}
}
}
return '0.0.0.0';
}
console.log('本机 IP 地址:', getLocalIP());
network
模块可以通过第三方模块 network
来获取 IP 地址。
npm install network
然后在代码中使用:
const network = require('network');
network.get_private_ip((err, ip) => {
if (err) {
console.error('获取 IP 地址失败:', err);
} else {
console.log('本机 IP 地址:', ip);
}
});
dns
模块通过 dns
模块可以查询本机的主机名,然后获取对应的 IP 地址。
const dns = require('dns');
const os = require('os');
dns.lookup(os.hostname(), (err, address, family) => {
if (err) {
console.error('获取 IP 地址失败:', err);
} else {
console.log('本机 IP 地址:', address);
}
});
127.0.0.1
或 ::1
:!alias.internal
)的 IPv4 地址。通过上述方法,可以有效地在 Node.js 应用中获取本机的 IP 地址,并根据不同的应用场景进行相应的配置和使用。
领取专属 10元无门槛券
手把手带您无忧上云