VC获取本地网卡信息
操作系统:win10
IDE:vs2019
涉及到的函数:GetAdaptersInfo
涉及到的头文件:Windows.h、iphlpapi.h、atlstr.h
涉及到的库:Iphlpapi.lib
代码如下:
#include <Windows.h> #include <iphlpapi.h> #include <iostream> #include <atlstr.h> #pragma comment(lib,"Iphlpapi.lib") int main() { PIP_ADAPTER_INFO pAdapterInfo = NULL; PIP_ADAPTER_INFO pAdapter = NULL; DWORD dwRetVal = 0; ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO); if (GetAdaptersInfo(NULL, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen); if((dwRetVal = GetAdaptersInfo(pAdapterInfo,&ulOutBufLen)) == NO_ERROR){ pAdapter = pAdapterInfo; while (pAdapter) { PIP_ADDR_STRING pIPAddr; pIPAddr = &pAdapter->IpAddressList; while (pIPAddr) { CString ip = pIPAddr->IpAddress.String; CString mask = pIPAddr->IpMask.String; if (ip.Compare(_T("0.0.0.0"))&&mask.Compare(_T("0.0.0.0"))) { std::cout << pAdapter->Description << " 已连接" << std::endl; std::cout << "IP地址: " << pIPAddr->IpAddress.String << std::endl; std::cout << "子网掩码: " << pIPAddr->IpMask.String << std::endl; } else { std::cout << pAdapter->Description << " 网卡未连接" << std::endl; } pIPAddr = pIPAddr->Next; } pAdapter = pAdapter->Next; } } if (pAdapterInfo)free(pAdapterInfo); return 0; }
编译通过,运行如下图:

在MFC中实现
布局:

设置1个控件变量,分别是CAdapter

代码部分:
双击布局中的获取按钮进入按钮事件函数,写如下代码即可
PIP_ADAPTER_INFO pAdapterInfo = NULL; PIP_ADAPTER_INFO pAdapter = NULL; DWORD dwRetVal = 0; ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO); if (GetAdaptersInfo(NULL, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen); if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { pAdapter = pAdapterInfo; while (pAdapter) { PIP_ADDR_STRING pIPAddr; pIPAddr = &pAdapter->IpAddressList; while (pIPAddr) { CString ip = (CString)pIPAddr->IpAddress.String; CString mask = (CString)pIPAddr->IpMask.String; if (ip.Compare(_T("0.0.0.0")) && mask.Compare(_T("0.0.0.0"))) { CAdapter.AddString((CString)pAdapter->Description + " 已连接"); CAdapter.AddString((CString)"IP地址: " + pIPAddr->IpAddress.String); CAdapter.AddString((CString)"子网掩码: " + pIPAddr->IpMask.String); } else { CAdapter.AddString((CString)pAdapter->Description + " 网卡未连接"); } pIPAddr = pIPAddr->Next; } pAdapter = pAdapter->Next; } } if (pAdapterInfo)free(pAdapterInfo);
截图一下我的获取按钮事件函数

编译运行成功,点击获取按钮发现内容的顺序发生了变化,是因为默认Listbox控件会排序,所以需要修改Listbox控件的Sort的属性为False,如下图:

再运行,点击获取按钮的内容顺序就不会乱了,如下图:
