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

JoinMulticastGroup() public method

public JoinMulticastGroup ( IPAddress multicastAddr, IPAddress localAddress ) : void
multicastAddr IPAddress
localAddress IPAddress
return void
        public void JoinMulticastGroup(IPAddress multicastAddr, IPAddress localAddress)
        {
            // Validate input parameters.
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (_family != AddressFamily.InterNetwork)
            {
                throw new SocketException((int)SocketError.OperationNotSupported);
            }

            MulticastOption mcOpt = new MulticastOption(multicastAddr, localAddress);

            _clientSocket.SetSocketOption(
               SocketOptionLevel.IP,
               SocketOptionName.AddMembership,
               mcOpt);
        }

Same methods

UdpClient::JoinMulticastGroup ( IPAddress multicastAddr ) : void
UdpClient::JoinMulticastGroup ( IPAddress multicastAddr, int timeToLive ) : 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