C++ QT实现获取本机网卡信息
作者:bangtan辉
这篇文章主要为大家详细介绍了如何利用qt自带的QNetworkInterface接口以及c++Iphlpapi库,获取当前windows电脑下的网卡信息,需要的可以参考下
本文将利用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的形式输出MAC char 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); } }
到此这篇关于C++ QT实现获取本机网卡信息的文章就介绍到这了,更多相关C++ QT获取网卡信息内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!