且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取机器的MAC地址-好的解决方案?

更新时间:2023-01-15 10:29:19

一种常见的方法是使用UUID中的位,但这并不完全可靠.例如,即使在没有网络适配器的计算机上,它也会返回一个值.

One common method is using bits from a UUID, but this isn't entirely dependable. For example, it'll return a value even on a machine that doesn't have a network adapter.

幸运的是,有一种方法可以在任何合理的Windows最新版本上可靠地工作. MSDN表示,它只能追溯到Windows 2000,但如果有内存可用,它也可以在NT 4上运行,从SP 5开始,以防万一有人还在使用NT 4.

Fortunately, there is a way that works dependably on any reasonably recent version of Windows. MSDN says it only goes back to Windows 2000, but if memory serves, it also works on NT 4, starting around SP 5, in case anybody's still using NT 4.

#include <windows.h>
#include <iphlpapi.h>
#include <stdio.h>

int main() {         
    IP_ADAPTER_INFO *info = NULL, *pos;
    DWORD size = 0;

    GetAdaptersInfo(info, &size);

    info = (IP_ADAPTER_INFO *)malloc(size);

    GetAdaptersInfo(info, &size);

    for (pos=info; pos!=NULL; pos=pos->Next) {
        printf("\n%s\n\t", pos->Description);
        printf("%2.2x", pos->Address[0]);
        for (int i=1; i<pos->AddressLength; i++)
            printf(":%2.2x", pos->Address[i]);
    }

    free(info);
    return 0;
}

请原谅古老的C代码...

Please forgive the ancient C code...