electron中获取mac地址

2023-12-14 13:54:20

electron中获取mac地址

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

思路

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

import { networkInterfaces } from "os";
console.log(JSON.stringify(networkInterfaces()));

?

{
        "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地址即可:

/**获取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;
};

文章来源:https://blog.csdn.net/airen3339/article/details/134988107
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。