简体   繁体   中英

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, ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM