获取linux下CPU、网卡、硬盘ID

2019-07-13 03:09发布

获取linux下CPU、网卡、硬盘ID #include #include #include #include #include #include #include #include #include #include #include #include static char* get_cpu(char *szCpuId){ unsigned long s1,s2,s3,s4; char string[128]; char p1[128], p2[128]; unsigned int eax = 0; unsigned int ebx,ecx,edx; asm volatile ("movl $0x01 , %%eax ; " "xorl %%edx , %%edx ; " "cpuid ; " "movl %%edx ,%0 ; " "movl %%eax ,%1 ; " :"=m"(s1),"=m"(s2) ); sprintf((char *)p1, "%08X%08X", htonl(s2), htonl(s1)); sprintf(szCpuId, "%c%c %c%c %c%c %c%c %c%c %c%c %c%c %c%c", p1[0],p1[1],p1[2],p1[3],p1[4],p1[5],p1[6],p1[7], p1[8],p1[9],p1[10],p1[11],p1[12],p1[13],p1[14],p1[15]); } int get_mac(char* mac, char* eth0) { struct ifreq tmp; int sock_mac; char mac_addr[30]; sock_mac = socket(AF_INET, SOCK_STREAM, 0); if( sock_mac == -1){ sprintf(mac, "create socket fail "); return -1; } memset(&tmp, 0, sizeof(tmp)); strncpy(tmp.ifr_name, eth0, strlen(eth0)-2); //strncpy(tmp.ifr_name, "eno16777736", sizeof(tmp.ifr_name)-1); if((ioctl( sock_mac, SIOCGIFHWADDR, &tmp)) < 0 ){ sprintf(mac, "mac ioctl error "); return -1; } sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", (unsigned char)tmp.ifr_hwaddr.sa_data[0], (unsigned char)tmp.ifr_hwaddr.sa_data[1], (unsigned char)tmp.ifr_hwaddr.sa_data[2], (unsigned char)tmp.ifr_hwaddr.sa_data[3], (unsigned char)tmp.ifr_hwaddr.sa_data[4], (unsigned char)tmp.ifr_hwaddr.sa_data[5] ); close(sock_mac); return 1; } static int getdiskid(char *diskid){ int fd; struct hd_driveid hid; fd = open("/dev/sda", O_RDONLY); if(fd < 0){ sprintf(diskid, "%s", "open error"); return -1; } if(ioctl(fd, HDIO_GET_IDENTITY, &hid) < 0){ sprintf(diskid, "%s", "ioctl error"); return -1; } close(fd); char tmp[sizeof(hid.serial_no)]; sprintf(tmp,"%s", hid.serial_no); int t = sizeof(hid.serial_no) - sizeof(diskid); strncpy(diskid, tmp+t, sizeof(tmp)); return 0; } int main(int argc, char* argv[]) { char cpuId[50]; get_cpu(cpuId); printf(" CpuID: %s ", cpuId); char macId[50], eth[20]; system("ifconfig | head -n 1 | cut -d ' ' -f1 > temp"); FILE *fp =fopen("temp", "r"); if(fp == NULL) return -1; int t = 0; while(fscanf(fp, "%c", ð[t++])!=EOF); get_mac(macId, eth); printf("MacID: %s ", macId); system("rm -rf temp"); char diskid[50]; getdiskid(diskid); printf("DiskID: %s ", diskid); return 0; } 获取网卡ID,有其他方法,待修改,,,