UDP广播和单播通过同一个套接字?
我有一个 Linux 应用程序,它打开 UDP 套接字并将其绑定到端口。 我通过套接字发送单播数据包没有遇到任何问题。 我有机会发送广播数据包,因此我启用了 SO_BROADCAST,这允许广播数据包通过,但后来我注意到单播数据包也在被广播。 这是 UDP 套接字的预期行为,还是更有可能是我配置错误?
I have a Linux application that opens a UDP socket and binds it to a port. I haven't had any problem sending unicast packets through the socket. I had occasion to send a broadcast packet, so I enabled SO_BROADCAST, which allowed the broadcast packets to pass, but then I noticed that the unicast packets were being broadcast as well. Is this expected behaviour for a UDP socket, or is it more likely that I've misconfigured something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我了解 SO_BROADCAST 是一个套接字选项。 因此,如果您在套接字上启用它,该套接字就会广播。 我想如果您想从相同的代码进行单播和广播,您将需要打开不同的套接字。
From what I understand SO_BROADCAST is a socket option. So if you enable it on your socket this socket will broadcast. I guess you will need to open different sockets if you want to do unicast and broadcast from the same code.
我在这里没有做过太多的编程工作,但您可能需要提供有关库、操作系统版本、代码等的更多信息。也许是代码示例?
如果我记得我读过的书,如果在套接字上设置标志,这将影响从套接字发送的所有数据报,因为套接字基本上是网络标志+文件描述符的数据结构。
I have not done much hands on programming here, but you probably need to provide more information about the library, OS version, code, etc. Maybe a code sample?
If I remember the books I read, if you set the flag on the socket, that is going to affect all datagrams sent from the socket, because the socket is a basically a data structure of network flags + a file descriptor.
我在 Linux 上发现了同样的问题,即套接字同时进行单播和广播。 我解决了以下问题(伪代码):
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &1)
bind(sock, bindaddr, sizeof(struct sockaddr)
需要注意的是,没有过滤(请参阅 3 中的注意事项)。 这样您就会收到所有消息。
发送的消息是单播还是广播,具体取决于
sendto()
中的给定地址。I have figured out the same issue on Linux about having a socket getting unicast and broadcast at the same time. I solved the problem as follow (pseudo-code):
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &1)
bind(sock, bindaddr, sizeof(struct sockaddr)
with<YourPort>
The caveat is that there is no filtering (see caveat in 3.). So you will get all messages.
The sent messages are either unicasted or broadcasted depedning on the given address in the
sendto()
.