通过设备名获取网卡Mac地址
2021-08-30
281
0
在Windows开发开发工程中,有时不仅需要获取网卡的原来MAC地址,也需要获了取软件修改后的MAC地址。
1.首先打开注册表:
计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards
枚举下面有多少个子项,获取每个子项ServiceName的键值
2.根据设备的服务名生成设备的实例名,然后打开设备,发送IOCTL_NDIS_QUERY_GLOBAL_STATS,输入参数为OID_802_3_CURRENT_ADDRESS和OID_802_3_PERMANENT_ADDRESS的参数,输出即为当前网卡的地址。
#include "stdafx.h"
#include<windows.h>
#include "Iphlpapi.h"
#pragma comment(lib, "IpHlpApi.lib")
#include <TCHAR.H>
#include <winioctl.h>
#include <strsafe.h>
#include <setupapi.h>
#include <ntddndis.h>
#include <algorithm>
int main()
{
// 网卡标识,可以在注册表下对应位置找到,本例:
//HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\3
HANDLE hDev = CreateFile(L"//./{FF78525B-F695-4AB5-AEF7-E257A11C185C}",
GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
if (INVALID_HANDLE_VALUE == hDev)
{
printf("CreateFile err :%d", GetLastError());
return 0;
}
int inBuf;
BYTE outBuf[256] = { 0 };
DWORD BytesReturned;
//原生的网卡地址
inBuf = OID_802_3_PERMANENT_ADDRESS;
if (DeviceIoControl(hDev, IOCTL_NDIS_QUERY_GLOBAL_STATS, (LPVOID)&inBuf, 4, outBuf, 256, &BytesReturned, NULL))
{
char buff[512] = { 0 };
sprintf_s(buff,512,"Real Mac Address: %02X-%02X-%02X-%02X-%02X-%02X", outBuf[0], outBuf[1], outBuf[2], outBuf[3], outBuf[4], outBuf[5]);
printf("%s", buff);
}
//可能修改后的网卡地址
inBuf = OID_802_3_CURRENT_ADDRESS;
if (DeviceIoControl(hDev, IOCTL_NDIS_QUERY_GLOBAL_STATS, (LPVOID)&inBuf, 4, outBuf, 256, &BytesReturned, NULL))
{
char buff[512] = { 0 };
sprintf_s(buff, 512, "Current Mac Address: %02X-%02X-%02X-%02X-%02X-%02X", outBuf[0], outBuf[1], outBuf[2], outBuf[3], outBuf[4], outBuf[5]);
printf("%s", buff);
}
CloseHandle(hDevice);
}
3.假如本机中有多块物理网卡,可枚举注册表,生成打开设备获取。
注意:同一块网卡会因网卡驱动的安装,卸载,重复安装而变化。