I\'m trying to get udp multicast data using sockets and c++ (c). I have a server with 2 network cards so I need to bind socket to specific interface. Currently I\'m testing
After some searching and testing I found out here that when binding udp multicast socket we specify port and leave address empty e.g. specify INADDR_ANY
.
So the following
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = (source_iface.empty() ?
htonl(INADDR_ANY) :
inet_addr(source_iface.c_str()));
should be look like:
COMMENT: If I understand your code you should be binding to your multicast address not the wildcard address. If you bind to the wildcard address you will be able to receive unicast packets on your multicast port. Binding to your multicast address will prevent this and ensure you only get multicast packets on that port.
EDIT: Fixed the code based on above comment, binding to multicast address, stored in 'group', as opposed to INADDR_ANY to receive only multicast packets sent to multicast address.
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = (group.empty() ?
htonl(INADDR_ANY) :
inet_addr(group.c_str()));
This solved the problem. Adding IP_MULTICAST_IF
will not help because that is for selecting specific interface for sending udp data, the problem above was on receiving side.
I think you need to add IP_MULTICAST_IF
struct ip_mreq multi;
multi.imr_multiaddr.s_addr = inet_addr(group.c_str());
multi.imr_interface.s_addr = (source_iface.empty() ?
htonl(INADDR_ANY): inet_addr(source_iface.c_str()));
status = setsockopt(me->ns_fd, IPPROTO_IP, IP_MULTICAST_IF,
(char *)&multi.imr_interface.s_addr,
sizeof(multi.imr_interface.s_addr));
I hope that helps.