UDP broadcast and unicast through the same socket?

本小妞迷上赌 提交于 2020-01-15 05:32:05

问题


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?


回答1:


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.




回答2:


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.




回答3:


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().



来源:https://stackoverflow.com/questions/800302/udp-broadcast-and-unicast-through-the-same-socket

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