一、背景信息
电脑有一个或者多个网卡,如下图所示:
一个网卡又可以配有多个IP地址,包括 IPv4 和 IPv6 地址:
二、代码实现
以下代码实现了查找电脑所有网卡,并获取某个网卡的 IP 等信息:
int main() {
// 获取所有网卡信息
QComboBox *m_netCardComboBox;
QList<QNetworkInterface> m_allInterfaces = QNetworkInterface::allInterfaces();
for (int i = 0; i < m_allInterfaces.size(); ++i) {
QNetworkInterface netInterface = m_allInterfaces.at(i);
m_netCardComboBox->addItem(netInterface.humanReadableName());
}
// 获取当前下拉框选择的网卡IP等信息
{
int currentIndex = m_netCardComboBox->currentIndex();
QNetworkInterface netInterface = m_allInterfaces.at(currentIndex);
QList<QNetworkAddressEntry> addressEntries = netInterface.addressEntries();
for (int k = 0; k < addressEntries.size(); ++k) {
QNetworkAddressEntry entry = addressEntries.at(k);
if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) { // 这里筛选一下IPv4地址
qDebug() << addressEntries.at(k).ip().toString();
qDebug() << addressEntries.at(k).netmask().toString();
qDebug() << addressEntries.at(k).broadcast().toString();
}
}
}
return 0;
}
三、VC++实现
如果你不是用QT来开发,可以通过调用 Windows API 来实现这个功能:
#include <iostream>
#include <Windows.h>
#include <IPHlpApi.h>
#include <vector>
#include <string>
#pragma comment(lib, "IPHlpApi.lib")
// wchar_t to string
void wcharToString(std::string& szDst, wchar_t *wchar) {
wchar_t * wText = wchar;
DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE); // WideCharToMultiByte的运用
char *psText; // psText为char*的临时数组,作为赋值给std::string的中间变量
psText = new char[dwNum];
WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE); // WideCharToMultiByte的再次运用
szDst = psText; // std::string赋值
delete[]psText; // psText的清除
}
void GetNetworkAdaptersInfo() {
ULONG outBufLen = 0;
GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &outBufLen);
std::vector<BYTE> buffer(outBufLen);
PIP_ADAPTER_ADDRESSES pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(buffer.data());
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &outBufLen) == ERROR_SUCCESS) {
while (pAddresses) {
std::string strName, strMAC;
wcharToString(strName, pAddresses->FriendlyName); // 用户友好的网卡名称
wchar_t buf[18];
swprintf_s(buf, sizeof(buf) / sizeof(wchar_t), L"%02X:%02X:%02X:%02X:%02X:%02X",
pAddresses->PhysicalAddress[0], pAddresses->PhysicalAddress[1], pAddresses->PhysicalAddress[2],
pAddresses->PhysicalAddress[3], pAddresses->PhysicalAddress[4], pAddresses->PhysicalAddress[5]);
wcharToString(strMAC, buf);
std::cout << strName << std::endl;
std::cout << strMAC << std::endl;
pAddresses = pAddresses->Next;
}
}
}