qt获得mac地址

我们在和服务器进行通讯时,有时需要上传本机相关信息:账号、IP、mac、硬盘序列号、cpu等等信息,关于获取这些信息的方式有:

QHostInfo【获取自己机器的主机名,也能获取远程服务器的IP地址信息或者根据IP地址找到对应的主机名称,查询方式也有阻塞式】,具体使用直接百度;

QNetworkInterface【这个主要是获取IP地址和mac地址等信息】

这里总结下在获取mac地址时,实际的场景中有虚拟机,自己项目的需求是:优先取物理机,且最多取两个(一般的个人PC也就两个:有线网卡和无线网卡),如果没有物理机网卡,然后再取虚拟网卡(非物理网卡),关键代码如下:

由于笔者是linux环境,linux下获得虚拟网卡的方式参考的该博文:

https://blog.csdn.net/weixin_34055787/article/details/94046205

问题来了:windows下就自行百度了,方法也应该很多,估计从注册表获取吧。

下面代码为linux下获得mac地址的方式:

QString MainWindow::getMacAddress(bool deleteColon)
{
    QString macAddr = "";
    QStringList physicsMacDevices = QStringList();
    QStringList virtualMacDevices = QStringList();
    QList nets = QNetworkInterface::allInterfaces(); // 获取所有网络接口列表

    //获得所有的虚拟网卡
    QStringList allVirtualMac = QStringList();
    QProcess *process = new QProcess(this);

     connect(process, static_cast(&QProcess::finished),
             this, [&](int exitCode, QProcess::ExitStatus exitStatus) {
            if(exitCode == 0 && exitStatus == QProcess::ExitStatus::NormalExit) {
                allVirtualMac << QString::fromLocal8Bit(process->readAllStandardOutput()).split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
                qDebug() << "all virtual mac " << allVirtualMac;
            }
                process->deleteLater();
    });

    process->start("ls", QStringList()<<"/sys/devices/virtual/net/");
    //等待process执行结束
    process->waitForFinished();

    int macCount = nets.count();
    QString strMacAddr = "";
    for (int i = 0; i < macCount; i++) {
        // 非回环地址:127.0.0.1
        if (!nets[i].flags().testFlag(QNetworkInterface::IsLoopBack)) {
            strMacAddr = nets[i].hardwareAddress();
            if (deleteColon)
                strMacAddr.replace(":", "");
            qDebug() << "-----" << i << strMacAddr;
            if (allVirtualMac.contains(nets[i].humanReadableName())) {
                virtualMacDevices.append(strMacAddr);
                qDebug() << "virtual address" << strMacAddr;
            } else {
                physicsMacDevices.append(strMacAddr);
                qDebug() << "Physics address" << strMacAddr;
            }
        }

        if (physicsMacDevices.size() == 2)
            break;
    }

    if (!physicsMacDevices.isEmpty()) {
        macAddr = QString(physicsMacDevices.join(","));
        qDebug() << "return physics macAddr" << macAddr;
        return macAddr;
    }

    if (!virtualMacDevices.isEmpty()) {
        if (virtualMacDevices.size() > 1)
            macAddr = virtualMacDevices.at(0) + "," + virtualMacDevices.at(1);
        else
            macAddr = virtualMacDevices.at(0);
    }
    qDebug() << "return macAddr" << macAddr;
    return macAddr;
}

 

你可能感兴趣的:(qt获得mac地址)