electron中获取mac地址

electron中获取mac地址

引入
为了方便做单点登录,我们往往需要使用某个唯一标识来标记客户端的设备,mac地址就是一个还不错的选择

思路

我们可以使用Node.js的内置模块os,调用其中的networkInterfaces方法。该方法会返回一个包含网络接口信息的数组对象,通过遍历该数组对象,可以获取到Mac地址,我们先看下调用得到的响应内容

TypeScript 复制代码
import { networkInterfaces } from "os";
console.log(JSON.stringify(networkInterfaces()));
TypeScript 复制代码
{
        "Ethernet0": [{
                "address": "fe80::803c:6a7b:14b0:f652",
                "netmask": "ffff:ffff:ffff:ffff::",
                "family": "IPv6",
                "mac": "00:0c:29:ea:41:55",
                "internal": false,
                "cidr": "fe80::803c:6a7b:14b0:f652/64",
                "scopeid": 7
        }, {
                "address": "192.168.213.154",
                "netmask": "255.255.255.0",
                "family": "IPv4",
                "mac": "00:0c:29:ea:41:55",
                "internal": false,
                "cidr": "192.168.213.154/24"
        }],
        "Loopback Pseudo-Interface 1": [{
                "address": "::1",
                "netmask": "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
                "family": "IPv6",
                "mac": "00:00:00:00:00:00",
                "internal": true,
                "cidr": "::1/128",
                "scopeid": 0
        }, {
                "address": "127.0.0.1",
                "netmask": "255.0.0.0",
                "family": "IPv4",
                "mac": "00:00:00:00:00:00",
                "internal": true,
                "cidr": "127.0.0.1/8"
        }]
}

封装代码

可以看到是个键值对的形式,所以我们直接获取key,然后遍历取值,再获取对象中的mac地址即可:

TypeScript 复制代码
/**获取mac地址信息 */
export const getMacAddress = function (): string {
  const interfaces = networkInterfaces();
  let macAddress = "";
  for (const interfaceName of Object.keys(interfaces)) {
    const interfaceInfos = interfaces[interfaceName];

    if (interfaceInfos) {
      for (const interfaceInfo of interfaceInfos) {
        if (interfaceInfo.mac && interfaceInfo.mac !== "00:00:00:00:00:00") {
          macAddress = interfaceInfo.mac;
          break;
        }
      }
    }

    if (macAddress.length > 0) break;
  }

  return macAddress;
};
相关推荐
进击的尘埃1 天前
Playwright Component Testing 拆到底:组件怎么挂上去的,快照怎么在 CI 里不翻车
javascript
左夕1 天前
最基础的类型检测工具——typeof, instanceof
前端·javascript
yuki_uix1 天前
递归:别再"展开脑补"了,学会"信任"才是关键
前端·javascript
用户5757303346241 天前
🐱 从“猫厂”倒闭到“鸭子”横行:一篇让你笑出腹肌的 JS 面向对象指南
javascript
码路飞1 天前
GPT-5.4 Computer Use 实战:3 步让 AI 操控浏览器帮你干活 🖥️
java·javascript
进击的尘埃1 天前
Service Worker 离线缓存这事,没你想的那么简单
javascript
进击的尘埃1 天前
HTTP/3 的多路复用和 QUIC 到底能让页面快多少?聊聊连接迁移和 0-RTT
javascript
Maxkim1 天前
前端工程化落地指南:pnpm workspace + Monorepo 核心用法与实践
前端·javascript·架构
小兵张健2 天前
开源 playwright-pool 会话池来了
前端·javascript·github
codingWhat2 天前
介绍一个手势识别库——AlloyFinger
前端·javascript·vue.js