Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

adapter1: address 192.168.1.104 subnet mask 255.255.255.0 broadcast: 192.168.1.255

adapter2: address 192.168.56.1 subnet mask 255.255.255.0 broadcast: 192.168.56.255

So you need both the address of the adapter you want to broadcast on and the subnet mask to find the correct broadcast address.

If you use adapter address and subnet mask to calculate the broadcast address this should work for IPv4 networks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top