UdpClient.JoinMulticastGroup Method

public void JoinMulticastGroup(int multicastAddress)

public void JoinMulticastGroup(IPAddress multicastAddress)

public void JoinMulticastGroup(int multicastAddress, int timeToLive)

public void JoinMulticastGroup(IPAddress multicastAddress, int timeToLive)

Initializes a new instance of the UdpClient class and joins the specified multicast group.

Parameters

multicastAddress
An IPAddress representing the multicast group to join.
OR An integer that specifies the IP address of the multicast group to join.
timeToLive
The maximum number of network hops the multicast datagram can take before being discarded. A value of 1 means that datagrams can only be delivered to hosts on the local network.

Returns

void
This method does not return a value.

Exceptions

ArgumentNullException
multicastAddress is null.
SocketException
An error occurred while accessing the socket.
ObjectDisposedException
The UdpClient has been closed.

Remarks

Multicast allows a single datagram to be sent to multiple destinations simultaneously. You can use the JoinMulticastGroup method to subscribe to a multicast group.

The timeToLive parameter controls the scope of the multicast. A timeToLive of 1 restricts multicast traffic to the local network segment. Higher values allow traffic to propagate across routers.

To leave a multicast group, use the LeaveMulticastGroup method.

Note: Multicast group addresses are in the range of 224.0.0.0 through 239.255.255.255.

Examples

The following code example demonstrates how to join a multicast group.


using System;
using System.Net;
using System.Net.Sockets;

public class MulticastExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Define the multicast group address and port
            IPAddress multicastAddr = IPAddress.Parse("239.255.0.1");
            int port = 12345;

            // Create a UdpClient and join the multicast group
            using (UdpClient udpClient = new UdpClient(port))
            {
                udpClient.JoinMulticastGroup(multicastAddr);
                Console.WriteLine($"Joined multicast group: {multicastAddr}");

                // Here you would typically start listening for multicast datagrams
                // or send datagrams to the group.

                // For demonstration, we'll wait a bit and then leave.
                Console.WriteLine("Waiting for 10 seconds...");
                System.Threading.Thread.Sleep(10000);

                udpClient.LeaveMulticastGroup(multicastAddr);
                Console.WriteLine($"Left multicast group: {multicastAddr}");
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine($"SocketException: {e.Message}");
        }
        catch (Exception e)
        {
            Console.WriteLine($"General exception: {e.Message}");
        }
    }
}