Using QUdpSocket to send datagrams

I am trying to send a datagram using QUdpSocket. The following is the code I'm using:

udpSocket = new QUdpSocket(this);
QByteArray datagram = "Message";
udpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 45454);

Now, if I run this on a computer with one network adapter, it seems to work without problems. However, if there are several adapters, I need to be able to control which one is used to send the datagram. I found that if I bind the socket as follows:

udpSocket->bind(QHostAddress("192.168.1.104"), 45454);

then I can force the datagram to the local network associated with this IP address (otherwise, it seems that it is selected randomly). However, the "bind" function sets up a socket for listening to packets that I really am not interested in at the moment. Is this the right way to manage the adapter, or is there an even easier way to do this?

thank

+3
source share
2 answers

You need something like this

QHostAddress myBroadcastAddress = QHostAddress("192.168.255.255");
udpSocket->writeDatagram(datagram.data(),datagram.size(), myBroadcastAddress , 45454 )

This will send udp broadcast packets.

+2
source

The broadcast address of the subnet is always the highest address on the subnet. In your case:

adapter1: address 192.168.1.104 subnet mask 255.255.255.0 broadcast: 192.168.1.255

adapter2: 192.168.56.1 255.255.255.0 : 192.168.56.255

, , , , .

, IPv4.

+2

All Articles