获取方法如下:
#include#include #include #include #include #include #include #include #include #include #include #include #include void get_mac_name(char *name, char *dev_name) { struct ifreq ifreq; int sock; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); goto __finish; } strcpy(ifreq.ifr_name, dev_name); if (ioctl(sock, SIOCGIFHWADDR, &ifreq) < 0) { perror("ioctl"); goto __finish; } printf("%02x:%02x:%02x:%02x:%02x:%02x\n", (unsigned char)ifreq.ifr_hwaddr.sa_data[0], (unsigned char)ifreq.ifr_hwaddr.sa_data[1], (unsigned char)ifreq.ifr_hwaddr.sa_data[2], (unsigned char)ifreq.ifr_hwaddr.sa_data[3], (unsigned char)ifreq.ifr_hwaddr.sa_data[4], (unsigned char)ifreq.ifr_hwaddr.sa_data[5]); char mac1[32], mac4[32], mac5[32], mac6[32]; sprintf(mac1, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[0]); sprintf(mac4, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[3]); sprintf(mac5, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[4]); sprintf(mac6, "%02x", (unsigned char)ifreq.ifr_hwaddr.sa_data[5]); sprintf(name, "%s%s%s%c", mac4, mac5, mac6, mac1[0]); __finish: if (strlen(name) != 7) { sprintf(name, "%s", "0000001"); printf("mac name len is error,len = %d, mac name is %s default mac_name:%s\n", (int)strlen(name), name, "0000001"); } }