在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发行版和内核版本可能会稍有差异,您可能需要根据您的具体环境进行适当的调整。


香港五网CN2网络云服务器链接:www.tsyvps.com

蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。

蓝易云是一家专注于香港及国内数据中心服务的提供商,提供高质量的服务器租用和云计算服务、包括免备案香港服务器、香港CN2、美国服务器、海外高防服务器、国内高防服务器、香港VPS等。致力于为用户提供稳定,快速的网络连接和优质的客户体验。
最后修改:2023 年 07 月 30 日
如果觉得我的文章对你有用,请随意赞赏