Closed. This question needs to be more focused。它当前不接受答案。












想改善这个问题吗?更新问题,使其仅关注editing this post的一个问题。

6年前关闭。



Improve this question




我尝试使用ioctlHDIO_GET_IDENTITY来确定硬盘的序列号,但是它需要root特权。

请帮助我在c中编写一个程序来获取设备的序列号(hdd,cpu,mb)或mac地址,该序列号不需要root权限。

最佳答案

为什么不使用MAC地址作为唯一的计算机ID。这是获取接口(interface)之一的MAC地址的代码。下面的代码基本上读取所有可用接口(interface)的名称,然后遍历它们以获取除回送接口(interface)之外的第一个可用接口(interface)的MAC地址。

int main()
{
struct ifreq ifr;
struct ifconf ifc;
char buf[1024];
int success = 0;

int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) { /* handle error*/ };

ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }

struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));

for (; it != end; ++it) {
    strcpy(ifr.ifr_name, it->ifr_name);
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
        if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
            if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
                success = 1;
                break;
            }
        }
    }
    else { /* handle error */ }
}

unsigned char mac_address[6];

if (success) memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6);
}

关于c++ - Linux程序,用于非root用户的设备的序列号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21211920/

10-13 09:54