C++获取网卡的MAC地址

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89597410

一 代码

#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/if_ether.h>
#include <bits/ioctls.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#include <errno.h>
#include <string.h> //bzero
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h> //for close
#include <arpa/inet.h>//htons
#include <stdio.h>
#include <stdlib.h>//EXIT_FAILURE

#define IFRNAME   "eno16777736"

unsigned char dest_mac[6] = { 0 };

int main(int argc, char **argv)
{
    int i, datalen;
    int sd;

    struct sockaddr_ll device;
    struct ifreq ifr;  //定义网口的信息请求体

    bzero(&ifr, sizeof(struct ifreq));

    if ((sd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL))) < 0)   // 创建原始套接字
    {
        printf("socket() failed to get socket descriptor for using ioctl()");
        return (EXIT_FAILURE);
    }
    memcpy(ifr.ifr_name, IFRNAME, sizeof(struct ifreq));
    if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0) {                     //发送请求
        printf("ioctl() failed to get source MAC address");
        return (EXIT_FAILURE);
    }
    close(sd);

    memcpy(dest_mac, ifr.ifr_hwaddr.sa_data, 6);
    // 打印MAC地址
    printf("mac addr:%02x:%02x:%02x:%02x:%02x:%02x\n", dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5]);

    return 0;
}

二 运行

[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
mac addr:08:00:27:60:7b:7f

三 说明

首先创建一个链路层的原始套接字,然后把网卡名字复制给ifr.ifr_name,接着调用ioctl函数获取SIOCGIFHWADDR指定的信息,即网卡的MAC地址。因为这里创建的套接字是链路层套接字,所以通过SIOCGIFHWADDR获得的地址是MAC地址。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89597410