如何获取本机网卡的物理地址
编号: QA001310
建立日期: 1999年7月9日 最后修改日期: 2005年8月22日
所属类别: C/C++ - 网络与通信
使用的操作系统:Win95
使用的编程工具:VC 5.0
遇到的问题:如何获取本机网卡的物理地址?(qiang pu)
由于NT机中可以同时安装多网卡,在Win9x中也可以装入Microsoft虚拟网卡,给获取完整本机网卡的物理地址带来麻烦。
寻找一块网卡的物理地址可参见SDK中的NetBIOS文档说明,例程片断如下:
#include <windows.h>
#include <wincon.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
typedef struct _ASTAT_
{
ADAPTER_STATUS adapt;
NAME_BUFFER NameBuff [30];
}ASTAT, * PASTAT;
ASTAT Adapter;
void main (void)
{
NCB ncb;
UCHAR uRetCode;
char NetName[50];
memset( &ncb, 0, sizeof(ncb) );
ncb.ncb_command = NCBRESET;
ncb.ncb_lana_num = 0;
uRetCode = Netbios( &ncb );
printf( "The NCBRESET return code is: 0x%x \n", uRetCode );
memset( &ncb, 0, sizeof(ncb) );
ncb.ncb_command = NCBASTAT;
ncb.ncb_lana_num = 0;
strcpy( (LPTSTR)ncb.ncb_callname, "* " );
ncb.ncb_buffer = (unsigned char *) &Adapter;
ncb.ncb_length = sizeof(Adapter);
uRetCode = Netbios( &ncb );
printf( "The NCBASTAT return code is: 0x%x \n", uRetCode );
if ( uRetCode == 0 )
{
printf( "The Ethernet Number is: %02x%02x%02x%02x%02x%02x\n",
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] );
}
}
获取多块网卡的例程片断需要多加一个循环,这时会有多个同样的物理地址出现,出现的原因可能是NetBEUI可能绑定在多个服务上(NT而言),而这些服务可能服务于同一块网卡。可以滤去相同地址取不同地址而得到不同的网卡物理地址(包含虚拟网卡)。例程片断如下:
#include <windows.h>
#include <wincon.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
typedef struct _ASTAT_
{
ADAPTER_STATUS adapt;
NAME_BUFFER NameBuff [30];
}ASTAT, * PASTAT;
ASTAT Adapter;
void main (void)
{
NCB Ncb;
UCHAR uRetCode;
LANA_ENUM lenum;
int i = 0;
memset(&Ncb, 0, sizeof(Ncb));
Ncb.ncb_command = NCBENUM;
Ncb.ncb_buffer = (UCHAR *)&lenum;
Ncb.ncb_length = sizeof(lenum);
uRetCode = Netbios( &Ncb );
printf("The NCBENUM return adapter number is: 0x%x \n", lenum.length);
for(i=0; i < lenum.length ;i++)
{
memset(&Ncb, 0, sizeof(Ncb));
Ncb.ncb_command = NCBRESET;
Ncb.ncb_lana_num = lenum.lana[i];
uRetCode = Netbios( &Ncb );
memset(&Ncb, 0, sizeof(Ncb));
Ncb.ncb_command = NCBASTAT;
Ncb.ncb_lana_num = lenum.lana[i];
strcpy((char *)Ncb.ncb_callname, "* ");
Ncb.ncb_buffer = (unsigned char *) &Adapter;
Ncb.ncb_length = sizeof(Adapter);
uRetCode = Netbios( &Ncb );
if (uRetCode == 0)
{
printf("The Ethernet Number on LANA %d is: %02x-%02x-%02x-%02x-%02x-%02x\n", lenum.lana[i],
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]);
}
}
}
在VC++中编译上面两个程序时,需要在工程中添加Netapi32.lib。