本文介绍了所有接口的C/C ++ Linux MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来检索当前计算机的所有MAC地址:

I am using the following code to retrieve all MAC addresses for current computer:

ifreq ifr;
ifconf ifc;
char buf[1024];

int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) { ... };

ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { ... }

ifreq *it = ifc.ifc_req;
const ifreq* const end = it + (ifc.ifc_len / sizeof(ifreq));

for (; it != end; ++it) {
    strcpy(ifr.ifr_name, it->ifr_name);
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
        if (!(ifr.ifr_flags & IFF_LOOPBACK)) {
            if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
               unsigned char mac_address[6];
               memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
               ...
            }
        }
    }
    else { ... }
}

通过运行简单的shell命令ifconfig,我可以看到lo,eth0和wlan0.我想通过我的C/C ++代码检索eth0和wlan0的MAC地址.但是只返回wlan0-缺少eth0(我得到了ifr_names lo,lo,wlan0).可能是因为eth0未激活(未连接以太网电缆,但已返回电缆).我可以以某种方式更改该ioctl(SIOCGIFCONF)命令来检索eth0吗,即使它已关闭"?

By running simple shell command ifconfig i can see lo, eth0 and wlan0. I would like to retrieve MAC addresses for eth0 and wlan0 by my C/C++ code. But only wlan0 is returned - eth0 is missing (I got ifr_names lo, lo, wlan0). Probably because eth0 is not active (no ethernet cable connected, with cable it is returned). Can I somehow alter that ioctl(SIOCGIFCONF) command to retrieve eth0 too even if it is "turned off"?

我可以直接使用它的硬件地址

I can get its HW address by using directly

  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, "eth0");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) { ... }

但是如果名称不是eth0而是其他名称(eth1,em0,...)怎么办?我想得到所有这些.感谢您的帮助.

but what if the name would be not eth0 but something else (eth1, em0,...)? I would like to get all of them. Thanks for help.

推荐答案

您应该停止使用net-tools和过时的ioctl接口,并开始使用现代的Netlink/sysfs接口.您有不少于5种可能性:

You should stop using net-tools and the archaic ioctl interface, and start on using the modern Netlink/sysfs interfaces. You have no less than 5 possibilities:

  • 编写您自己的Netlink接口代码
  • 您自己的NL代码,结合使用 libmnl (->参见示例
  • 或利用诸如 libnl3
  • 之类的自治库
  • 解析ip -o link的文本输出(-o是获取用于文本分析的输出,与ifconfig不同)
  • 或使用sysfs并查看/sys/class/net/eth0/address
  • write your own Netlink-interfacing code
  • your own NL code, in combination utilizing libmnl (-> see rtnl-link-dump in Examples
  • or utilize autonomous libs like libnl3
  • parse text output of ip -o link (-o is to get output meant for text parsing, unlike ifconfig)
  • or use sysfs and just look at /sys/class/net/eth0/address

这篇关于所有接口的C/C ++ Linux MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 20:06