Search code examples
c#socketsmulticastudpclientunicast

Can udpclient be both multicast and unicast


I am trying to build a client server socket library that will abstract the complexities of sending and receiving data. I was wondering if you have a UDP server setup to have a multicast group. Can it still send and receive unicast requests to specific clients if needed? Or do you have to have to open two sockets to handle either type?


Solution

  • You can do multicast and unicast at the same time using the same socket.

    You can send and receive any multicast and/or unicast UDP packets interleaved in anyway, so even if you want to talk to many different peers, some multicast, some unicast, you can use a single socket for this, and it fact it is often useful to do so in terms of complexity of the application.

    Some things to consider:

    On Linux you will want to bind() your UDP socket to your desired port and to the IP address 0.0.0.0 (INADDR_ANY). This will enable you to receive UDP packets targeted at any multicast address and any unicast address. Specifying a concrete IP address for bind() with UDP has a filtering effect and will only let UDP packets in targeted at that specific UDP address, which is rarely useful in practice, as all multicast servers usually also want to allow the same traffic to arrive as unicast, transparently.

    On Windows binding to a fixed nonzero IP address has different semantics: It binds the UDP socket to a specific interface (the one with the given IP address). Sending and receiving UDP traffic for multicast/unicast should work on Windows even without binding to 0.0.0.0.