使用QUdpSocket发送数据报

发布于 2024-11-15 13:45:22 字数 544 浏览 7 评论 0原文

我正在尝试使用 QUdpSocket 发送数据报。以下是我正在使用的代码:

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

现在,如果我在一台只有一个网络适配器的计算机上运行它,它似乎可以正常工作。但是,如果有多个适配器,我需要能够控制哪个适配器用于发送数据报。我发现,如果我按如下方式绑定套接字:

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

那么我可以强制将数据报发送到与该 IP 关联的本地网络上(否则它似乎是随机选择一个)。然而,“bind”函数设置套接字来侦听数据包,目前我对此并不感兴趣。这是控制使用哪个适配器的正确方法,还是有一些更直接的方法来做到这一点?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟火散人牵绊 2024-11-22 13:45:22

你需要这样的东西

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

这将发送 udp 广播数据包。

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.

北风几吹夏 2024-11-22 13:45:22

子网的广播地址始终是子网中的最高地址。在您的情况下:

适配器1:地址192.168.1.104子网掩码255.255.255.0广播:192.168.1.255

适配器2:地址192.168.56.1子网掩码255.255.255.0广播:192.168.56.255

所以您需要要广播的适配器的地址和子网掩码来查找正确的广播地址。

如果您使用适配器地址和子网掩码来计算广播地址,这应该适用于 IPv4 网络。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文