electron 获取本机 ip 地址
1. 主进程代码
在主进程中,使用 `os` 模块获取本机 IP 地址,并通过 `ipcMain` 将结果发送给渲染进程。
// main.js
const { app, BrowserWindow, ipcMain } = require("electron");
const os = require("os");
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextBridge: true,
},
});
win.loadFile("index.html");
}
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// 获取本机 IP 地址的函数
function getLocalIP() {
let interfaces = os.networkInterfaces();
for (let devName in interfaces) {
let iface = interfaces[devName];
for (let i = 0; i < iface.length; i++) {
let alias = iface[i];
if (
alias.family === "IPv4" &&
alias.address !== "127.0.0.1" &&
!alias.internal
) {
return alias.address;
}
}
}
}
// 监听渲染进程的请求
ipcMain.on("get-ip-address", (event) => {
const localIP = getLocalIP();
event.reply("ip-address", localIP);
});
2. 渲染进程代码
在渲染进程中,使用 `ipcRenderer` 向主进程发送请求,并接收主进程返回的 IP 地址。
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Electron IP Address</title>
</head>
<body>
<button id="get-ip">获取本机 IP 地址</button>
<p id="ip-address"></p>
<script>
const { ipcRenderer } = require("electron");
const getIpButton = document.getElementById("get-ip");
const ipAddressDisplay = document.getElementById("ip-address");
getIpButton.onclick = () => {
ipcRenderer.send("get-ip-address");
};
ipcRenderer.on("ip-address", (event, ip) => {
ipAddressDisplay.textContent = ip;
});
</script>
</body>
</html>