electron中获取mac地址的实现示例
作者:依星net188.com
在基于Electron的应用中,有一个业务需求是获取物理网卡的Mac地址以用于客户机唯一性识别,本文主要介绍了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; };
到此这篇关于electron中获取mac地址的实现示例的文章就介绍到这了,更多相关electron获取mac地址内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!