First of all, you should consider broadcast obsolete, specially INADDR_BROADCAST
(255.255.255.255). Your question highlights exactly one of the reasons that broadcast is unsuitable. It should die along with IPv4 (hopefully). Note that IPv6 doesn't even have a concept of broadcast (multicast is used, instead).
INADDR_BROADCAST
is limited to the local link. Nowadays, it's only visible use is for DHCP auto-configuration, since at such time, the client will not know yet in what network it is connected to.
With a single sendto()
, only a single packet is generated, and the outgoing interface is determined by the operating system's routing table (ip route
on linux). You can't have a single sendto()
generate more than one packet, you would have to iterate over all interfaces, and either use raw sockets or bind the socket to a device using setsockopt(..., SOL_SOCKET, SO_BINDTODEVICE, "ethX")
to send each packet bypassing the OS routing table (this requires root privileges). Not a good solution.
Instead, since INADDR_BROADCAST
is not routed anyway, you can achieve almost the same thing by iterating over each interface, and sending the packet to its broadcast address. For example, assuming that your networks have 255.255.255.0 (/24) masks, the broadcast addresses are 192.168.1.255 and 192.168.2.255. Call sendto()
once for each of these addresses and you will have accomplished your goal.
Edit: fixed information regarding to INADDR_BROADCAST
, and complementing the answer with information about SO_BINDTODEVICE
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…