2
votes

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?

3

3 Answers

3
votes

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.

0
votes

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.

-1
votes

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