#include "stdafx.h" #include <Windows.h> #include <IPHlpApi.h> #include <iostream> #pragma comment(lib,"IPHlpApi.lib") using namespace std; BOOL GetLocalAdaptersInfo() { //IP_ADAPTER_INFO结构体 PIP_ADAPTER_INFO pIpAdapterInfo = NULL; pIpAdapterInfo = new IP_ADAPTER_INFO; //结构体大小 unsigned long ulSize = sizeof(IP_ADAPTER_INFO); //获取适配器信息 int nRet = GetAdaptersInfo(pIpAdapterInfo,&ulSize); if (ERROR_BUFFER_OVERFLOW == nRet) { //空间不足,删除之前分配的空间 delete []pIpAdapterInfo; //重新分配大小 pIpAdapterInfo = (PIP_ADAPTER_INFO) new BYTE[ulSize]; //获取适配器信息 nRet = GetAdaptersInfo(pIpAdapterInfo,&ulSize); //获取失败 if (ERROR_SUCCESS != nRet) { if (pIpAdapterInfo != NULL) { delete []pIpAdapterInfo; } return FALSE; } } //MAC 地址信息 char szMacAddr[20]; //赋值指针 PIP_ADAPTER_INFO pIterater = pIpAdapterInfo; while(pIterater) { cout<<"网卡名称:"<<pIterater->AdapterName<<endl; cout<<"网卡描述:"<<pIterater->Description<<endl; sprintf_s(szMacAddr,20,"%02X-%02X-%02X-%02X-%02X-%02X", pIterater->Address[0], pIterater->Address[1], pIterater->Address[2], pIterater->Address[3], pIterater->Address[4], pIterater->Address[5]); cout<<"MAC 地址:"<<szMacAddr<<endl; cout<<"IP地址列表:"<<endl<<endl; //指向IP地址列表 PIP_ADDR_STRING pIpAddr = &pIterater->IpAddressList; while (pIpAddr) { cout<<"IP地址: "<<pIpAddr->IpAddress.String<<endl; cout<<"子网掩码:"<<pIpAddr->IpMask.String<<endl; //指向网关列表 PIP_ADDR_STRING pGateAwayList = &pIterater->GatewayList; while(pGateAwayList) { cout<<"网关: "<<pGateAwayList->IpAddress.String<<endl; pGateAwayList = pGateAwayList->Next; } pIpAddr = pIpAddr->Next; } cout<<endl<<"--------------------------------------------------"<<endl; pIterater = pIterater->Next; } //清理 if (pIpAdapterInfo) { delete []pIpAdapterInfo; } return TRUE; } int _tmain(int argc, _TCHAR* argv[]) { GetLocalAdaptersInfo(); cin.get(); return 0; }