在Qt中获取Windows上的MAC地址

时间:2011-09-30 11:53:38

标签: qt4 qtnetwork

我试图使用以下代码在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

我应该包含哪些库才能使其正常工作?

2 个答案:

答案 0 :(得分:41)

使用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 :(得分:3)

我一直在寻找相同的东西,并且在虚拟机和不同类型的承载方面存在一些问题,这是我找到的另一种方法:

{{1}}