美文网首页
获取 linux 网卡MAC地址(包含编程方法)

获取 linux 网卡MAC地址(包含编程方法)

作者: 该用户已趴倒 | 来源:发表于2020-02-19 16:24 被阅读0次

网卡在计算机专业词汇里面被叫做 network interface 如果检索资料可以用这个词汇

常用的几种办法

  1. ip link show
  2. cat /sys/class/net/<interface name>/address
  3. 使用 getifaddrs 接口编程获取
#include <stdio.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <linux/if_packet.h>

int main(int argc, char *argv[])
{
    struct ifaddrs* ifap;
    if (getifaddrs(&ifap)) {
        perror("get ifaddr error:");
        return -1;
    }

    struct ifaddrs* pif;
    // use 'man 7 packet' to see the struct sockaddr_ll
    const unsigned char* mac;
    for (pif = ifap; pif; pif = pif->ifa_next) {
        if (pif->ifa_addr->sa_family != AF_PACKET) {
            continue;
        }
        mac = (const unsigned char*)((struct sockaddr_ll*)pif->ifa_addr)->sll_addr;
        printf("%-16s%02x:%02x:%02x:%02x:%02x:%02x\n", pif->ifa_name, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }

    freeifaddrs(ifap);
    return 0;
}

这段程序在我的电脑上输出为:

lo                    00:00:00:00:00:00
enp14s0       3c:07:71:5f:66:da
wlp7s0          0c:84:dc:e9:d3:a1

确定当前使用的是哪个网卡需要其他手段。目前我还没有查到相关资料。

相关文章

网友评论

      本文标题:获取 linux 网卡MAC地址(包含编程方法)

      本文链接:https://www.haomeiwen.com/subject/clmafhtx.html