主要 API GetNetworkParams() 和 GetAdaptersInfo() 函數枚舉Windows系統中的所有網路介面卡,並列印出IP,gateway,和MAC,並將MAC地址由HEX轉換為String輸出。
/*
向項目中添加
iphlpapi.lib
檔案
*/
#include <windows.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <time.h>
void __fastcall EnumAdapterInfo()
{
// 取得本網裝置地址
DWORD Err;
PFIXED_INFO pFixedInfo;
DWORD FixedInfoSize = 0;
PIP_ADAPTER_INFO pAdapterInfo, pAdapt;
DWORD AdapterInfoSize;
PIP_ADDR_STRING pAddrStr;
String pstrip = "";
String pstrgateway = "";
String pstrmac = "";
//
// Get the main IP configuration information for this machine using a FIXED_INFO structure
//
if((Err = GetNetworkParams(NULL, &FixedInfoSize)) != 0)
{
if(Err != ERROR_BUFFER_OVERFLOW)
{
// printf("GetNetworkParams sizing failed with error %d/n", Err);
return;
}
}
// Allocate memory from sizing information
if((pFixedInfo = (PFIXED_INFO) GlobalAlloc(GPTR, FixedInfoSize)) == NULL)
{
// printf("Memory allocation error/n");
return;
}
AdapterInfoSize = 0;
if((Err = GetAdaptersInfo(NULL, &AdapterInfoSize)) != 0)
{
if(Err != ERROR_BUFFER_OVERFLOW)
{
// printf("GetAdaptersInfo sizing failed with error %d/n", Err);
return;
}
}
if((pAdapterInfo = (PIP_ADAPTER_INFO) GlobalAlloc(GPTR, AdapterInfoSize)) == NULL)
{
// printf("Memory allocation error/n");
return;
}
// Get actual adapter information
if((Err = GetAdaptersInfo(pAdapterInfo, &AdapterInfoSize)) != 0)
{
// printf("GetAdaptersInfo failed with error %d/n", Err);
return;
}
while(pAdapterInfo != NULL)
{
try
{
// 獲得 ip 和網關
String ip = pAdapterInfo->IpAddressList.IpAddress.String;
String gateway = pAdapterInfo->GatewayList.IpAddress.String;
// -----------------------------------------
// 把 MAC 由 Hex 轉換出來
// 將 hex 的 mac 轉換為 string 的 mac
String strmac = "";
char hexmac[MAC_LENGTH];
memset(hexmac, 0, MAC_LENGTH);
// 得到 mac
memcpy(hexmac, pAdapterInfo->Address, MAC_LENGTH);
// 取長度
int length = strlen(hexmac);
// 臨時儲存 mac
char buf[16];
// 迴圈 hex 轉換為 char
for(int i = 0; i < length; i ++)
{
sprintf(buf, "%2.2x", hexmac[i]);
if(strmac.Length() > 0)
{
strmac = strmac + "-";
}
// 對應的 char 添加到 mac 串
strmac = strmac + String(buf[6]);
strmac = strmac + String(buf[7]);
}
// 轉換為大寫
pstrmac = strmac.UpperCase();
// -----------------------------------------
// 得到 ip
pstrip = ip;
// -----------------------------------------
// 得到 gateway
pstrgateway = gateway;
printf("ip: %s\n", ip.t_str());
printf("mac: %s\n", pstrmac.t_str());
printf("gateway: %s\n", pstrgateway.t_str());
printf("------------------\n");
}
catch(...)
{
}
// 沒有找到相應的裝置 遍曆下一個裝置
pAdapterInfo = pAdapterInfo->Next;
}
}
Q群 236201801 討論
.