DatagramSocket: support for sending UDP Broadcast packets


#1

Jules,

Any chance you could add support for sending UDP local broadcast packets (i.e. packets sent to 255.255.255.255) to the DatagramSocket class in the next version of JUCE? It is currently possible to receive these packets, but not to send them.

To add support for sending UDP broadcast packets:

The expression starting on line 98 of juce_Socket.cpp:

return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0 && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0 && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0));

…should be changed to:

return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0 && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0 && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0)) && (!isDatagram || (setsockopt( handle, SOL_SOCKET, SO_BROADCAST, (const char*)&one, sizeof(int) ) == 0));

Many thanks for so generously providing such a fantastic library! :slight_smile:


#2

I’m not the world’s greatest expert on sockets… Will adding that setting cause any unwanted behaviours for existing code?


#3

Unfortunately, I’m no socket expert myself. However I have been working with them enough now that I don’t think adding broadcast packet support would break anything. As far as I know, enabling the SO_BROADCAST socket option doesn’t change anything beyond allowing the socket to send a packet to the special IP address 255.255.255.255 to address everyone on a local network. It doesn’t change how any other packets are sent. Broadcast packets are received by the DatagramSocket class regardless of whether SO_BROADCAST is enabled.

For more info: http://msdn.microsoft.com/en-us/library/tst0kwb1.aspx

If you still have doubts, this support could be added as a property of the DatagramSocket class, e.g.:

void enableBroadcastPackets( bool ShouldBeEnabled ) bool isBroadcastingEnabled( void );


#4

Ok, that seems fair enough then. If no-one else objects, I’ll add that setting to the buid. Thanks!


#5

Don’t enable this option by default, or it’ll break on Linux with SELinux enabled.

SO_BROADCAST is not required for normal application socket, thus is priviledge under linux. As is you shouldn’t enable it by default, else the application will get permission denied errors.

I think adding a method for controlling SO_BROADCAST and SO_REUSEADDR would be a good idea anyway, but it shouldn’t be the default.

(And also, from other network code I’ve written, controlling SO_LINGER for TCP is a good idea too, as it avoids having zombie sockets)


#6

Agh, I’d already done it, and never thought of there being a privilege issue.

Ok, I’ll tweak it so that this is a flag you can pass to the constructor.