Using QUdpSocket to send datagrams

John Gaby picture John Gaby · Jun 16, 2011 · Viewed 7k times · Source

I am trying to send a datagram using QUdpSocket. The following is the code I am 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 that has only one network adapter, it seems to work with no problem. However, if there are multiple adapters, I need to be able to control which is used to send the datagram. I have found that if I bind the socket as follows:

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

then I can force the datagram to be sent out on the local network associated with that IP (otherwise it appears to choose one at random). However, the 'bind' function sets up the socket to listen for packets, which I am really not interested in at this point. Is this the correct way to control which adapter is used, or is there some more straightforward way to do this?

Thanks

Answer

O.C. picture O.C. · Jun 16, 2011

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.