[源码实例] c/c++获取网卡mac地址
清泛原创
代码如下:
#include "stdafx.h"
#include <afx.h>
#include < nb30.h >
#pragma comment(lib,"netapi32.lib")
typedef struct _ASTAT_
{
ADAPTER_STATUS adapt;
NAME_BUFFER NameBuff [30];
}ASTAT, * PASTAT;
ASTAT Adapter;
void getmac_one (int lana_num,char *pMicID)
{
NCB ncb;
UCHAR uRetCode;
memset( &ncb, 0, sizeof(ncb) );
ncb.ncb_command = NCBRESET;
ncb.ncb_lana_num = lana_num; // 指定网卡号
// 首先对选定的网卡发送一个NCBRESET命令,以便进行初始化
uRetCode = Netbios( &ncb );
memset( &ncb, 0, sizeof(ncb) );
ncb.ncb_command = NCBASTAT;
ncb.ncb_lana_num = lana_num; // 指定网卡号
strcpy( (char *)ncb.ncb_callname,
"* " );
ncb.ncb_buffer = (unsigned char *) &Adapter;
// 指定返回的信息存放的变量
ncb.ncb_length = sizeof(Adapter);
// 接着,可以发送NCBASTAT命令以获取网卡的信息
uRetCode = Netbios( &ncb );
if ( uRetCode == 0 )
{
// 把网卡MAC地址格式化成常用的16进制形式,如0010-A4E4-5802
sprintf(pMicID,"%02x-%02x-%02x-%02x-%02x-%02x",
Adapter.adapt.adapter_address[0],
Adapter.adapt.adapter_address[1],
Adapter.adapt.adapter_address[2],
Adapter.adapt.adapter_address[3],
Adapter.adapt.adapter_address[4],
Adapter.adapt.adapter_address[5]);
}
}
void ShowAllMac()
{
NCB ncb;
UCHAR uRetCode;
LANA_ENUM lana_enum;
memset( &ncb, 0, sizeof(ncb) );
ncb.ncb_command = NCBENUM;
ncb.ncb_buffer = (unsigned char *) &lana_enum;
ncb.ncb_length = sizeof(lana_enum);
//向网卡发送NCBENUM命令,以获取当前机器的网卡信息,如有多少个网卡、每张网卡的编号等
uRetCode = Netbios( &ncb );
if( uRetCode == 0 )
{
for ( int i=0; i<lana_enum.length; ++i)
{
char szBuf[MAX_PATH] = {0};
getmac_one( lana_enum.lana[i], szBuf );
printf("%s\n", szBuf);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
ShowAllMac();
return 0;
}
运行结果(所有的网卡mac地址,包括虚拟机的):
上一篇:cpuid汇编指令
下一篇:AfxIsValidAddress 测试内存地址