VC实现获取本机MAC地址的方法
本文实例采用vc6.0运行环境,通过实例实现获得MAC地址的功能。
完整的实例代码如下:
#include"stdafx.h" #include<stdio.h> #include<stdlib.h> #include<httpext.h> #include<windef.h> #include<Nb30.h> intgetMAC(char*mac) { NCBncb; typedefstruct_ASTAT_ { ADAPTER_STATUSadapt; NAME_BUFFERNameBuff[30]; }ASTAT,*PASTAT; ASTATAdapter; typedefstruct_LANA_ENUM {//le UCHARlength; UCHARlana[MAX_LANA]; }LANA_ENUM; LANA_ENUMlana_enum; UCHARuRetCode; memset(&ncb,0,sizeof(ncb)); memset(&lana_enum,0,sizeof(lana_enum)); ncb.ncb_command=NCBENUM; ncb.ncb_buffer=(unsignedchar*)&lana_enum; ncb.ncb_length=sizeof(LANA_ENUM); uRetCode=Netbios(&ncb); if(uRetCode!=NRC_GOODRET) returnuRetCode; for(intlana=0;lana<lana_enum.length;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) returnuRetCode; 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=(unsignedchar*)&Adapter; ncb.ncb_length=sizeof(Adapter); uRetCode=Netbios(&ncb); if(uRetCode!=NRC_GOODRET) returnuRetCode; 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] ); return0; } intmain(intargc,char*argv[]) { charmac[200]; getMAC(mac); printf("mac:%s\n",mac); return0; }
另外还需要注意:必须在project->Setting里添加库文件“netapi32.lib”。