在Qt中获取Windows的MAC地址

13

我正在尝试使用以下代码在Windows XP上获取 MAC 地址:

QString getMacAddress()
{
QString macaddress="??:??:??:??:??:??";
#ifdef Q_WS_WIN
PIP_ADAPTER_INFO pinfo=NULL;

unsigned long len=0;
unsigned long nError;

if (pinfo!=NULL)
delete (pinfo);

nError  =   GetAdaptersInfo(pinfo,&len);    //Have to do it 2 times?

if(nError != 0)
{
pinfo= (PIP_ADAPTER_INFO)malloc(len);
nError  =   GetAdaptersInfo(pinfo,&len);
}

if(nError == 0)
macaddress.sprintf("%02X:%02X:%02X:%02X:%02X:%02X",pinfo->Address[0],pinfo->Address[1],pinfo->Address[2],pinfo->Address[3],pinfo->Address[4],pinfo->Address[5]);
#endif
return macaddress;
}

这段代码建议从这里获取:http://www.qtforum.org/post/42589/how-to-obtain-mac-address.html#post42589

要使它工作,我应该包含哪些库?


可能是在Qt中获取MAC ID的重复问题。 - iammilind
我认为你应该进入你链接的问题,并将其标记为重复,因为我提出了我的问题2年前 - Gandalf
2个回答

45

使用Qt和QtNetwork模块,您可以像这样获取一个MAC地址:

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();
}

1
在Windows和MSVC编译器中,您应该用其他变量替换QNetworkInterface变量“interface”,否则编译会失败。还可以参见此线程的解释:http://qt-project.org/forums/viewthread/19133 - Christian Feldbacher
当Android未连接WiFi时,接口变为环回并且hardwareAddress()读取为00:00:00:00:00:00 - Ayberk Özgür
在 Mac OS X/Qt 5.6 上,此操作将返回一个空字符串。您可以通过仅在值非空时返回来解决此问题。 - Andy Brice

3

我也曾经遇到过在虚拟机和不同类型的载体上出现问题的情况,以下是我找到的另一种解决方法:

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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接