在Linux下使用C++ STL获取MAC地址的教程如下:

蓝易云服务器 - Linux下C++ STL获取Mac地址教程_网络接口

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>

// 从/sys/class/net目录获取所有网络接口的名称
std::vector<std::string> getInterfaceNames() {
    std::vector<std::string> names;
    std::ifstream file("/sys/class/net/operstate");
    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            if (line != "down") { // 只获取状态为"up"的接口
                std::string interfaceName = line.substr(0, line.find(':'));
                names.push_back(interfaceName);
            }
        }
        file.close();
    }
    return names;
}

// 从/sys/class/net/<interface>/address获取指定网络接口的MAC地址
std::string getMACAddress(const std::string& interfaceName) {
    std::string macAddress;
    std::ifstream file("/sys/class/net/" + interfaceName + "/address");
    if (file.is_open()) {
        std::getline(file, macAddress);
        file.close();
    }
    return macAddress;
}

int main() {
    std::vector<std::string> interfaceNames = getInterfaceNames();

    if (interfaceNames.empty()) {
        std::cout << "未找到可用的网络接口。\n";
        return 1;
    }

    for (const std::string& interfaceName : interfaceNames) {
        std::string macAddress = getMACAddress(interfaceName);
        if (!macAddress.empty()) {
            // 格式化MAC地址为 xx:xx:xx:xx:xx:xx
            std::ostringstream formattedMAC;
            std::string delimiter = ":";
            std::string::size_type pos = 0;
            while (pos != std::string::npos) {
                formattedMAC << macAddress.substr(pos, 2) << delimiter;
                pos += 2;
            }
            formattedMAC.str().pop_back(); // 去除最后一个冒号

            std::cout << "接口名: " << interfaceName << ", MAC地址: " << formattedMAC.str() << "\n";
        }
    }

    return 0;
}

上述C++代码通过解析 /sys/class/net 目录下的接口信息来获取所有状态为"up"的网络接口名称,然后逐个获取对应接口的MAC地址,并将其格式化为 xx:xx:xx:xx:xx:xx 的形式进行输出。

请注意,获取MAC地址需要root权限,因此在运行代码时可能需要使用sudo权限。另外,不同的Linux发行版和内核版本可能会稍有差异,您可能需要根据您的具体环境进行适当的调整。