I have a hardware device connected on one of the available network interfaces (in general don't know which one) that answers to UDP broadcast messages with UDP broadcast messages. I need to be able to send a message and receive the broadcast answer.
From other topics on stackoverflow, I've been able to get part of it to work, but not both send and receive simultaneously. Currently I do the following:
- For each interface listed by
getifaddrs(&ifaces)
withiface->ifa_addr->sa_family == AF_INET
- Create a socket with
socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
- Set the socket to broadcast with
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, ...)
bind()
to the address inifaces->ifa_addr
ofgetifaddrs()
with 0 as port (first free port)- Send, with
sendto()
, a packet toINADDR_BROADCAST
from each of the opened sockets - In n parallel threads (one for each socket) I wait for answers with
recvfrom()
So, I fired up wireshark and the message gets sent correctly to all interfaces, the hardware answers in broadcast (255.255.255.255) correctly on the same port from which the packet was sent, but recvfrom()
never returns data, it just waits. With the same code, if I bind to INADDR_ANY
instead of ifaces->ifa_addr
and run sendto()
on the actual IP of the hardware instead of INADDR_BROADCAST
, the broadcast answer gets caught without problems.
What exactly is going on? Why isn't the answer caught in the first case? How can send and receive in broadcast on multiple interfaces?
By the way, root access is not an option, so I can't do setsockopt(..., SOL_SOCKET, SO_BINDTODEVICE, "ifacename")
. And the OS is Linux.