UDP Broadcast not working when no Default Gateway configured on Linux
There are a few pitfalls for the burdened Software Engineer getting going with UDP datagram broadcast. One that I hit this week involved clients not receiving broadcast messages unless a default gateway was configured on the broadcasting host.
Very strange, why should broadcast need a gateway? Well it turns out that it doesn’t, it really just needed to know which network adapter to use when sending (and failing that it uses the gateway).
So to fix this we have a few options, including:
1.) Add a broadcast route to the network device in question (e.g. in /etc/network/interfaces), or
2.) Update the UDP code so that the outgoing network device is specified – which can be done like this (to target eth0):
// char buffer[]="eth0"; setsockopt(socket, SOL_SOCKET, SO_BINDTODEVICE, buffer, 5); //
PS, I think this may be non-portable an may only work on Linux. Some more info here.