Do I need a PORT when joining a multicast group or just the IP?

chrisapotek picture chrisapotek · Feb 24, 2012 · Viewed 14.3k times · Source

I would like to learn that once and for all. What is the procedure to connect a multicast socket? I know you have to bind to a local interface (do you need IP and port for that?) then I know you have to join a group (do you need IP:PORT for the address you want to join and the network interface again!!!??) and then finally you can leave the group.

Can someone with experience clarify what is the whole of those many addresses? I will list below:

  • BindAddress (IP:PORT)
  • NetworkAddress (IP:PORT)
  • MulticastAddress (IP:PORT)

Where and what is the multicast group here?

Answer

user207421 picture user207421 · Feb 24, 2012

A multicast group is a special IP address. You join it via setsockopt() using the socket option IP_ADDMEMBERSHIP, or e.g. in Java via MulticastSocket.joinGroup(). No port number here. If you want to join via a specific local address, use the overload that specifies a local address, or call setNetworkInterface() first.

Binding to a local address is a separate operation, which primarily determines which local addresses the socket can send and receive data on: one, or all of them: either one local address, which determines which of your available subnets you are listening to and can send via, or a port, or both. Normally it is best to use INADDR_ANY as the bind-address, unless your application magically knows about the network topology.

This is muddied by the fact that you can bind to a multicast address in Linux, but this appears to be a misunderstanding that will now always be with us.

You send to a multicast group by sending to the multicast address.