J
VS2003:
#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
#include <tchar.h>
#include <string>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "Ws2_32.lib")
std::string GetMACAddress(int adapternumber)
{
int nAdapterCount = 0;
ULONG ip;
ULONG buflen;
PIP_ADAPTER_INFO pAdInfo = NULL;
PIP_ADAPTER_INFO pAdInfo_c = NULL;
buflen = 0;
GetAdaptersInfo(pAdInfo, &buflen); //since buflen=0, buffer is
// too small. function returns required buffersize in buflen.
pAdInfo = (struct _IP_ADAPTER_INFO *)new UCHAR[buflen+1];
pAdInfo_c = pAdInfo;
if (GetAdaptersInfo(pAdInfo, &buflen) == ERROR_SUCCESS)
{
do
{
ip = inet_addr(pAdInfo->IpAddressList.IpAddress.String);
if ((ip != 0)&&(ip != 0x7f000001))
{
nAdapterCount++;
if ((nAdapterCount == adapternumber)||(adapternumber == 0))
{
if (pAdInfo->AddressLength != 0)
{
std::string macstr;
for (int i = 0; i < (int)pAdInfo->AddressLength; i++)
{
char szTemp[10];
sprintf(szTemp, "%02X", pAdInfo->Address[i]);
macstr += szTemp;
}
delete [] pAdInfo_c;
return macstr;
}
}
}
} while ((pAdInfo->Next != NULL)&&((pAdInfo = pAdInfo->Next) != pAdInfo));
}
delete [] pAdInfo_c;
return "";
}
int _tmain()
{
printf("MAC: %s\n", GetMACAddress(0).c_str());
}