所有接口的C/C++ Linux MAC地址

8

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

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?
我可以直接使用它的HW地址来获取其HW地址。
  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等),我也想获取它们。感谢您的帮助。

4个回答

10

您应该停止使用net-tools和过时的ioctl接口,开始使用现代的Netlink/sysfs接口。 您有至少五种选择:

  • 编写自己的Netlink交互代码
  • 编写自己的NL代码,同时利用libmnl(-> 查看示例中的rtnl-link-dump)
  • 或者利用类似libnl3的独立库
  • 解析ip -o link的文本输出(-o是为了获得用于文本解析的输出,与ifconfig不同)
  • 或者使用sysfs并查看/sys/class/net/eth0/address

1

谢谢,但我不确定我理解你的意思。在你的代码示例中,所有内容都是关于请求名为argv [1]的接口参数 - 例如,可以像我第二个代码片段中一样是eth0。这很好。但我需要列出所有接口。按照您建议的“特定”部分跳过,会留下什么?我需要获取一些接口列表,然后再请求详细信息(MAC),这正确吗?就我所理解的而言,这就是通过调用SIOCGIFCONF来完成的。但是eth0不在列表中。 - user1173626
这样如何将两个答案结合起来:解析ifconfig结果仅获取名称(我认为这应该是相当平台无关的),并使用此方法查找您找到的每个名称的MAC地址。 - Scott Hunter
或者获取ifconfig的源代码,看看它是如何找到这些名称的。 - Scott Hunter

0

也许不是那么优雅,但你可以从 ifconfig 中捕获和解析结果,因为它看起来正是你想要的。


谢谢,那总是一个解决方案,但我宁愿使用一些 C 解决方案,解析 ifconfig 的结果可能会有问题,格式在不同的 Linux 版本中可能会有所不同等。 - user1173626

0
jørgensen's answer 启发,下面的 C++17 代码使用 Netlink 获取每个接口的 MAC 地址和名称。这是 this gist 的修改版本,它帮助我克服了对使用 Netlink 的羞怯感。实际上,它一开始看起来并不像那么复杂。
#include <linux/rtnetlink.h>
#include <net/if_arp.h>
#include <unistd.h>

#include <cstddef>
#include <cstring>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

using std::byte;
using std::string;
using std::vector;

struct RtReq {
    nlmsghdr header;
    ifinfomsg msg;
};

class fd_wrapper
{
  public:
    fd_wrapper( int const fd_arg ) : fd_( fd_arg ) {}
    ~fd_wrapper() { close( fd_ ); }
    int fd() const noexcept { return fd_; }

  private:
    int fd_;
};

void print_all_macs()
{
    fd_wrapper fd = ( []() -> fd_wrapper {
        RtReq req = ( []() {
            RtReq req;
            memset( &req, 0, sizeof( req ) );
            req.header.nlmsg_len = NLMSG_LENGTH( sizeof( struct ifinfomsg ) );
            req.header.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT;
            req.header.nlmsg_type = RTM_GETLINK;
            req.header.nlmsg_seq = 1; // We're only sending one message
            req.msg.ifi_family = AF_UNSPEC;
            req.msg.ifi_change = 0xffffffff;
            return std::move( req );
        } )();

        sockaddr_nl sa;
        memset( &sa, 0, sizeof( sa ) );
        sa.nl_family = AF_NETLINK;
        iovec iov = {&req, req.header.nlmsg_len};
        msghdr msg = {&sa, sizeof( sa ), &iov, 1, nullptr, 0, 0};

        int fd = socket( AF_NETLINK, SOCK_RAW, NETLINK_ROUTE );

        sendmsg( fd, &msg, 0 );

        return fd_wrapper( fd );
    } )();

    enum class Result { not_done, done };

    auto read_message = []( fd_wrapper const& fd ) -> Result {
        char buf[16 * 1024];
        iovec iov = {buf, sizeof( buf )};
        sockaddr_nl sa;
        msghdr msg = {&sa, sizeof( sa ), &iov, 1, nullptr, 0, 0};
        int len = recvmsg( fd.fd(), &msg, 0 );
        for( nlmsghdr* nh = (nlmsghdr*)buf; NLMSG_OK( nh, len ); nh = NLMSG_NEXT( nh, len ) ) {
            if( nh->nlmsg_type == NLMSG_DONE ) {
                return Result::done;
            }

            if( nh->nlmsg_type != RTM_BASE )
                continue;

            ifinfomsg* msg = (ifinfomsg*)NLMSG_DATA( nh );
            if( msg->ifi_type != ARPHRD_ETHER )
                continue;

            rtattr* rta = IFLA_RTA( msg );
            int alen = nh->nlmsg_len - NLMSG_LENGTH( sizeof( *msg ) );

            string name;
            vector<byte> addr;

            for( ; RTA_OK( rta, alen ); rta = RTA_NEXT( rta, alen ) ) {
                if( rta->rta_type == IFLA_ADDRESS ) {
                    auto const p = reinterpret_cast<byte const*>( RTA_DATA( rta ) );
                    addr.insert( addr.begin(), p, p + 6 );
                }

                if( rta->rta_type == IFLA_IFNAME ) {
                    name = string{(char*)RTA_DATA( rta )};
                }
            }

            auto const c = reinterpret_cast<uint8_t const*>( addr.data() );
            printf( "%02x:%02x:%02x:%02x:%02x:%02x %s\n", c[0], c[1], c[2], c[3], c[4], c[5],
                    name.c_str() );
        }
    };

    Result result;
    while( ( result = read_message( fd ) ) == Result::not_done )
        ;
}

int main( int /*argc*/, char** /*argv*/ )
{
    print_all_macs();
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接