利用qt自带的QNetworkInterface接口以及c++Iphlpapi库,获取当前windows电脑下的网卡型号、物理地址、ip地址、子网掩码、网关等信息。
#include <QtNetwork/QNetworkInterface>#include <iostream>
#include <Windows.h>
#include <iphlpapi.h>#pragma comment(lib, "Iphlpapi.lib")//获取对应网卡部分信息
BOOL MatchNetcardInfo(UiNetcardVersion &netcardVer)
{PIP_ADAPTER_INFO pIPAdapterInfo = new IP_ADAPTER_INFO();PIP_ADAPTER_INFO adapters = nullptr;ULONG size = sizeof(IP_ADAPTER_INFO);int nRet = GetAdaptersInfo(pIPAdapterInfo, &size);//pIPAdapterInfo内存不够,重新申请if (ERROR_BUFFER_OVERFLOW == nRet){delete pIPAdapterInfo;pIPAdapterInfo = (PIP_ADAPTER_INFO)new byte[size];nRet = GetAdaptersInfo(pIPAdapterInfo, &size);}if (ERROR_SUCCESS == nRet){adapters = pIPAdapterInfo;while (adapters){//以XX-XX-XX-XX-XX-XX的形式输出MACchar buf[20]{0};sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", adapters->Address[0], adapters->Address[1], adapters->Address[2], adapters->Address[3], adapters->Address[4], adapters->Address[5]);QString macTmp = buf;if(macTmp != netcardVer.macAddr){adapters = adapters->Next;continue;}netcardVer.desc = adapters->Description;//可能网卡有多IP,因此通过循环去判断IP_ADDR_STRING* pIpAddrString = &(adapters->IpAddressList);do{netcardVer.ipAddr = pIpAddrString->IpAddress.String;netcardVer.netMask = pIpAddrString->IpMask.String;netcardVer.gateway = adapters->GatewayList.IpAddress.String;pIpAddrString = pIpAddrString->Next;} while (pIpAddrString);break;}}//释放分配的内存if (pIPAdapterInfo)delete pIPAdapterInfo;return true;
}//获取网卡信息
void GetNetcardInfo(){QList<UiNetcardVersion> netcardList;netcardList.clear();QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();foreach(const QNetworkInterface& it, interfaces){if(QNetworkInterface::Loopback == it.type())continue;UiNetcardVersion netcardVer;//获取名称和mac地址netcardVer.name = it.humanReadableName();netcardVer.macAddr = it.hardwareAddress();//获取型号、ip地址、子网掩码、网关MatchNetcardInfo(netcardVer);//添加到容器netcardList.append(netcardVer);}
}