c++

c++如何获取mac地址

小亿
120
2024-08-01 18:50:16
栏目: 编程语言

在C++中获取Mac地址通常需要使用操作系统提供的API来实现。以下是一种在Windows和Linux操作系统中获取Mac地址的方法:

  1. 使用Windows API获取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;
}
  1. 使用Linux系统调用获取Mac地址:
#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;
}

请注意,这些代码片段仅供参考,实际环墋中可能需要根据具体情况进行调整和改进。

0
看了该问题的人还看了