electron 获取本机 ip 地址

1. 主进程代码

在主进程中,使用 `os` 模块获取本机 IP 地址,并通过 `ipcMain` 将结果发送给渲染进程。

javascript 复制代码
// 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 地址。

javascript 复制代码
<!-- 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>
相关推荐
lichenyang45319 分钟前
从 0 新增一个 `has.echo`:我如何理解小程序容器里的 API 调用链路
前端
leptune1 小时前
Mac 使用 Microsoft Word 批量将 DOCX 转 PDF(保持原排版)
前端
大龄秃头程序员1 小时前
Flutter 长列表 1 万条滑动卡顿治理:Baseline vs Optimized 可跑 Demo
前端
yingyima1 小时前
Git 核心命令速查:掌握底层原理与实战技巧
前端
黄林晴1 小时前
Kuikly 是什么?和KMP有什么关系?
android·前端
HokKeung1 小时前
Git Hooks 和 Husky 怎么选
前端·前端工程化
李明卫杭州1 小时前
Vue 3 响应式三剑客:ref、shallowRef、reactive,你真的用对了吗?
前端
触底反弹1 小时前
🔥 JavaScript this 指向全解析:面试必考的 5 大绑定规则
前端·javascript·面试
Csvn2 小时前
TypeScript 类型守卫的 4 个实战级别:从 `filter(Boolean)` 到自定义类型谓词
前端
骑士雄师2 小时前
langchain:推荐切片策略
服务器·前端·langchain