解説
ネットワークアダプタのMACアドレス取得にはいくつかの方法がある。 「VC ++TIPS」にはここのものとは異なる方法での取得を紹介しています。ここではPlatform SDK(Internet Protocol Helper)を使用したMACアドレス取得 方法を紹介する。
ビルドにはPlatform SDKのインストールが必須。
この方法はWindows98以降に対応(Windows 95 非対応!:Windows NT4.0はSP4以降に対応)。
サンプル
void Test()
{
int i;
CString strMessage;
CStringArray astrMacAddress;
if(GetMacAddress(astrMacAddress) == false)
{
AfxMessageBox("取得できませんでした");
return;
}
for(i = 0; i < astrMacAddress.GetSize(); i++)
{
strMessage += astrMacAddress[i];
strMessage += "\n";
}
AfxMessageBox(strMessage);
}
取得部分
#include "afxtempl.h"
#include "iphlpapi.h"
#pragma comment(lib,"iphlpapi.lib")
//
// ビルド時 PMIB_ICMP_EX のエラーが出る場合は
// iphlpapi.h内のGetIcmpStatisticsEx() をコメ
// ントアウト!(どこで定義されてるの??)
//
// Platform SDK: Internet Protocol Helper
//
// GetIfTable() によるMACアドレスの取得
//
// Windows98以降に対応(Windows 95 非対応!:Windows NT4.0はSP4以降に対応)
//
bool GetMacAddress(CStringArray& astrMacAddress)
{
DWORD ret;
ULONG i;
ULONG dwSize;
BYTE* pBuff;
PMIB_IFTABLE pIfTable;
CString strBuff;
astrMacAddress.RemoveAll();
dwSize = 0;
::GetIfTable(NULL,&dwSize,TRUE); //必要バッファサイズ取得
pBuff = new BYTE[dwSize];
pIfTable = (PMIB_IFTABLE) pBuff;
ret = ::GetIfTable(pIfTable,&dwSize,TRUE);
if(ret == NO_ERROR)
{
for(i = 0; i < pIfTable->dwNumEntries; i++)
{
strBuff.Format("%02X%02X%02X%02X%02X%02X\n"
,pIfTable->table[i].bPhysAddr[0]
,pIfTable->table[i].bPhysAddr[1]
,pIfTable->table[i].bPhysAddr[2]
,pIfTable->table[i].bPhysAddr[3]
,pIfTable->table[i].bPhysAddr[4]
,pIfTable->table[i].bPhysAddr[5]);
astrMacAddress.Add(strBuff);
}
}
delete pBuff;
if(astrMacAddress.GetSize() > 0)
return true;
return false;
}
