VC++获取本机MAC地址

作者:袖梨 2022-06-25
 代码如下 复制代码

bool GetMAC(LPTSTR lpszMAC)
{
 ASSERT(lpszMAC);
 char mac[200]={0};
 NCB ncb;
 typedef struct _ASTAT_
 {
  ADAPTER_STATUS   adapt;
  NAME_BUFFER   NameBuff   [30];
 }ASTAT,*PASTAT;

 ASTAT Adapter;

 typedef struct _LANA_ENUM
 {
  UCHAR   length;
  UCHAR   lana[MAX_LANA];
 }LANA_ENUM;

 LANA_ENUM lana_enum;
 UCHAR uRetCode;
 memset(&ncb, 0, sizeof(ncb));
 memset(&lana_enum, 0, sizeof(lana_enum));   
 ncb.ncb_command = NCBENUM;
 ncb.ncb_buffer = (unsigned char *)&lana_enum;
 ncb.ncb_length = sizeof(LANA_ENUM);
 uRetCode = Netbios(&ncb);

 if(uRetCode != NRC_GOODRET)    
  return false;    

 for(int lana=0; lana  {
  ncb.ncb_command = NCBRESET;
  ncb.ncb_lana_num = lana_enum.lana[lana];
  uRetCode = Netbios(&ncb);
  if(uRetCode == NRC_GOODRET)
   break;
 }

 if(uRetCode != NRC_GOODRET)
  return false;

 memset(&ncb, 0, sizeof(ncb));
 ncb.ncb_command = NCBASTAT;
 ncb.ncb_lana_num = lana_enum.lana[0];
 strcpy((char*)ncb.ncb_callname, "*");
 ncb.ncb_buffer = (unsigned char *)&Adapter;
 ncb.ncb_length = sizeof(Adapter);
 uRetCode = Netbios(&ncb);

 if(uRetCode != NRC_GOODRET)
  return false;

 sprintf(mac,"%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]);
 strcpy(lpszMAC,mac);
 log_printf("Get local mac address!");
 return true;
}

头文件中需要包含的文件和链接库

 代码如下 复制代码

#include "nb30.h"
#pragma comment(lib, "netapi32")

相关文章

精彩推荐