electron 获取本机 ip 地址

打印 上一主题 下一主题

主题 924|帖子 924|积分 2772

1.  主进程代码

在主进程中,使用 `os` 模块获取本机 IP 地址,并通过 `ipcMain` 将结果发送给渲染进程。
  1. // main.js
  2. const { app, BrowserWindow, ipcMain } = require("electron");
  3. const os = require("os");
  4. function createWindow() {
  5.   const win = new BrowserWindow({
  6.     width: 800,
  7.     height: 600,
  8.     webPreferences: {
  9.       nodeIntegration: true,
  10.       contextBridge: true,
  11.     },
  12.   });
  13.   win.loadFile("index.html");
  14. }
  15. app.whenReady().then(() => {
  16.   createWindow();
  17.   app.on("activate", () => {
  18.     if (BrowserWindow.getAllWindows().length === 0) {
  19.       createWindow();
  20.     }
  21.   });
  22. });
  23. // 获取本机 IP 地址的函数
  24. function getLocalIP() {
  25.   let interfaces = os.networkInterfaces();
  26.   for (let devName in interfaces) {
  27.     let iface = interfaces[devName];
  28.     for (let i = 0; i < iface.length; i++) {
  29.       let alias = iface[i];
  30.       if (
  31.         alias.family === "IPv4" &&
  32.         alias.address !== "127.0.0.1" &&
  33.         !alias.internal
  34.       ) {
  35.         return alias.address;
  36.       }
  37.     }
  38.   }
  39. }
  40. // 监听渲染进程的请求
  41. ipcMain.on("get-ip-address", (event) => {
  42.   const localIP = getLocalIP();
  43.   event.reply("ip-address", localIP);
  44. });
复制代码
2. 渲染进程代码

在渲染进程中,使用 `ipcRenderer` 向主进程发送请求,并吸收主进程返回的 IP 地址。
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4.   <head>
  5.     <meta charset="UTF-8" />
  6.     <title>Electron IP Address</title>
  7.   </head>
  8.   <body>
  9.     <button id="get-ip">获取本机 IP 地址</button>
  10.     <p id="ip-address"></p>
  11.     <script>
  12.       const { ipcRenderer } = require("electron");
  13.       const getIpButton = document.getElementById("get-ip");
  14.       const ipAddressDisplay = document.getElementById("ip-address");
  15.       getIpButton.onclick = () => {
  16.         ipcRenderer.send("get-ip-address");
  17.       };
  18.       ipcRenderer.on("ip-address", (event, ip) => {
  19.         ipAddressDisplay.textContent = ip;
  20.       });
  21.     </script>
  22.   </body>
  23. </html>
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

汕尾海湾

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表