Search code examples
c#tcpudpipmulticast

How do I send data to multiple specific IP's


I'm writing a C# program that needs to send the same data to multiple specific recipients. I can't use multicast because that sends the data to everyone listening on the multicast address.

My current solution is to just iterate through the recipients and send the data to each of them separately but I'm looking for something a little more efficient.

Here's my current solution:

    public void SendToMultiple(IPAddress[] Recipients, byte[] Data)
    {
        UdpClient Client = new UdpClient();
        foreach(IPAddress Recipient in Recipients)
        {
            Client.Send(Data, Data.Length, new IPEndPoint(Recipient, PORT));
        }
        Client.Close();
    }

Solution

  • To the best of my knowledge you can either use Unicast, Multicast or Broadcast. Since you are only interested in sending to a particular set of clients, I can only recommend Unicast as the other two will send to those also listening.

    The only thing I can think of to make it more efficient is to put the code in maybe a Parallel.Foreach loop and create the UdpClient in there and then send the data out?

    public void SendToMultiple(IPAddress[] Recipients, byte[] Data)
    {
        Parallel.ForEach(Recipients,
            Recipient =>
            {
                UdpClient Client = new UdpClient();
                Client.Send(Data, Data.Length, new IPEndPoint(Recipient, PORT));
                Client.Close();
            });
    }