How to set up a socket for UDP multicast with 2 network cards present?

萝らか妹 提交于 2019-11-30 05:03:15

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!