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.
multicastAddressIPAddress representing the multicast group to join.
timeToLivevoidArgumentNullExceptionmulticastAddress is null.
SocketExceptionObjectDisposedExceptionUdpClient has been closed.
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.
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}");
}
}
}