DropMulticastGroup() public method

public DropMulticastGroup ( IPAddress multicastAddr ) : void
multicastAddr IPAddress
return void
コード例 #1
18
        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));
                }
            }
        }
コード例 #2
0
ファイル: MainWindow.xaml.cs プロジェクト: bdr27/c-
        private void HandleBroadcasts()
        {
            var localIP = new IPEndPoint(IPAddress.Any, 50001);
            var udpClient = new UdpClient();
            udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpClient.ExclusiveAddressUse = false;
            udpClient.Client.Bind(localIP);

            var multicastingIP = IPAddress.Parse("228.5.6.7");
            udpClient.JoinMulticastGroup(multicastingIP);

            running = true;
            while (running)
            {
                var bytes = udpClient.Receive(ref localIP);
                var message = Encoding.UTF8.GetString(bytes);

                Dispatcher.Invoke(() =>
                {
                    lblResponse.Content = message;
                });
            }

            udpClient.DropMulticastGroup(multicastingIP);
            udpClient.Close();
        }
コード例 #3
0
ファイル: FeiQIM.cs プロジェクト: wellbeing2014/mywatcher
 /// <summary>
 /// 关闭连接
 /// </summary>
 public void close()
 {
     if (IsListening)
     {
         UdpClient.DropMulticastGroup(GroupIP);
         IsListening = false;
         thUDPListener.Abort();
     }
     UdpClient.Close();
 }
コード例 #4
0
ファイル: MainWindow.xaml.cs プロジェクト: bdr27/c-
        private void BoardbastMessages()
        {
            var multicastIP = IPAddress.Parse("228.5.6.7");
            var udpClient = new UdpClient();
            udpClient.JoinMulticastGroup(multicastIP);
            var endPoint = new IPEndPoint(multicastIP, 50001);
            running = true;

            while (running)
            {
                Thread.Sleep(2000);

                //broadbast the current time to all client
                var nowText = DateTime.Now.ToShortTimeString();
                var bytes = Encoding.UTF8.GetBytes(nowText);
                udpClient.Send(bytes, bytes.Length, endPoint);
            }

            udpClient.DropMulticastGroup(multicastIP);
            udpClient.Close();
        }
コード例 #5
0
        private void BackgroundListener()
        {
            IPEndPoint bindingEndpoint = new IPEndPoint(IPAddress.Any, _endPoint.Port);
            using (UdpClient client = new UdpClient())
            {
                client.ExclusiveAddressUse = false;
                client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                client.Client.Bind(bindingEndpoint);
                client.JoinMulticastGroup(_endPoint.Address);

                bool keepRunning = true;
                while (keepRunning)
                {
                    try
                    {
                        IPEndPoint remote = new IPEndPoint(IPAddress.Any, _endPoint.Port);
                        byte[] buffer = client.Receive(ref remote);
                        lock (this)
                        {
                            DataReceived(this, new MulticastDataReceivedEventArgs(remote, buffer));
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        keepRunning = false;
                        Thread.ResetAbort();
                    }
                }

                client.DropMulticastGroup(_endPoint.Address);
            }
        }
コード例 #6
0
ファイル: ConnectionManager.cs プロジェクト: ewin66/Forge
        internal void InitializeUDPDetector()
        {
            if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.Enabled)
            {
                {
                    // UDP szerver indítása
                    List <int> listeningPorts = NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.BroadcastListeningPorts;
                    if (listeningPorts.Count > 0)
                    {
                        if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.DetectionMode == UDPDetectionModeEnum.Multicast)
                        {
                            Action <AddressFamily, string> initMulticastUdpClient = ((a, ip) =>
                            {
                                IPEndPoint broadcastEp = null;
                                System.Net.Sockets.UdpClient udpClient = null;
                                foreach (int port in listeningPorts)
                                {
                                    try
                                    {
                                        if (LOGGER.IsInfoEnabled)
                                        {
                                            LOGGER.Info(string.Format("CONNECTION_MANAGER, trying to initialize broadcast detector on port {0} ({1}).", port, a.ToString()));
                                        }
                                        IPAddress multicastAddress = IPAddress.Parse(ip); // (239.0.0.222)
                                        broadcastEp = new IPEndPoint(a == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, port);
                                        udpClient = new System.Net.Sockets.UdpClient(a);

                                        udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                                        udpClient.ExclusiveAddressUse = false;
                                        udpClient.Client.Bind(broadcastEp);
                                        udpClient.EnableBroadcast = true;
                                        udpClient.MulticastLoopback = true;
                                        udpClient.AllowNatTraversal(true);

                                        udpClient.JoinMulticastGroup(multicastAddress);

                                        if (LOGGER.IsInfoEnabled)
                                        {
                                            LOGGER.Info(string.Format("CONNECTION_MANAGER, broadcast detector initialized on port {0} ({1}).", port, a.ToString()));
                                        }
                                        break;
                                    }
                                    catch (Exception ex)
                                    {
                                        if (LOGGER.IsErrorEnabled)
                                        {
                                            LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to initialize broadcast detector on port {0} ({1}). Reason: {2}", port, a.ToString(), ex.Message), ex);
                                        }
                                    }
                                }
                                if (udpClient != null)
                                {
                                    BroadcastServer server = new BroadcastServer(broadcastEp, udpClient);
                                    mBroadcastServers.Add(server);
                                    server.BeginReceive();
                                }
                            });
                            if (!string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress))
                            {
                                initMulticastUdpClient(AddressFamily.InterNetwork, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress);
                            }
                            if (NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6 && !string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress))
                            {
                                initMulticastUdpClient(AddressFamily.InterNetworkV6, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress);
                            }
                        }

                        if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.DetectionMode == UDPDetectionModeEnum.Broadcast)
                        {
                            Action <AddressFamily> initUdpClient = (a =>
                            {
                                IPEndPoint broadcastEp = null;
                                System.Net.Sockets.UdpClient udpClient = null;
                                foreach (int port in listeningPorts)
                                {
                                    try
                                    {
                                        if (LOGGER.IsInfoEnabled)
                                        {
                                            LOGGER.Info(string.Format("CONNECTION_MANAGER, trying to initialize broadcast detector on port {0} ({1}).", port, a.ToString()));
                                        }
                                        broadcastEp = new IPEndPoint(a == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, port);
                                        udpClient = new System.Net.Sockets.UdpClient(broadcastEp);
                                        udpClient.EnableBroadcast = true;
                                        udpClient.AllowNatTraversal(true);
                                        if (a == AddressFamily.InterNetwork)
                                        {
                                            udpClient.DontFragment = true;
                                        }
                                        if (LOGGER.IsInfoEnabled)
                                        {
                                            LOGGER.Info(string.Format("CONNECTION_MANAGER, broadcast detector initialized on port {0} ({1}).", port, a.ToString()));
                                        }
                                        break;
                                    }
                                    catch (Exception ex)
                                    {
                                        if (LOGGER.IsErrorEnabled)
                                        {
                                            LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to initialize broadcast detector on port {0} ({1}). Reason: {2}", port, a.ToString(), ex.Message), ex);
                                        }
                                    }
                                }
                                if (udpClient != null)
                                {
                                    BroadcastServer server = new BroadcastServer(broadcastEp, udpClient);
                                    mBroadcastServers.Add(server);
                                    server.BeginReceive();
                                }
                            });
                            initUdpClient(AddressFamily.InterNetwork);
                            if (NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6)
                            {
                                initUdpClient(AddressFamily.InterNetworkV6);
                            }
                        }
                    }
                }
                {
                    // UDP üzenetek szétszórása a hálózatba
                    List <int> targetPorts = NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.BroadcastTargetPorts;
                    if (targetPorts.Count > 0)
                    {
                        AddressEndPoint[] addressEps = null;
                        AddressEndPoint[] ipEps      = null;
                        if (NetworkManager.Instance.InternalLocalhost.NATGatewayCollection.NATGateways.Count > 0)
                        {
                            addressEps = new AddressEndPoint[NetworkManager.Instance.InternalLocalhost.NATGatewayCollection.NATGateways.Count];
                            for (int i = 0; i < addressEps.Length; i++)
                            {
                                addressEps[i] = NetworkManager.Instance.InternalLocalhost.NATGatewayCollection.NATGateways[i].EndPoint;
                            }
                        }
                        if (NetworkManager.Instance.InternalLocalhost.TCPServerCollection.TCPServers.Count > 0)
                        {
                            ipEps = new AddressEndPoint[NetworkManager.Instance.InternalLocalhost.TCPServerCollection.TCPServers.Count];
                            for (int i = 0; i < ipEps.Length; i++)
                            {
                                ipEps[i] = NetworkManager.Instance.InternalLocalhost.TCPServerCollection.TCPServers[i].EndPoint;
                            }
                        }
                        if (addressEps != null || ipEps != null)
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                {
                                    UdpBroadcastMessage message = new UdpBroadcastMessage(NetworkManager.Instance.InternalLocalhost.Id,
                                                                                          NetworkManager.Instance.InternalLocalhost.NetworkContext.Name, addressEps, ipEps);
                                    MessageFormatter <UdpBroadcastMessage> formatter = new MessageFormatter <UdpBroadcastMessage>();
                                    formatter.Write(ms, message);
                                    ms.Position = 0;
                                }

                                // multicast
                                if (NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.DetectionMode == UDPDetectionModeEnum.Multicast)
                                {
                                    // multicast
                                    foreach (int port in targetPorts)
                                    {
                                        Action <AddressFamily, string> sendMulticastUdpClient = ((a, ip) =>
                                        {
                                            using (System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(a))
                                            {
                                                udpClient.MulticastLoopback = true;
                                                udpClient.EnableBroadcast = true;
                                                udpClient.AllowNatTraversal(true);
                                                try
                                                {
                                                    IPAddress multicastaddress = IPAddress.Parse(ip);
                                                    udpClient.JoinMulticastGroup(multicastaddress);
                                                    IPEndPoint remoteEp = new IPEndPoint(multicastaddress, port);
                                                    if (LOGGER.IsInfoEnabled)
                                                    {
                                                        LOGGER.Info(string.Format("CONNECTION_MANAGER, sending multicast message on port {0}. ({1})", port, a.ToString()));
                                                    }
                                                    udpClient.Send(ms.ToArray(), Convert.ToInt32(ms.Length), remoteEp);
                                                    udpClient.DropMulticastGroup(multicastaddress);
                                                }
                                                catch (Exception ex)
                                                {
                                                    if (LOGGER.IsErrorEnabled)
                                                    {
                                                        LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to send multicast message ({0}). Reason: {1}", a.ToString(), ex.Message));
                                                    }
                                                }
                                            }
                                        });
                                        if (!string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress))
                                        {
                                            sendMulticastUdpClient(AddressFamily.InterNetwork, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv4MulticastAddress);
                                        }
                                        if (NetworkManager.Instance.InternalConfiguration.Settings.EnableIPV6 && !string.IsNullOrEmpty(NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress))
                                        {
                                            sendMulticastUdpClient(AddressFamily.InterNetworkV6, NetworkManager.Instance.InternalConfiguration.NetworkPeering.UDPDetection.IPv6MulticastAddress);
                                        }
                                    }
                                }
                                else
                                {
                                    // broadcast
                                    using (System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient())
                                    {
                                        udpClient.MulticastLoopback = false;
                                        udpClient.EnableBroadcast   = true;
                                        udpClient.AllowNatTraversal(true);
                                        udpClient.DontFragment = true;
                                        foreach (int port in targetPorts)
                                        {
                                            try
                                            {
                                                if (LOGGER.IsInfoEnabled)
                                                {
                                                    LOGGER.Info(string.Format("CONNECTION_MANAGER, sending broadcast message on port {0}.", port));
                                                }
                                                udpClient.Send(ms.ToArray(), Convert.ToInt32(ms.Length), new IPEndPoint(IPAddress.Broadcast, port));
                                            }
                                            catch (Exception ex)
                                            {
                                                if (LOGGER.IsErrorEnabled)
                                                {
                                                    LOGGER.Error(string.Format("CONNECTION_MANAGER, failed to send broadcast message. Reason: {0}", ex.Message));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (LOGGER.IsInfoEnabled)
                            {
                                LOGGER.Info("CONNECTION_MANAGER, both of list NAT gateways and TCP servers are empties for broadcast detection.");
                            }
                        }
                    }
                    else
                    {
                        if (LOGGER.IsInfoEnabled)
                        {
                            LOGGER.Info("CONNECTION_MANAGER, no target udp port definied for broadcast detection.");
                        }
                    }
                }
            }
            else
            {
                if (LOGGER.IsInfoEnabled)
                {
                    LOGGER.Info("CONNECTION_MANAGER, broadcast detection disabled.");
                }
            }
        }
コード例 #7
0
        private static async Task Sender(IPEndPoint endpoint, bool broadcast, string groupAddress)
        {
            try
            {
                string localhost = Dns.GetHostName();
                using (var client = new UdpClient())
                {
                    client.EnableBroadcast = broadcast;
                    if (groupAddress != null)
                    {
                        client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
                    }

                    bool completed = false;
                    do
                    {
                        WriteLine("Enter a message or bye to exit");
                        string input = ReadLine();
                        WriteLine();
                        completed = input == "bye";

                        byte[] datagram = Encoding.UTF8.GetBytes($"{input} from {localhost}");
                        int sent = await client.SendAsync(datagram, datagram.Length, endpoint);
                    } while (!completed);

                    if (groupAddress != null)
                    {
                        client.DropMulticastGroup(IPAddress.Parse(groupAddress));
                    }

                }
            }
            catch (SocketException ex)
            {
                WriteLine(ex.Message);
            }

        }
コード例 #8
0
ファイル: UDPMulticastListener.cs プロジェクト: 2m0nd/udp2com
        private void threadProc()
        {
            IPAddress addr = IPAddress.Parse(address);
            IPEndPoint ep = new IPEndPoint(addr, port);
            client = new UdpClient(port);

            while (!isTerminated)
            {
                byte[] data = client.Receive(ref ep);
                string s = Encoding.UTF8.GetString(data);
                this.SetText(s);
                vport.Write(s);
            }

            client.DropMulticastGroup(addr);
            client.Close();
        }