Exemple #1
0
        void Send(Message msg, bool checkDuplicate, IPEndPoint remoteEndPoint = null)
        {
            var packet = msg.ToByteArray();

            if (packet.Length > maxPacketSize)
            {
                throw new ArgumentOutOfRangeException($"Exceeds max packet size of {maxPacketSize}.");
            }

            if (checkDuplicate && !sentMessages.TryAdd(packet))
            {
                return;
            }

            // Standard multicast reponse?
            if (remoteEndPoint == null)
            {
                client?.SendAsync(packet).GetAwaiter().GetResult();
            }
            // Unicast response
            else
            {
                var unicastClient = (remoteEndPoint.Address.AddressFamily == AddressFamily.InterNetwork)
                    ? unicastClientIp4 : unicastClientIp6;
                unicastClient.SendAsync(packet, packet.Length, remoteEndPoint).GetAwaiter().GetResult();
            }
        }
Exemple #2
0
        void Send(Message msg, bool checkDuplicate, IPEndPoint remoteEndPoint = null, bool isLegacyUnicast = false)
        {
            var packet = msg.ToByteArray();

            if (packet.Length > maxPacketSize)
            {
                throw new ArgumentOutOfRangeException($"Exceeds max packet size of {maxPacketSize}.");
            }

            if (checkDuplicate && !sentMessages.TryAdd(packet))
            {
                return;
            }

            // Standard multicast response?
            if (remoteEndPoint == null && !isLegacyUnicast)
            {
                // no clear remote endpoint or querier defined - could be from an announce
                // better perform asynchronously, because this message gets sent on all available NICs and should not block
                Task.Run(() => client?.SendAsync(msg).GetAwaiter().GetResult()).ConfigureAwait(false);
            }
            else if (!isLegacyUnicast)
            {
                client?.SendAsync(msg, remoteEndPoint.Address).GetAwaiter().GetResult();
            }

            // Unicast response
            if (isLegacyUnicast && remoteEndPoint != null)
            {
                var unicastClient = (remoteEndPoint.Address.AddressFamily == AddressFamily.InterNetwork)
                    ? unicastClientIp4 : unicastClientIp6;
                unicastClient.SendAsync(packet, packet.Length, remoteEndPoint).GetAwaiter().GetResult();
            }
        }
        public async Task DuplicateCheck()
        {
            var r = new RecentMessages {
                Interval = TimeSpan.FromMilliseconds(100)
            };
            var a = new byte[] { 1 };
            var b = new byte[] { 2 };

            Assert.IsTrue(r.TryAdd(a));
            Assert.IsTrue(r.TryAdd(b));
            Assert.IsFalse(r.TryAdd(a));

            await Task.Delay(200);

            Assert.IsTrue(r.TryAdd(a));
        }
Exemple #4
0
        /// <summary>
        ///   Called by the MulticastClient when a DNS message is received.
        /// </summary>
        /// <param name="sender">
        ///   The <see cref="MulticastClient"/> that got the message.
        /// </param>
        /// <param name="result">
        ///   The received message <see cref="UdpReceiveResult"/>.
        /// </param>
        /// <remarks>
        ///   Decodes the <paramref name="result"/> and then raises
        ///   either the <see cref="QueryReceived"/> or <see cref="AnswerReceived"/> event.
        ///   <para>
        ///   Multicast DNS messages received with an OPCODE or RCODE other than zero
        ///   are silently ignored.
        ///   </para>
        ///   <para>
        ///   If the message cannot be decoded, then the <see cref="MalformedMessage"/>
        ///   event is raised.
        ///   </para>
        /// </remarks>
        public void OnDnsMessage(object sender, UdpReceiveResult result)
        {
            // If recently received, then ignore.
            // A message has been recently received, if its content, as well as the remote endpoint(!) match, otherwise messages from different senders can be considered equal.
            var receivedMessage = new byte[result.Buffer.Length + result.RemoteEndPoint.Address.GetAddressBytes().Length];

            result.Buffer.CopyTo(receivedMessage, 0);
            result.RemoteEndPoint.Address.GetAddressBytes().CopyTo(receivedMessage, result.Buffer.Length);

            if (IgnoreDuplicateMessages && !receivedMessages.TryAdd(receivedMessage))
            {
                // Not continuing here because it looks like a duplicate message
                return;
            }

            var msg = new Message();

            try
            {
                msg.Read(result.Buffer, 0, result.Buffer.Length);
            }
            catch (Exception e)
            {
                log.Warn("Received malformed message", e);
                MalformedMessage?.Invoke(this, result.Buffer);
                return; // eat the exception
            }

            if (msg.Opcode != MessageOperation.Query || msg.Status != MessageStatus.NoError)
            {
                return;
            }

            // Dispatch the message.
            try
            {
                if (msg.IsQuery && msg.Questions.Count > 0)
                {
                    QueryReceived?.Invoke(this, new MessageEventArgs {
                        Message = msg, RemoteEndPoint = result.RemoteEndPoint
                    });
                }
                else if (msg.IsResponse && msg.Answers.Count > 0)
                {
                    AnswerReceived?.Invoke(this, new MessageEventArgs {
                        Message = msg, RemoteEndPoint = result.RemoteEndPoint
                    });
                }
            }
            catch (Exception e)
            {
                log.Error("Receive handler failed", e);
                // eat the exception
            }
        }
Exemple #5
0
        /// <summary>
        ///   Called by the MulticastClient when a DNS message is received.
        /// </summary>
        /// <param name="sender">
        ///   The <see cref="MulticastClient"/> that got the message.
        /// </param>
        /// <param name="result">
        ///   The received message <see cref="UdpReceiveResult"/>.
        /// </param>
        /// <remarks>
        ///   Decodes the <paramref name="result"/> and then raises
        ///   either the <see cref="QueryReceived"/> or <see cref="AnswerReceived"/> event.
        ///   <para>
        ///   Multicast DNS messages received with an OPCODE or RCODE other than zero
        ///   are silently ignored.
        ///   </para>
        ///   <para>
        ///   If the message cannot be decoded, then the <see cref="MalformedMessage"/>
        ///   event is raised.
        ///   </para>
        /// </remarks>
        public void OnDnsMessage(object sender, UdpReceiveResult result)
        {
            // If recently received, then ignore.
            if (!receivedMessages.TryAdd(result.Buffer))
            {
                return;
            }

            var msg = new Message();

            try
            {
                msg.Read(result.Buffer, 0, result.Buffer.Length);
            }
            catch (Exception e)
            {
                log.Warn("Received malformed message", e);
                MalformedMessage?.Invoke(this, result.Buffer);
                return; // eat the exception
            }

            if (msg.Opcode != MessageOperation.Query || msg.Status != MessageStatus.NoError)
            {
                return;
            }

            // Dispatch the message.
            try
            {
                if (msg.IsQuery && msg.Questions.Count > 0)
                {
                    QueryReceived?.Invoke(this, new MessageEventArgs {
                        Message = msg, RemoteEndPoint = result.RemoteEndPoint
                    });
                }
                else if (msg.IsResponse && msg.Answers.Count > 0)
                {
                    AnswerReceived?.Invoke(this, new MessageEventArgs {
                        Message = msg, RemoteEndPoint = result.RemoteEndPoint
                    });
                }
            }
            catch (Exception e)
            {
                log.Error("Receive handler failed", e);
                // eat the exception
            }
        }
Exemple #6
0
        void Send(Message msg, bool checkDuplicate)
        {
            var packet = msg.ToByteArray();

            if (packet.Length > maxPacketSize)
            {
                throw new ArgumentOutOfRangeException($"Exceeds max packet size of {maxPacketSize}.");
            }

            if (checkDuplicate && !sentMessages.TryAdd(packet))
            {
                return;
            }

            client.SendAsync(packet).GetAwaiter().GetResult();
        }