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 地址。







  

    

    Electron IP Address

  

  

    

    

     

你可能感兴趣的:(electron,javascript,前端)