阅读量:80
在C++中获取Mac地址通常需要使用操作系统提供的API来实现。以下是一种在Windows和Linux操作系统中获取Mac地址的方法:
- 使用Windows API获取Mac地址:
#include
#include
#include
#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 class="hljs-keyword">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 class="hljs-keyword">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 class="hljs-keyword">else {
std::cout << "Failed to get MAC address" << std class="hljs-built_in">free(pAdapterInfo);
return 0;
}
- 使用Linux系统调用获取Mac地址:
#include
#include
#include
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptrdecltype (&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 class="hljs-keyword">return 0;
}
请注意,这些代码片段仅供参考,实际环墋中可能需要根据具体情况进行调整和改进。