Subscribing to multiple multicast groups on one socket (Linux, C)

前端 未结 6 1476
悲哀的现实
悲哀的现实 2020-12-31 15:29

Is it possible to receive data from more than one multicast group on a single socket?

For example:

void AddGroup(int sock,
              const char*          


        
相关标签:
6条回答
  • 2020-12-31 15:57

    You only bind a socket once. Skip the bind the second time and see what happens.

    0 讨论(0)
  • 2020-12-31 15:59

    Yes, it's possible: look on the example in the link (http://www.tenouk.com/Module41c.html) To shorten this up in a few steps:

    1. You setsockopt with SO_REUSEADDR
    2. You bind on INADDR_ANY
    3. You setsockopt with IP_ADD_MEMBERSHIP on every group you want to receive datagram from.
    4. It seems to me that using IP_PKTINFO gives an option to distinguish received packets, but sender must take care about preparing them(Setting the source IP for a UDP socket)
    0 讨论(0)
  • 2020-12-31 16:02

    You can join as many multicast groups as you like, using the appropriate setsockopt() call with the IP_ADD_MEMBERSHIP option, rather than bind().

    0 讨论(0)
  • 2020-12-31 16:02

    In unix based OSes:

    If you need to bind to multicast address, you cannot call bind() more than once. And you will need to bind to multicast address when you expect more than one multicast streams using same destination port and multiple processes running in same device receiving those multicasts.

    For example, when you have multicast streams: 239.0.0.1:1234, 239.0.0.2:1234, 239.0.0.3:1234 and 239.0.0.4:1234, and you want to receive 239.0.0.1, 239.0.0.2 in process-A and want to receive 239.0.0.3, 239.0.0.4 in process-B, you cannot accomplish this when both processes A and B running in same device.

    0 讨论(0)
  • 2020-12-31 16:04

    You can join as many multicast groups you want to on a single socket. See setsockopt(), IP_PKTINFO for a way to recognize which multicast group you are reading data from.

    0 讨论(0)
  • 2020-12-31 16:13

    bind to the passive address, i.e. 0.0.0.0 for IPv4 and use ASM or SSM to pull in additional groups, e.g. IP_ADD_MEMBERSHIP as listed.

    You can only bind once.

    0 讨论(0)
提交回复
热议问题