Example #1
0
        /// <summary>
        ///   Stop the service.
        /// </summary>
        /// <remarks>
        ///   Clears all the event handlers.
        /// </remarks>
        public void Stop()
        {
            // All event handlers are cleared.
            QueryReceived              = null;
            AnswerReceived             = null;
            NetworkInterfaceDiscovered = null;

            // Stop current UDP listener
            client?.Dispose();
            client = null;
        }
Example #2
0
        void FindNetworkInterfaces()
        {
            log.Debug("Finding network interfaces");

            try
            {
                var currentNics = GetLinkLocalAddresses().ToList();

                var newNics = new List <IPAddress>();
                var oldNics = new List <IPAddress>();

                foreach (var nic in knownIPs?.Where(k => !currentNics.Any(n => k.Equals(n))))
                {
                    oldNics.Add(nic);

                    if (log.IsDebugEnabled)
                    {
                        log.Debug($"Removed ip '{nic}'.");
                    }
                }

                foreach (var nic in currentNics.Where(nic => !knownIPs.Any(k => k.Equals(nic))))
                {
                    newNics.Add(nic);

                    if (log.IsDebugEnabled)
                    {
                        log.Debug($"Found ip '{nic}'.");
                    }
                }

                knownIPs = currentNics;

                // Only create client if something has changed.
                if (newNics.Any() || oldNics.Any())
                {
                    client?.Dispose();
                    client = new MulticastClient(UseIpv4, UseIpv6, knownIPs);
                    client.MessageReceived += OnDnsMessage;
                }

                // Tell others.
                if (newNics.Any())
                {
                    NetworkInterfaceDiscovered?.Invoke(this, new IPEventArgs
                    {
                        NetworkInterfaces = newNics
                    });
                }

                // Magic from @eshvatskyi
                //
                // I've seen situation when NetworkAddressChanged is not triggered
                // (wifi off, but NIC is not disabled, wifi - on, NIC was not changed
                // so no event). Rebinding fixes this.
                //
                // Do magic only on Windows.
#if NET461
                if (Environment.OSVersion.Platform.ToString().StartsWith("Win"))
#else
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
#endif
                {
                    NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;
                    NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
                }
            }
            catch (Exception e)
            {
                log.Error("FindNics failed", e);
            }
        }