- 原理:客户端通过发送广播消息信息到ip:255.255.255.255(QHostAddress::Broadcast),局域网内的所有设备收到该消息回复客户端即可。客户端通过收到的回复统计当前有哪些设备在线。
- 获取到本地的IP,getLocalIP函数获取到过滤了虚拟机网卡以及本地回环网卡后的ip地址。
#include "udpclient.h"
#include <QDebug>
#include <QHostInfo>
#include <QNetworkInterface>
#include <iostream>
udpClient::udpClient(QObject *parent) : QObject(parent)
{
QString localIp = getLocalIP();
udpSocket = new QUdpSocket;
udpSocket->bind(QHostAddress(localIp),2001);
connect(udpSocket,&QUdpSocket::readyRead,this,&udpClient::processData);
}
QString udpClient::getLocalIP() {
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
foreach (const QNetworkInterface &interface, interfaces) {
QList<QNetworkAddressEntry> entries = interface.addressEntries();
qDebug()<<"name:"<<interface.humanReadableName()<<endl;
if(interface.humanReadableName().contains("Loopback") ||
interface.humanReadableName().contains("VMware Network Adapter"))
{
continue;
}
foreach (const QNetworkAddressEntry &entry, entries) {
if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
qDebug() << "Local IP Address: " << entry.ip().toString()<< endl;
}
}
}
return QString();
}
udpClient::~udpClient()
{
if(udpSocket)
{
delete udpSocket;
}
}
void udpClient::sendBroadCast()
{
QByteArray datagram = "Device Discovery";
udpSocket->writeDatagram(datagram,QHostAddress::Broadcast,8888);
}
void udpClient::processData()
{
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
qDebug() << "Received response from: " << sender.toString()<<"port:"<<senderPort << endl;
}
}