實例代碼:
#include <Windows.h> #include <iphlpapi.h> #include <list> #include <string> #pragma comment(lib, "Iphlpapi.lib") std::list<std::string> GetMACs() { std::list<std::string> lst; ULONG ulSize = 0; ::GetAdaptersInfo(nullptr, &ulSize); if (ulSize == 0) return lst; PIP_ADAPTER_INFO pInfo = (PIP_ADAPTER_INFO)malloc(ulSize); if (::GetAdaptersInfo(pInfo, &ulSize) != ERROR_SUCCESS) { free(pInfo); return lst; } PIP_ADAPTER_INFO pNext = pInfo; while (pNext != nullptr) { std::string mac; char tmp[10]; for (int i = 0; i < (int)pNext->AddressLength; i++) { sprintf_s(tmp, "%02X-", pNext->Address[i]); mac += tmp; } if (!mac.empty()) { mac.pop_back(); lst.emplace_back(std::move(mac)); } pNext = pNext->Next; } free(pInfo); return lst; } int main() { GetMACs(); return 0; }