场景:设备物理标识和账号进行绑定的场景,需要拿到设备的信息 如 mac  address 等;

设备:当前对win10 和 win7 的获取方法进行总结: 台式PC   一体机  笔记本 ;

网上的方法均为下面这种:

let interfaces = require('os').networkInterfaces()
let mac = interfaces['以太网'][1].mac
let ipv4 = interfaces['以太网'][1].address

但是上面这种只是win10 台式机联网后,才能获取到;

且在win7  时我们需要这样获取:

let interfaces = require('os').networkInterfaces()
let mac = interfaces['本地连接'][1].mac
let ipv4 = interfaces['本地连接'][1].address

而当笔记本或一体机 使用无线网络连接时,需要这样获取:

WIN10

et interfaces = require('os').networkInterfaces()
let mac = interfaces['WLAN'][1].mac
let ipv4 = interfaces['WLAN'][1].address

WIN7

et interfaces = require('os').networkInterfaces()
let mac = interfaces['无线网络连接'][3].mac
let ipv4 = interfaces['无线网络连接'][3].address

但当我们业务使用时,不可能将上述方法全写一边,那么我们来汇总一下:

function getPcMsg() {
    let interfaces = require('os').networkInterfaces()
    let pcObj = {}
    let pcMessage = []
    for (let key in interfaces) {
        if(key.indexOf('WLAN') !== -1 || key.indexOf('无线网络连接') !== -1 || key.indexOf('以太网') !== -1 || key.indexOf('本地连接') !== -1) {
            pcObj = interfaces[key]
        }
    }
    pcMessage = pcObj.filter((item) => {
        if(item.family === 'IPv4') {
            return item
        }
    })
    return pcMessage[0]
}

let mac = getPcMsg().mac
let ipv4 = getPcMsg().address

除此之外还有一个大问题需要解决:

场景:当使用笔记本或者一体机时, 既可以无线网络连接网络,也可以使用网线连接网络;

1.用户在无线联网时,进行设备绑定,此时获取到的是无线网卡的mac物理地址,无线网卡的物理地址与登陆账户绑定后; 下次用户插上网线,使用该账户登录,系统判断有线网卡物理地址未与账户绑定;

2.用户在插网线联网时,进行设备绑定,此时获取到的是有线网卡的mac物理地址,有线网卡的物理地址与登陆账户绑定后; 下次用户WIFI联网,使用该账户登录,系统判断无线网卡物理地址未与账户绑定;

以上两种情况怎么解决呢? 经测试发现,如果同时具备无线和有线 两种上网功能,会出现该情况:

1.wifi 联网时  interfaces  返回包含无线网卡物理地址;

2.有线联网时  interfaces  返回包含无线网卡和有线网卡 两种物理地址;

如此在考虑解决上述场景的情况,将代码优化为:

function getPcMsg() {
    let interfaces = require('os').networkInterfaces()
    let pcObj = {}
    let pcMessage = []
    for (let key in interfaces) {
        if(key.indexOf('WLAN') !== -1 || key.indexOf('无线网络连接') !== -1) {
            pcObj = interfaces[key]
            break
        } else if (key.indexOf('以太网') !== -1 || key.indexOf('本地连接') !== -1) {
            pcObj = interfaces[key]
        } else if (Object.keys(pcObj).length < 1) {
            pcObj = interfaces[key]
        }
    }
    pcMessage = pcObj.filter((item) => {
        if(item.family === 'IPv4') {
            return item
        }
    })
    return pcMessage[0]
}

let mac = getPcMsg().mac
let ipv4 = getPcMsg().address

内容原创,转载请注明出处

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐