// 获取本地mac
std::string getLocalMac()
{
#ifndef _WIN32
int sock_mac;
struct ifreq ifr_mac;
char mac_addr[30];
sock_mac = socket(AF_INET, SOCK_STREAM, 0);
if (sock_mac == -1)
{
perror("create socket falise...mac\n");
return "";
}
memset(&ifr_mac, 0, sizeof(ifr_mac));
strncpy(ifr_mac.ifr_name, "eth0", sizeof(ifr_mac.ifr_name) - 1);
if ((ioctl(sock_mac, SIOCGIFHWADDR, &ifr_mac)) < 0)
{
printf("mac ioctl error\n");
close(sock_mac);
return "";
}
sprintf(mac_addr, "%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[0],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[1],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[2],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[3],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[4],
(unsigned char)ifr_mac.ifr_hwaddr.sa_data[5]
);
close(sock_mac);
return mac_addr;
#else
return "00:00:00:00:00:00";
#endif
}
linux 获取本地mac地址(指定网卡)
最新推荐文章于 2024-08-16 19:06:03 发布