在Windows中获取网络适配器相关信息是很方便的,可以通过GetAdaptersInfo函数获取并保存在IP_ADAPTER_INFO结构体中,再对结构休进行解析得到适配器信息。有关函数和结构体的详细说明可以参考MSDN,这里就不再复述。下面直接给出具体示例程序。
//引入头文件
#include <winsock2.h>
#include <stdio.h>
#include <IPHlpApi.h>
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "WS2_32.lib")
int main()
{
PIP_ADAPTER_INFO pAdapterInfo = NULL;
ULONG uLen = 0;
//为适配器结构申请内存
GetAdaptersInfo(pAdapterInfo, &uLen);
pAdapterInfo = (PIP_ADAPTER_INFO)GlobalAlloc(GPTR, uLen);
//取得本地适配器结构信息
DWORD dwRes = GetAdaptersInfo(pAdapterInfo, &uLen);
if(ERROR_SUCCESS == dwRes) //正确获取适配器信息
{
//解析适配器结构体输出适配器信息
while(pAdapterInfo)
{
//适配器名称
printf("The name of the adapter : %s\n", pAdapterInfo->AdapterName);
//适配器描述信息
printf("The description for the adapter : %s\n", pAdapterInfo->Description);
//硬件地址长度
printf("The length of the hardware address for the adapter : %d\n", pAdapterInfo->AddressLength);
//硬件地址
printf("The hardware address of adapter : ");
for(UINT i = 0; i < pAdapterInfo->AddressLength; i++)
{
if(i == pAdapterInfo->AddressLength - 1)
{
printf("%02x", pAdapterInfo->Address[i]);
}
else
{
printf("%02x-", pAdapterInfo->Address[i]);
}
}
IP_ADDR_STRING *pAddrString = &(pAdapterInfo->IpAddressList);
while(pAddrString)
{
//适配器配置的IP地址
printf("The IP address for this adapter : %s\n", pAddrString->IpAddress.String);
//适配器配置的子网掩码地址
printf("The mask address for this adapter : %s\n", pAddrString->IpMask.String);
pAddrString = pAddrString->Next;
}
pAddrString = &(pAdapterInfo->GatewayList);
while(pAddrString)
{
//适配器配置的默认网关地址
printf("The default gateway for this adapter : %s\n", pAddrString->IpAddress.String);
pAddrString = pAddrString->Next;
}
pAdapterInfo = pAdapterInfo->Next;
}
}
//未能正确获取适配器信息时的返回值,打印的内容是对应的错误信息描述
else if(ERROR_BUFFER_OVERFLOW == dwRes)
{
printf("The buffer size indicated by the pOutBufLen parameter is too \n");
printf("small to hold the adapter information. The pOutBufLen parameter points to the required size.\n");
}
else if(ERROR_INVALID_DATA == dwRes)
{
printf("The pOutBufLen parameter is NULL, or the calling process does not ");
printf("have read/write access to the memory pointed to by pOutBufLen, or ");
printf("the calling process does not have write access to the memory pointed to by the pAdapterInfo parameter.\n");
}
else if(ERROR_NO_DATA == dwRes)
{
printf("No adapter information exists for the local computer.\n");
}
else if(ERROR_NOT_SUPPORTED == dwRes)
{
printf("GetAdaptersInfo is not supported by the operating system running on the local computer.\n");
}
else
{
printf("Can't get information about adapter.\n");
}
return 0;
}
结构体中还有其他适配器信息在上述程序中没有解析,但是都可以根据需要做相应解析。