Obtaining MAC address on windows in Qt

前端 未结 2 513
一生所求
一生所求 2021-01-17 12:16

I am attempting to obtain mac address on windows xp using this code:

QString getMacAddress()
{
QString macaddress=\"??:??:??:??:??:??\";
#ifdef Q_WS_WIN
PIP_         


        
相关标签:
2条回答
  • 2021-01-17 12:50

    I was looking for the same and had some problems with virtual machines and different types of bearers, here's another approach that I found:

    QNetworkConfiguration nc;
    QNetworkConfigurationManager ncm;
    QList<QNetworkConfiguration> configsForEth,configsForWLAN,allConfigs;
    // getting all the configs we can
    foreach (nc,ncm.allConfigurations(QNetworkConfiguration::Active))
    {
        if(nc.type() == QNetworkConfiguration::InternetAccessPoint)
        {
            // selecting the bearer type here
            if(nc.bearerType() == QNetworkConfiguration::BearerWLAN)
            {
                configsForWLAN.append(nc);
            }
            if(nc.bearerType() == QNetworkConfiguration::BearerEthernet)
            {
                configsForEth.append(nc);
            }
        }
    }
    // further in the code WLAN's and Eth's were treated differently
    allConfigs.append(configsForWLAN);
    allConfigs.append(configsForEth);
    QString MAC;
    foreach(nc,allConfigs)
    {
        QNetworkSession networkSession(nc);
        QNetworkInterface netInterface = networkSession.interface();
        // these last two conditions are for omiting the virtual machines' MAC
        // works pretty good since no one changes their adapter name
        if(!(netInterface.flags() & QNetworkInterface::IsLoopBack)
                && !netInterface.humanReadableName().toLower().contains("vmware")
                && !netInterface.humanReadableName().toLower().contains("virtual"))
        {
            MAC = QString(netInterface.hardwareAddress());
            break;
        }
    }
    
    0 讨论(0)
  • 2021-01-17 13:02

    With Qt and the QtNetwork module, you can get one of the MAC addresses like that:

    QString getMacAddress()
    {
        foreach(QNetworkInterface netInterface, QNetworkInterface::allInterfaces())
        {
            // Return only the first non-loopback MAC Address
            if (!(netInterface.flags() & QNetworkInterface::IsLoopBack))
                return netInterface.hardwareAddress();
        }
        return QString();
    }
    
    0 讨论(0)
提交回复
热议问题