2011-09-30 4 views
11

이 코드 사용하여 윈도우 XP에 MAC 주소를 얻기 위해 시도하는 오전에 창에 주소를 입수 코드는 여기에 제안 된MAC는 Qt를

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를하고 QtNetwork 모듈

답변

37

, 당신이 그와 같은 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 –

+1

우분투에서도 작동합니다 – PedroMorgan

+0

안드로이드에서 WiFi가 연결되어 있지 않으면 인터페이스는 루프백이되고'hardwareAddress()'는'00 : 00 : 00 : 00 : 00 : 00'. –

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