C / C ++ Linux MAC Address of All Interfaces

I use the following code to extract all the MAC addresses for the 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 { ... } } 

By running a simple ifconfig shell command, I can see lo, eth0 and wlan0. I would like to get the MAC addresses for eth0 and wlan0 using my C / C ++ code. But only wlan0 is returned - eth0 is missing (I got ifr_names lo, lo, wlan0). Probably because eth0 is inactive (Ethernet cable not connected, cable is returning). Can I somehow modify this ioctl (SIOCGIFCONF) command to retrieve eth0, even if it is disabled?

I can get his HW address 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)) { ... } 

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

+7
source share
3 answers

You should stop using network tools and the ioctl archaic interface and start using modern Netlink / sysfs interfaces. You have at least 5 possibilities:

  • write your own Netlink communication code
  • your own NL code combined with using libmnl (-> see rtnl-link-dump in Examples
  • or use standalone libraries like libnl3
  • parsing text output ip -o link (-o - get output intended for parsing text, unlike ifconfig)
  • or use sysfs and just look at /sys/class/net/eth0/address
+9
source

You can find the solution here: Get mac address based on specific interface

You can simply skip a specific part of the interface.

+1
source

Maybe not so elegant, but you can capture and analyze the results of ifconfig, as it looks like it has only what you are looking for.

0
source

All Articles