linux系统C++怎么实现获取物理网卡mac地址
时间: 2023-04-04 13:02:35 浏览: 330
可以使用ioctl函数和SIOCGIFHWADDR命令来获取物理网卡的MAC地址。具体实现可以参考以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int fd;
struct ifreq ifr;
unsigned char *mac;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if(fd < 0)
{
perror("socket");
exit(1);
}
strcpy(ifr.ifr_name, "eth0");
if(ioctl(fd, SIOCGIFHWADDR, &ifr) < 0)
{
perror("ioctl");
exit(1);
}
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
printf("MAC Address: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
close(fd);
return 0;
}
阅读全文