一 代码
<code>#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
", dest_mac[0], dest_mac[1], dest_mac[2], dest_mac[3], dest_mac[4], dest_mac[5]);
return 0;
}</code>
二 运行
<code>[root@localhost test]# g++ test.cpp -o test [root@localhost test]# ./test mac addr:08:00:27:60:7b:7f</code>
三 说明
首先创建一个链路层的原始套接字,然后把网卡名字复制给ifr.ifr_name,接着调用ioctl函数获取SIOCGIFHWADDR指定的信息,即网卡的MAC地址。因为这里创建的套接字是链路层套接字,所以通过SIOCGIFHWADDR获得的地址是MAC地址。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!