由于软件的特殊性,需要将机器码写到软件中用于鉴权。所以这几天找了一些linux下获取CPUID和MAC地址的代码,均测试通过。下面是代码:
linux获取CPUID
- #include <stdio.h>
- #include <string.h>
- int main(int argc, char* argv[])
- {
- unsigned long s1,s2,s3,s4;
- char string[128];
- char szCpuId[1024];
- char p1[128], p2[128];
- unsigned int eax = 0;
- unsigned int ebx,ecx,edx;
- asm volatile
- ( "cpuid"
- : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
- : "0"(0)
- );
- snprintf(szCpuId, 5, "%s", (char *)&ebx);
- snprintf(szCpuId+4, 5, "%s", (char *)&edx);
- snprintf(szCpuId+8, 5, "%s", (char *)&ecx);
- asm volatile
- ( "movl $0x01 , %%eax ; \n\t"
- "xorl %%edx , %%edx ;\n\t"
- "cpuid ;\n\t"
- "movl %%edx ,%0 ;\n\t"
- "movl %%eax ,%1 ; \n\t"
- :"=m"(s1),"=m"(s2)
- );
- sprintf((char *)p1, "-%08X\n%08X-", s1, s2);
- snprintf(szCpuId+12, 20, "%s", (char *)p1);
- asm volatile
- ( "movl $0x03,%%eax ;\n\t"
- "xorl %%ecx,%%ecx ;\n\t"
- "xorl %%edx,%%edx ;\n\t"
- "cpuid ;\n\t"
- "movl %%edx,%0 ;\n\t"
- "movl %%ecx,%1 ;\n\t"
- :"=m"(s3),"=m"(s4)
- );
- sprintf((char *)p2, "%08X-%08X\n", s3, s4);
- snprintf(szCpuId+31, 19, "%s", (char *)p2);
- printf((char*)szCpuId);
- return 0;
- }
获取MAC地址:
- #include <sys/ioctl.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <stdio.h>
- #include <string.h>
- #include <unistd.h>
- #include <net/if.h>
- int get_mac(char* mac)
- {
- struct ifreq tmp;
- int sock_mac;
- char mac_addr[30];
- sock_mac = socket(AF_INET, SOCK_STREAM, 0);
- if( sock_mac == -1){
- perror("create socket fail\n");
- return -1;
- }
- memset(&tmp,0,sizeof(tmp));
- strncpy(tmp.ifr_name,"eth0",sizeof(tmp.ifr_name)-1 );
- if( (ioctl( sock_mac, SIOCGIFHWADDR, &tmp)) < 0 ){
- printf("mac ioctl error\n");
- return -1;
- }
- sprintf(mac_addr, "%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]
- );
- printf("local mac:%s\n", mac_addr);
- close(sock_mac);
- memcpy(mac,mac_addr,strlen(mac_addr));
- return 1;
- }
- int main()
- {
- char buff[512];
- memset(buff, 0, 512);
- get_mac(buff);
- fprintf(stderr, "%s\n", buff);
- }
具体原理网上有很多,代码也有很多,我只是找了几个可用的代码备份,以便以后使用
阅读(8679) | 评论(0) | 转发(0) |