UDP广播和单播通过同一个套接字?

发布于 2024-07-17 22:34:53 字数 161 浏览 4 评论 0原文

我有一个 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 技术交流群。

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

发布评论

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

评论(3

天气好吗我好吗 2024-07-24 22:34:53

据我了解 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.

甜味拾荒者 2024-07-24 22:34:53

我在这里没有做过太多的编程工作,但您可能需要提供有关库、操作系统版本、代码等的更多信息。也许是代码示例?

如果我记得我读过的书,如果在套接字上设置标志,这将影响从套接字发送的所有数据报,因为套接字基本上是网络标志+文件描述符的数据结构。

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.

疯到世界奔溃 2024-07-24 22:34:53

我在 Linux 上发现了同样的问题,即套接字同时进行单播和广播。 我解决了以下问题(伪代码):

  1. sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
    • 打开套接字
  2. setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &1)
    • 允许从此套接字传入和传出广播
  3. bind(sock, bindaddr, sizeof(struct sockaddr)

<块引用>
<块引用>

bindaddr.sin_family = AF_INET

bindaddr.sin_port = <您的端口>

bindaddr.sin_addr.s_addr = INADDR_ANY


  • 获取任何卡上的所有传入消息 < code>

需要注意的是,没有过滤(请参阅 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):

  1. sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
    • Open the socket
  2. setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &1)
    • Allows incoming and outgoing broadcast from this socket
  3. bind(sock, bindaddr, sizeof(struct sockaddr) with

bindaddr.sin_family = AF_INET

bindaddr.sin_port = <YourPort>

bindaddr.sin_addr.s_addr = INADDR_ANY

  • Get all incoming messages on any card for <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().

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