for x in `ls /sys/class/net |grep -v lo`; do cat /sys/class/net/$x/address; done
可以从C程序执行 .
17
扩展@ user175104给出的答案......
std::vector<std::string> GetAllFiles(const std::string& folder, bool recursive = false)
{
// uses opendir, readdir, and struct dirent.
// left as an exercise to the reader, as it isn't the point of this OP and answer.
}
bool ReadFileContents(const std::string& folder, const std::string& fname, std::string& contents)
{
// uses ifstream to read entire contents
// left as an exercise to the reader, as it isn't the point of this OP and answer.
}
std::vector<std::string> GetAllMacAddresses()
{
std::vector<std::string> macs;
std::string address;
// from: https://stackoverflow.com/questions/9034575/c-c-linux-mac-address-of-all-interfaces
// ... just read /sys/class/net/eth0/address
// NOTE: there may be more than one: /sys/class/net/*/address
// (1) so walk /sys/class/net/* to find the names to read the address of.
std::vector<std::string> nets = GetAllFiles("/sys/class/net/", false);
for (auto it = nets.begin(); it != nets.end(); ++it)
{
// we don't care about the local loopback interface
if (0 == strcmp((*it).substr(-3).c_str(), "/lo"))
continue;
address.clear();
if (ReadFileContents(*it, "address", address))
{
if (!address.empty())
{
macs.push_back(address);
}
}
}
return macs;
}
11 回答
您需要迭代计算机上的所有可用接口,并使用
ioctl
和SIOCGIFHWADDR
标志来获取mac地址 . mac地址将以6个八位字节的二进制数组的形式获得 . 您还想跳过环回接口 .比所有这个套接字或shell疯狂更好的只是使用sysfs:
文件
/sys/class/net/eth0/address
将您的mac地址作为简单字符串,您可以使用fopen()
/fscanf()
/fclose()
读取 . 没有比这更容易的了 .如果你想支持除eth0之外的其他网络接口(你可能想要),那么只需在
/sys/class/net/
上使用opendir()
/readdir()
/closedir()
.您想看一下getifaddrs(3)手册页 . 在您可以使用的联机帮助页中的C中有一个示例 . 您想获取类型
AF_LINK
的地址 .我刚刚写了一个并在virtualbox中的gentoo上测试它 .
使用getifaddrs,您可以从家庭
AF_PACKET
获取MAC地址 .为了显示每个接口的MAC地址,您可以这样继续:
假设c代码(c 11)也正常,并且接口已知 .
在Linux上,使用DBus上的“网络管理器”服务 .
还有一个好的shell程序可以调用并抓取结果(在C下使用exec函数):
$ /sbin/ifconfig | grep HWaddr
一种非常便携的方法是解析此命令的输出 .
提供ifconfig可以作为当前用户(通常可以)和awk安装(通常是)运行 . 这将为您提供机器的mac地址 .
这是一个Bash行,它打印除loopback之外的所有可用mac地址:
可以从C程序执行 .
扩展@ user175104给出的答案......