Bokeh Bokeh - 1 year ago 181
C Question

Receiving multicast UDP packets from a single network interface on macOS

This is a macOS question. I am trying to setup a UDP socket that receives SSDP messages, i.e. UDP packets, sent to multicast addresses. I want to restrict receiving these packets from a single network interface.

I tried

int fd = socket(AF_INET, SOCK_DGRAM, 0);
char* itf = "en0";
int res = setsockopt(fd, SOL_SOCKET, IP_RECVIF, itf, strlen(itf));


The setsockopt call fails with
errno 42
(Protocol not available).
I have also found
SO_BINDTODEVICE
that can be used for the same purpose, but it seems that this is not available on macOS.

Using bind with port and address also does not work. Then no packets sent to the multicast address are received on that socket.

Answer Source

From the OSX documentation on IP multicast...

A host must become a member of a multicast group before it can receive datagrams sent to the group. To join a multicast group, use the IP_ADD_MEMBERSHIP option...

To receive multicast traffic on a specific interface you need to tell the OS that you want to join that multicast group. Follow these steps (you were almost there)...

  1. Create a datagram socket (done).
  2. Bind to INADDR_ANY with the expected port.
  3. Join the multicast group via setsockopt() with the IP_ADD_MEMBERSHIP option. Here you can pass the IP address of the specific network interface you wish to receive multicast traffic on in the ip_mreq struct.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download