UDP broadcast and unicast over the same socket?

I have a Linux application that opens a UDP socket and binds it to a port. I had no problem sending unicast packets over the socket. I was fortunate enough to send a broadcast packet, so I turned on SO_BROADCAST, which allowed broadcast packets, but then I noticed that unicast packets were also transmitted. Is this the expected behavior for a UDP socket, or is it more likely that I misconfigured something?

+1
source share
3 answers

From what I understand SO_BROADCAST is a socket option. Therefore, if you enable it in your socket, this socket will be broadcast. I think you will need to open different sockets if you want to do unicast and broadcast from the same code.

+2
source

I didn't program very much here, but you probably need to provide more information about the library, OS version, code, etc. Maybe an example code?

If I remember the books that I read, if you set the flag on the socket, this will affect all datagrams sent from the socket, because the socket is basically a network flag data structure + file descriptor.

0
source

I found the same problem on Linux that the socket is receiving unicast and broadcasting at the same time. I solved the problem as follows (pseudocode):

  • sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
    • Open socket
  • setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &1)
    • Allows you to receive incoming and outgoing messages from this socket.
  • 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 disclaimer in 3.). Thus, you will receive all messages. Sent messages are either messy or broadcast to the specified address in sendto() .

-1
source

All Articles