3

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

Bruce
  • 7,094
  • 1
  • 25
  • 42
John Gaby
  • 1,500
  • 3
  • 19
  • 33

2 Answers2

3

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.

O.C.
  • 6,711
  • 1
  • 25
  • 26
  • Thanks for the suggestion, however using the address "192.168.255.255" does not help. The IP address of my computer on adapter 1 is 192.168.1.104, and on adapter 2 is 192.168.56.1, so I am assuming that with the above address it is still picking the wrong adapter. However if I use "192.168.1.255" it does seem to work. I do not have a lot of experience with networks, however. How robust is this going to be. That is, will it work on any (most) systems? Thanks. – John Gaby Jun 16 '11 at 14:25
2

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.

Patrick
  • 21
  • 1
  • 1
    QHostAddress::Broadcast is a constant that is always 255.255.255.255, the generic broadcast address. Unfortunately an address that can work on any adapter doesn't tell your OS which adapter to use. – Patrick Aug 04 '11 at 13:12