Forum Xamarin.Mac

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

NetworkAddressChanged not working

VRahikkaVRahikka Member ✭✭

Hi,

I'm trying to detect changes in the network adapters in Network Settings of macOS. But it seems that this event is never triggered when new network adapter appears or is disconnected. On Windows this works.

So my question is that am I using this event wrong and is there some other event that I should be listening instead.

Thanks!

Tagged:

Best Answer

Answers

  • ChrisHamonsChrisHamons USForum Administrator, Xamarin Team Xamurai

    You are much more likely to get actionable feedback if you provide a small sample / example code showing what API you are using and in what context.

  • VRahikkaVRahikka Member ✭✭
    using System.Net.NetworkInformation;
    private void OnNetworkAddressChanged(Object sender, EventArgs e)
            {
                lock (this._endpoints)
                {
                    var endpoints = this.FindEndpoints();
    
                    // first, remove disconnected devices
    
                    var endpointsToRemove = this._endpoints.Where(endpoint => !endpoints.Contains(endpoint)).ToArray();
                    Tracer.Verbose($"{endpointsToRemove.Length} adapters to remove");
    
                    foreach (var endpointToRemove in endpointsToRemove)
                    {
                        Tracer.Trace($"Removing adapter '{endpointToRemove}'");
                        this._endpoints.Remove(endpointToRemove);
                        this.OnDeviceDeleted(endpointToRemove.ToString());
                    }
    
                    // then, add connected devices
    
                    var endpointsToAdd = endpoints.Where(endpoint => !this._endpoints.Contains(endpoint)).ToArray();
                    Tracer.Verbose($"{endpointsToAdd.Length} adapters to add");
    
                    foreach (var endpointToAdd in endpointsToAdd)
                    {
                        Tracer.Trace($"Adding adapter '{endpointToAdd}'");
                        this._endpoints.Add(endpointToAdd);
                        this.OnDeviceCreated(endpointToAdd.ToString(), endpointToAdd);
                    }
                }
            }
    

    So what we are after is changes in the network adapter list. On Windows this works. When network adapter connects or disconnects OnNetworkAddressChanged-event is emmitted.

    On Mac this event is never emitted. Currently we have done it so that we just poll this function 5secs. It does the trick but it would be nicer to be able to utilize the event.

    Thanks!

Sign In or Register to comment.