简介
使用ping方式获取网络可访问或者存在的设备发现部分会无法ping通但实际网络上存在此设备, 但使用arp -a却可以显示出来, 所以现在使用windows API的方式获取arp 表。
实现
参考Windows提供的示例转化成Qt
Qt .pro
cpp
LIBS += -liphlpapi
LIBS += -lws2_32
main.cpp
cpp
#include <QCoreApplication>
#include <QDebug>
#include <winsock2.h>
#include <windows.h>
#include <ws2ipdef.h>
#include <iphlpapi.h>
#include <netioapi.h>
int main()
{
PMIB_IPNET_TABLE2 pIpNetTable2 = NULL;
DWORD dwSize = 0;
unsigned long status = 0;
// 获取ARP表
status = GetIpNetTable2(AF_INET, &pIpNetTable2);
if (status != NO_ERROR)
{
printf("GetIpNetTable2 failed (error code %lu)\n", status);
free(pIpNetTable2);
return 1;
}
// 遍历ARP表并打印每项
for (DWORD i = 0; i < pIpNetTable2->NumEntries; i++)
{
MIB_IPNET_ROW2 row = pIpNetTable2->Table[i];
QString ip = QString::fromStdString(inet_ntoa(row.Address.Ipv4.sin_addr));
QString mac = QString::asprintf("%02X-%02X-%02X-%02X-%02X-%02X",
row.PhysicalAddress[0], row.PhysicalAddress[1],
row.PhysicalAddress[2], row.PhysicalAddress[3],
row.PhysicalAddress[4], row.PhysicalAddress[5]);
if (ip.startsWith("192.168.3") && mac != QString("00-00-00-00-00-00") && row.State != NlnsUnreachable) // 过滤192.168.3网段, mac地址不能为零, 可到达
{
qDebug() << "IP: " << ip << ", mac: " << mac;
}
}
// 释放缓冲区
free(pIpNetTable2);
return 0;
}