Linux下获取CPUID、硬盘序列号与MAC地址
tderr, "open hard disk device failed.n");
return -1; } if (ioctl (fd, HDIO_GET_IDENTITY, &hid) < 0) { fprintf (stderr, "ioctl error.n"); return -1; } close (fd); snprintf (id, max, "%s", hid.serial_no); fprintf (stdout, "get hard disk serial number: %sn", id); return 0; } 获取MAC地址 通过创建一个socket,然后bind特定的IP地址,就可以通过ioctl得到这个套按地绑定的网络接口名称.然后再通过网络接口名称,得到MAC地址. 如果ioctl的第二个参数为SIOCGIFNAME, 则获得指定网络接口的名称;如果ioctl的第二个参数为SIOCGIFHWADDR,则获得指定网络接口的MAC地址 ioctl的第三个参数为struct ifreq ,在linux/if.h头文件里,struct ifreq声明如下: struct ifreq { #define IFHWADDRLEN 6 union { char ifrn_name[IFNAMSIZ]; / if name, e.g. "en0" */ } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; int ifru_ivalue; int ifru_mtu; struct ifmap ifru_map; char ifru_slave[IFNAMSIZ]; /* Just fits the size */ char ifru_newname[IFNAMSIZ]; void * ifru_data; struct if_settings ifru_settings; } ifr_ifru; }
,其中,ifrn_name为网络接口的名称,ifr_ifru.ifru_hwaddr为网络接口的MAC地址. #ifndef MAX_IFINDEX # define MAX_IFINDEX 8 #endif static int getmacaddr (const char *ip, char *id, size_t max) { int i, sockfd; struct sockaddr_in *loc; struct ifreq req[1]; sockfd = socket (AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { fprintf (stderr, "Unable to create socket.n"); return -1; } for (i = 0; i <= MAX_IFINDEX; i) { req->ifr_ifindex = i; if (ioctl (sockfd, SIOCGIFNAME, req) < 0) { fprintf (stderr, "ioctl error: %sn", strerror (errno)); continue; } if (ioctl (sockfd, SIOCGIFADDR, req) < 0) { fprintf (stderr, "ioctl interface index [%d] error: %sn", i, strerror (errno)); continue; } loc = (struct sockaddr_in *) (&(req->ifr_ifru.ifru_addr)); if (loc->sin_addr.s_addr == inet_addr (ip)) { fprintf (stderr, "%s bind at %s.n", ip, req->ifr_name); break; } } if (i > MAX_IFINDEX) { fprintf (stderr, "input IP error.n"); close (sockfd); return -1; } if (ioctl (sockfd, SIOCGIFHWADDR, req) < 0) { fprintf (stderr, "ioctl error: %sn", strerror (errno)); close (sockfd); return -1; } close (sockfd); snprintf (id, max, "XXXXXX", req->ifr_hwaddr.sa_data[0] & 0xff, req->ifr_hwaddr.sa_data[1] & 0xff, req->ifr_hwaddr.sa_data[2] & 0xff, req->ifr_hwaddr.sa_data[3] & 0xff, req->ifr_hwaddr.sa_data[4] & 0xff, req->ifr_hwaddr.sa_data[5] & 0xff); fprin |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |