System.Net.Sockets.UdpClient.JoinMulticastGroup C# (CSharp) Method

JoinMulticastGroup() public method

public JoinMulticastGroup ( IPAddress multicastAddr, int timeToLive ) : void
multicastAddr IPAddress
timeToLive int
return void
        public void JoinMulticastGroup(IPAddress multicastAddr, int timeToLive)
        {
            // parameter validation;
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (multicastAddr == null)
            {
                throw new ArgumentNullException(nameof(multicastAddr));
            }
            if (!RangeValidationHelpers.ValidateRange(timeToLive, 0, 255))
            {
                throw new ArgumentOutOfRangeException(nameof(timeToLive));
            }

            // Join the Multicast Group.
            JoinMulticastGroup(multicastAddr);

            // Set Time To Live (TTL).
            _clientSocket.SetSocketOption(
                (_family == AddressFamily.InterNetwork) ? SocketOptionLevel.IP : SocketOptionLevel.IPv6,
                SocketOptionName.MulticastTimeToLive,
                timeToLive);
        }

Same methods

UdpClient::JoinMulticastGroup ( IPAddress multicastAddr ) : void
UdpClient::JoinMulticastGroup ( IPAddress multicastAddr, IPAddress localAddress ) : void
UdpClient::JoinMulticastGroup ( int ifindex, IPAddress multicastAddr ) : void

Usage Example

        private static async Task ReaderAsync(int port, string groupAddress)
        {
            using (var client = new UdpClient(port))
            {
                if (groupAddress != null)
                {
                    client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
                    WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}");
                }

                bool completed = false;
                do
                {
                    WriteLine("starting the receiver");
                    UdpReceiveResult result = await client.ReceiveAsync();
                    byte[] datagram = result.Buffer;
                    string received = Encoding.UTF8.GetString(datagram);
                    WriteLine($"received {received}");
                    if (received == "bye")
                    {
                        completed = true;
                    }
                } while (!completed);
                WriteLine("receiver closing");

                if (groupAddress != null)
                {
                    client.DropMulticastGroup(IPAddress.Parse(groupAddress));
                }
            }
        }
All Usage Examples Of System.Net.Sockets.UdpClient::JoinMulticastGroup