Deb*_*rth 6 javascript reactjs electron
我需要在 React js 应用程序中获取计算机的本地 IP。有人可以建议一个好方法吗?
您可以使用该os模块找到您机器的任何 IP 地址 - 这是 Node.js 原生的:
const os = require('os');
const networkInterfaces = os.networkInterfaces();
const ip = networkInterfaces['eth0'][0]['address']
console.log(networkInterfaces);
Run Code Online (Sandbox Code Playgroud)
更新:Windows操作系统解决方案
const { networkInterfaces } = require('os');
const getIPAddress = () => {
const nets = networkInterfaces();
const results = {};
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Retrieve only IPv4 addresses
if (net.family === 'IPv4' && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
// Return the first IP address for the first NIC found
const nicNames = Object.keys(results);
if (nicNames.length > 0) {
const firstNICAddresses = results[nicNames[0]];
if (firstNICAddresses.length > 0) {
return firstNICAddresses[0];
}
}
// No IP address found
return null;
};
const ipAddress = getIPAddress();
console.log(ipAddress);
Run Code Online (Sandbox Code Playgroud)
该解决方案使用 os.networkInterfaces() 方法检索所有网络接口及其关联的 IP 地址。然后,它过滤掉所有内部的 IPv4 地址(例如,环回)并将它们存储在由 NIC 名称索引的对象中。
最后,代码返回对象中第一个 NIC 找到的第一个 IP 地址,如果未找到 IP 地址,则返回 null。