Skip to content

Commit

Permalink
sensor: broadcast the correct ip for each network interface
Browse files Browse the repository at this point in the history
  • Loading branch information
Williangalvani committed Jun 29, 2023
1 parent c6cd156 commit 9ee91d1
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/sensor/ping360helperservice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,33 @@ void Ping360HelperService::doBroadcast()
{
const QByteArray datagram = Ping360AsciiProtocol::discoveryMessage();

// Send discovery message as broadcast and for companion ip subnet
for (const QHostAddress& address : {QHostAddress {QHostAddress::Broadcast}, QHostAddress {"192.168.2.255"}}) {
_broadcastSocket.writeDatagram(datagram, address, Ping360AsciiProtocol::udpPort());
// Retrieve the IP addresses and their associated broadcast addresses
QList<QPair<QHostAddress, QHostAddress>> ipBroadcastAddresses;
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for (const QNetworkInterface& interface : interfaces) {
if (interface.flags().testFlag(QNetworkInterface::IsUp) &&
!interface.flags().testFlag(QNetworkInterface::IsLoopBack)) {
QList<QNetworkAddressEntry> entries = interface.addressEntries();
for (const QNetworkAddressEntry& entry : entries) {
if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
ipBroadcastAddresses.append(qMakePair(entry.ip(), entry.broadcast()));
}
}
}
}

// Send discovery message as broadcast for each interface's associated broadcast address
for (const QPair<QHostAddress, QHostAddress>& addressPair : ipBroadcastAddresses) {
const QHostAddress& ipAddress = addressPair.first;
const QHostAddress& broadcastAddress = addressPair.second;

if (_broadcastSocket.writeDatagram(datagram, broadcastAddress, Ping360AsciiProtocol::udpPort()) == -1) {
qDebug() << "Failed to send datagram to broadcast address:" << broadcastAddress.toString()
<< "for IP address:" << ipAddress.toString();
} else {
qDebug() << "Datagram sent successfully to broadcast address:" << broadcastAddress.toString()
<< "for IP address:" << ipAddress.toString();
}
}
}

Expand Down

0 comments on commit 9ee91d1

Please sign in to comment.