Using QUdpSocket to send datagrams

寵の児 提交于 2019-12-07 13:59:38

问题


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


回答1:


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:


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.



来源:https://stackoverflow.com/questions/6367209/using-qudpsocket-to-send-datagrams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!