API 察看IP和子网

    技术2022-05-11  109

    主要 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 讨论

    .

     


    最新回复(0)