示例#1
0
        public Endpoint Bind(UdpEndpoint endpoint)
        {
            Debug.Assert(_incoming);
            try
            {
                if (Network.IsMulticast(_addr))
                {
                    Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
                    Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

                    MulticastAddress = _addr;
                    if (OperatingSystem.IsWindows())
                    {
                        // Windows does not allow binding to the multicast address itself so we bind to INADDR_ANY
                        // instead. As a result, bidirectional connection won't work because the source address won't
                        // be the multicast address and the client will therefore reject the datagram.
                        if (_addr.AddressFamily == AddressFamily.InterNetwork)
                        {
                            _addr = new IPEndPoint(IPAddress.Any, _addr.Port);
                        }
                        else
                        {
                            _addr = new IPEndPoint(IPAddress.IPv6Any, _addr.Port);
                        }
                    }

                    Socket.Bind(_addr);
                    _addr = (IPEndPoint)Socket.LocalEndPoint !;

                    if (endpoint.Port == 0)
                    {
                        MulticastAddress.Port = _addr.Port;
                    }

                    Network.SetMulticastGroup(Socket, MulticastAddress.Address, _multicastInterface);
                }
                else
                {
                    Socket.Bind(_addr);
                    _addr = (IPEndPoint)Socket.LocalEndPoint !;
                }
            }
            catch (SocketException ex)
            {
                throw new TransportException(ex);
            }

            Debug.Assert(endpoint != null);
            return(endpoint.Clone((ushort)_addr.Port));
        }