在C++中獲取Mac地址通常需要使用操作系統(tǒng)提供的API來實現(xiàn)。以下是一種在Windows和Linux操作系統(tǒng)中獲取Mac地址的方法:
#include <iostream>
#include <WinSock2.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi.lib")
int main()
{
PIP_ADAPTER_INFO pAdapterInfo;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
if (pAdapterInfo == NULL) {
std::cout << "Memory allocation failed" << std::endl;
return 1;
}
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(ulOutBufLen);
if (pAdapterInfo == NULL) {
std::cout << "Memory allocation failed" << std::endl;
return 1;
}
}
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == NO_ERROR) {
std::cout << "MAC Address: " << pAdapterInfo->Address[0] << ":" << pAdapterInfo->Address[1] << ":" << pAdapterInfo->Address[2] << ":" << pAdapterInfo->Address[3] << ":" << pAdapterInfo->Address[4] << ":" << pAdapterInfo->Address[5] << std::endl;
} else {
std::cout << "Failed to get MAC address" << std::endl;
}
free(pAdapterInfo);
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
int main() {
std::string mac_address = exec("ifconfig | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'");
std::cout << "MAC Address: " << mac_address << std::endl;
return 0;
}
請注意,這些代碼片段僅供參考,實際環(huán)墋中可能需要根據(jù)具體情況進行調(diào)整和改進。