在网络编程中获得网卡的某些信息是必要的,比如网卡名称.MAC地址等.这也是最基本的.所以写了这个小程序并封装成了模块,可以在以后用到的时候直接调用!
//--------------------------------------------------------------------------------------------------------------------------------//
#include <windows.h>
#include <stdio.h>
#include <Iphlpapi.h>
#pragma comment(lib, "Iphlpapi.lib")
typedef struct tagAdapterInfo
{
char szDeviceName[128]; // 名字
char szIPAddrStr[16]; // IP
char szHWAddrStr[18]; // MAC
DWORD dwIndex; // 编号
bool filled;//是否取得了网卡信息
}INFO_ADAPTER, *PINFO_ADAPTER;
//入口参数:指向INFO_ADAPTER结构数组的指针(数组大小依本机网卡数量而定)
//返回值:
//-1函数执行失败非零为本机网卡的数量
int GetLocalAdapterList(PINFO_ADAPTER infoAdapterList)
{
ULONG dwSize=0;
PIP_ADAPTER_INFO pAdapter=NULL; // 定义PIP_ADAPTER_INFO结构存储网卡信息
int nAdapterIndex = 0;
char strTemp[128];
//获得网卡列表信息串长度
DWORD dwRet = GetAdaptersInfo(pAdapter, &dwSize);
if (dwRet != ERROR_BUFFER_OVERFLOW)
{
printf("不能获得网卡信息结构大小!");
return -1;
}
pAdapter = (PIP_ADAPTER_INFO)new(char[dwSize]);
dwRet = GetAdaptersInfo(pAdapter, &dwSize);
if (dwRet != ERROR_SUCCESS)
{
printf("获得网卡信息失败!");
delete pAdapter;
return -1;
}
//枚举获得获得网卡信息
while (pAdapter)
{
// 网卡名字
lstrcpy(strTemp, "\\Device\\NPF_");
lstrcat(strTemp,pAdapter->AdapterName); //构造网卡名字
lstrcpy(infoAdapterList[nAdapterIndex].szDeviceName,strTemp);
// IP
lstrcpy(infoAdapterList[nAdapterIndex].szIPAddrStr,pAdapter->IpAddressList.IpAddress.String);
// MAC
sprintf(infoAdapterList[nAdapterIndex].szHWAddrStr, "%02x%02x%02x%02x%02x%02x", \
pAdapter->Address[0],pAdapter->Address[1],pAdapter->Address[2], \
pAdapter->Address[3],pAdapter->Address[4],pAdapter->Address[5]);
// 网卡编号
infoAdapterList[nAdapterIndex].dwIndex = pAdapter->Index;
pAdapter = pAdapter->Next;
nAdapterIndex ++;
}
delete pAdapter;
return nAdapterIndex;
}
void main()
{
INFO_ADAPTER infoAdapterList[10];
int adaptercout = GetLocalAdapterList(infoAdapterList);
printf("本机器有%d块网卡\n\n",adaptercout);
for(int i=0;i<adaptercout;i++)
printf("%d: %s: %s\n\n",i+1,infoAdapterList[i].szIPAddrStr,infoAdapterList[i].szDeviceName);
}
//--------------------------------------------------------------------------------------------------------------------------------//
vc6.0编译通过!