广播
如果可能的话,有人可以向我提供使用 UDP 发送和接收广播消息的代码或链接吗?
我一直陷入一个问题,希望你们能帮助我解决它。 谢谢
Could anyone please provide me with the code or link to send and receive broadcast messages if possible using UDP?
I have been stuck in a problem and hope if u guys could help me resolve it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个 C# 示例:
Here's a C# example:
以下是广播发送者和接收者的示例代码。
它应该可以轻松移植到任何可以访问标准 Berkly Sockets API 的语言。
Here is example code for both the broadcast sender and receiver.
It should be easily portable to any language which has access to the standard Berkly Sockets API.
我不会发布代码,只是提出几点意见:
发送 UDP 广播就像发送单播数据包 - 只是目标地址不同。 这可以是
INADDR_BROADCAST
(255.255.255.255),但这可能会在具有多个网络接口的系统上导致问题。 最好发送到您要发送的接口的特定广播地址。 唯一重要的警告是,您可能需要在操作系统允许发送广播之前设置SO_BROADCAST
套接字选项。接收 UDP 广播完全就像接收单播数据包一样。 不需要特殊代码,但您应该将接收器绑定到
INADDR_ANY
。I'm not going to post code, just a couple of observations:
Sending a UDP broadcast is just like sending a unicast packet - only the destination address is different. This can be
INADDR_BROADCAST
(255.255.255.255) but that can cause problems on systems with multiple network interfaces. It's better to send to the specific broadcast address for the interface that you want to send on. The only significant caveat is that you may need to set theSO_BROADCAST
socket option before your O/S will permit sending the broadcast.Receiving a UDP broadcast is exactly like receiving a unicast packet. No special code is necessary, but you should have the receiver bound to
INADDR_ANY
.我刚刚开始学习这一点,但这是我的第一个工作示例,它可能会对您有所帮助。
收件人代码:
发件人代码:
I'm just starting to learn this, but this was my first working example, it might help you.
Receiver code:
Sender code: