c++ 获取机器码

看到网上代码代码都没什么好的,自己备用一个

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <Windows.h>
#include <iphlpapi.h> // 包含这个头文件以获取 PIP_ADAPTER_INFO
#include <intrin.h> // 包含这个头文件以使用 __cpuid

#pragma comment(lib, "IPHLPAPI.lib") // 链接到IPHLPAPI.lib库

// Function to get CPU serial number
std::string GetCPUSerialNumber() {
    std::string result;
    int cpuInfo[4] = { -1 };
    __cpuid(cpuInfo, 1);
    unsigned int lowPart = cpuInfo[3];
    unsigned int highPart = cpuInfo[0];
    std::stringstream stream;
    stream << std::hex << highPart << std::hex << lowPart;
    result = stream.str();
    return result;
}

// Function to get hard disk serial number
std::string GetHardDiskSerialNumber() {
    std::string result;
    DWORD dwVolumeSerialNumber;
    GetVolumeInformationA("C:\\", NULL, 0, &dwVolumeSerialNumber, NULL, NULL, NULL, 0);
    std::stringstream stream;
    stream << std::hex << std::setw(8) << std::setfill('0') << dwVolumeSerialNumber;
    result = stream.str();
    return result;
}

// Function to get MAC address of the first network adapter
std::string GetMACAddress() {
    std::string result;
    PIP_ADAPTER_INFO pAdapterInfo;
    ULONG ulOutBufLen = sizeof(PIP_ADAPTER_INFO);
    pAdapterInfo = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
    if (pAdapterInfo != NULL) {
        if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
            free(pAdapterInfo);
            pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
        }
        if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == NO_ERROR) {
            result = pAdapterInfo->Address[0];
        }
        free(pAdapterInfo);
    }
    return result;
}

// Function to generate unique machine ID
std::string GenerateMachineID() {
    std::string cpuSerial = GetCPUSerialNumber();
    std::string diskSerial = GetHardDiskSerialNumber();
    std::string macAddress = GetMACAddress();
    std::string machineID = cpuSerial + diskSerial + macAddress;
    return machineID;
}

int main() {
    std::string machineID = GenerateMachineID();
    std::cout << "Machine ID: " << machineID << std::endl;
    return 0;
}

在这里插入图片描述

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值