CString GetMAC(PCTSTR szURL)
{
CString sMAC;
PIP_ADAPTER_INFO pAdapterInfo(NULL);
try
{
if (NULL == szURL || 0 == szURL[0]) { throw 1; }
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) { throw 1; }
static HINSTANCE hDll(NULL);
if (NULL == hDll) {
hDll = LoadLibrary( "iphlpapi.dll" );
if (NULL == hDll) throw 2;
}
GETBESTINTERFACE GetBestInterface(NULL);
if ( GetBestInterface == NULL ) {
GetBestInterface = (GETBESTINTERFACE)GetProcAddress( hDll, "GetBestInterface" );
if ( GetBestInterface == NULL ) throw 3;
}
struct hostent *psthost;
psthost = gethostbyname("..");
if (psthost == NULL) throw 4;
DWORD iAddr = *(unsigned int *)psthost->h_addr_list[0];
DWORD iIndex(0);
GetBestInterface( iAddr, &iIndex );
static GETADAPTERSINFO GetAdaptersInfo(NULL);
if ( GetAdaptersInfo == NULL ) {
GetAdaptersInfo = (GETADAPTERSINFO) GetProcAddress( hDll, "GetAdaptersInfo" );
if( GetAdaptersInfo == NULL ) throw 5;
}
DWORD dwErr, dwAdapterInfoSize = 0;
if ((dwErr = GetAdaptersInfo(NULL, &dwAdapterInfoSize) ) != 0 ) {
if ( dwErr != ERROR_BUFFER_OVERFLOW ) throw 6;
}
if ( ( pAdapterInfo = (PIP_ADAPTER_INFO) GlobalAlloc( GPTR, dwAdapterInfoSize )) == NULL ) { throw 7; }
if ( ( dwErr = GetAdaptersInfo( pAdapterInfo, &dwAdapterInfoSize ) ) != 0 ) { throw 8; }
PIP_ADAPTER_INFO pAdapt;
for ( pAdapt = pAdapterInfo; pAdapt; pAdapt = pAdapt->Next ) {
if ( pAdapt->Index != iIndex ) continue;
char strMacAddr_[18];
memset(strMacAddr_, 0, sizeof strMacAddr_);
for (UINT i=0; i<pAdapt->AddressLength; i++) {
char temp_[3];
memset(temp_, 0, sizeof temp_);
sprintf(temp_, "%02X",(int)pAdapt->Address[i]);
strcat(strMacAddr_, temp_);
}
sMAC = strMacAddr_;
break;
}
} catch(int /* errNo */) {}
WSACleanup();
if (pAdapterInfo) GlobalFree( pAdapterInfo );
return sMAC;
}