private static void AddressChangedCallback(object stateObject, bool signaled) { lock (s_callerArray) { s_isPending = false; if (s_isListening) { s_isListening = false; DictionaryEntry[] array = new DictionaryEntry[s_callerArray.Count]; s_callerArray.CopyTo(array, 0); StartHelper(null, false, (StartIPOptions)stateObject); for (int i = 0; i < array.Length; i++) { NetworkAddressChangedEventHandler key = (NetworkAddressChangedEventHandler)array[i].Key; ExecutionContext context = (ExecutionContext)array[i].Value; if (context == null) { key(null, EventArgs.Empty); } else { ExecutionContext.Run(context.CreateCopy(), s_runHandlerCallback, key); } } } } }
public IObservable <NetworkReachability> WhenStatusChanged() { this.statusOb = this.statusOb ?? Observable.Create <NetworkReachability>(async ob => { var current = await this.IsReachable(); ob.OnNext(current ? NetworkReachability.Other : NetworkReachability.NotReachable); var handler = new NetworkAddressChangedEventHandler(async(sender, args) => { var reachable = await this.IsReachable(); if (current != reachable) { current = reachable; ob.OnNext(current ? NetworkReachability.Other : NetworkReachability.NotReachable); } }); NetworkChange.NetworkAddressChanged += handler; return(() => NetworkChange.NetworkAddressChanged -= handler); }) .Replay(1) .RefCount(); return(this.statusOb); }
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 public void NetworkAddressChanged_AddRemove_Success() { NetworkAddressChangedEventHandler handler = NetworkChange_NetworkAddressChanged; NetworkChange.NetworkAddressChanged += handler; NetworkChange.NetworkAddressChanged -= handler; }
private static void OnAddressChanged() { Dictionary <NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null; lock (s_gate) { if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary <NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers); } } if (addressChangedSubscribers != null) { foreach (KeyValuePair <NetworkAddressChangedEventHandler, ExecutionContext> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } }
void Unregister(NetworkAddressChangedEventHandler d) { lock (_lock) { AddressChanged -= d; MaybeCloseSocket(); } }
private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr info) { Dictionary <NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null; Dictionary <NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null; lock (s_lockObj) { if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary <NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers); } if (s_availabilityChangedSubscribers.Count > 0) { availabilityChangedSubscribers = new Dictionary <NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityChangedSubscribers); } } if (addressChangedSubscribers != null) { foreach (KeyValuePair <NetworkAddressChangedEventHandler, ExecutionContext> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } if (availabilityChangedSubscribers != null) { bool isAvailable = NetworkInterface.GetIsNetworkAvailable(); NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable; foreach (KeyValuePair <NetworkAvailabilityChangedEventHandler, ExecutionContext> subscriber in availabilityChangedSubscribers) { NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, args); } else { ExecutionContext.Run(ec, callbackContext, handler); } } } }
private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr info) { NetworkAddressChangedEventHandler handler = s_addressChangedSubscribers; if (handler != null) { handler(null, EventArgs.Empty); } }
void OnAddressChanged(object unused) { NetworkAddressChangedEventHandler d = AddressChanged; if (d != null) { d(null, EventArgs.Empty); } }
/// <summary> /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed. /// <example> /// networkaddresschangedeventhandler.BeginInvoke(sender, e, callback); /// </example> /// </summary> public static IAsyncResult BeginInvoke(this NetworkAddressChangedEventHandler networkaddresschangedeventhandler, Object sender, EventArgs e, AsyncCallback callback) { if (networkaddresschangedeventhandler == null) { throw new ArgumentNullException("networkaddresschangedeventhandler"); } return(networkaddresschangedeventhandler.BeginInvoke(sender, e, callback, null)); }
// Callback fired when an address change occurs. private static void AddressChangedCallback(object?stateObject, bool signaled) { Dictionary <NetworkAddressChangedEventHandler, ExecutionContext?>?addressChangedSubscribers = null; lock (s_globalLock) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary <NetworkAddressChangedEventHandler, ExecutionContext?>(s_addressChangedSubscribers); } try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject !); } catch (NetworkInformationException nie) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Error(null, nie); } } } // Release the lock before calling into user callback. if (addressChangedSubscribers != null) { foreach (KeyValuePair <NetworkAddressChangedEventHandler, ExecutionContext?> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext?ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } }
protected override void OnStart(string[] args) { Program.Log("Starting the service"); Debug.Assert(ServiceImplInstance == null); ServiceImplInstance = new ServiceImpl(); AddressChangeHandler = new NetworkAddressChangedEventHandler(AddressChangedCallback); NetworkChange.NetworkAddressChanged += AddressChangeHandler; Program.Log("Performing initial config"); ReloadConfiguration(); Program.Log("Service is started"); }
internal static void Stop(NetworkAddressChangedEventHandler caller) { lock (s_callerArray) { s_callerArray.Remove(caller); if (s_callerArray.Count == 0 && s_isListening) { s_isListening = false; } } }
// Callback fired when an address change occurs. private static void AddressChangedCallback(object stateObject, bool signaled) { Dictionary <NetworkAddressChangedEventHandler, ExecutionContext> copy; lock (s_globalLock) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop copy = new Dictionary <NetworkAddressChangedEventHandler, ExecutionContext>(s_callerArray); try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (NetEventSource.IsEnabled) { NetEventSource.Error(null, nie); } } } // Release the lock before calling into user callback. if (copy.Count > 0) { foreach (var entry in copy) { NetworkAddressChangedEventHandler handler = entry.Key; ExecutionContext context = entry.Value; if (context == null) { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(context, s_runHandlerCallback, handler); } } } }
public NetInfo(IExceptionHandler exceptionhandler) { updating = new Object(); this.exceptionhandler = exceptionhandler; wmisession = WmiBase.Singleton.GetXenStoreSession("Adapters"); devicevif = wmisession.GetXenStoreItem("device/vif"); datavif = wmisession.GetXenStoreItem("data/vif"); numvif = wmisession.GetXenStoreItem("data/num_vif"); needsRefresh = true; onAddrChange(null, null); addrChangeHandler = new NetworkAddressChangedEventHandler(onAddrChange); NetworkChange.NetworkAddressChanged += addrChangeHandler; vifListen = devicevif.Watch(onVifChanged); }
private static void OnSocketEvent(Interop.Sys.NetworkChangeKind kind) { switch (kind) { case Interop.Sys.NetworkChangeKind.AddressAdded: case Interop.Sys.NetworkChangeKind.AddressRemoved: NetworkAddressChangedEventHandler handler = s_addressChangedSubscribers; if (handler != null) { handler(null, EventArgs.Empty); } break; } }
internal static void Stop(NetworkAddressChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_addressChangedSubscribers.Remove(caller); if (s_addressChangedSubscribers.Count == 0 && s_isListening) { s_isListening = false; } } } }
/// <summary>Disposes of the pools, disposing of each individual pool.</summary> public void Dispose() { _cleaningTimer?.Dispose(); foreach (KeyValuePair <HttpConnectionKey, HttpConnectionPool> pool in _pools) { pool.Value.Dispose(); } if (_networkChangedDelegate != null) { NetworkChange.NetworkAddressChanged -= _networkChangedDelegate; _networkChangedDelegate = null; } }
static void StateChangedCallback(IntPtr sender, IntPtr data) { try { NetworkAddressChangedEventHandler h = NetworkAddressChanged; if (h != null) { h(null, EventArgs.Empty); } } catch (Exception ex) { try { Console.WriteLine("Unhandled exception: {0}", ex); } catch { // Ignore } } }
public NetworkManager(AddInManager addInManager) { this.addInManager = addInManager; networkChangedHandler = new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged); NetworkChange.NetworkAddressChanged += networkChangedHandler; powerModeChangedHandler = new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged); SystemEvents.PowerModeChanged += powerModeChangedHandler; if (Windows7Helper.IsWindows7) { locationManager = LocationManager.Instance; locationManager.NewLocationAvailable += new EventHandler(locationManager_NewLocationAvailable); } }
//callback fired when an address change occurs private static void AddressChangedCallback(object stateObject, bool signaled) { lock (s_callerArray) { //the listener was cancelled, which would only happen if we aren't listening //for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop DictionaryEntry[] callerArray = new DictionaryEntry[s_callerArray.Count]; s_callerArray.CopyTo(callerArray, 0); try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (Logging.On) { Logging.Exception(Logging.Web, "AddressChangeListener", "AddressChangedCallback", nie); } } for (int i = 0; i < callerArray.Length; i++) { NetworkAddressChangedEventHandler handler = (NetworkAddressChangedEventHandler)callerArray[i].Key; ExecutionContext context = (ExecutionContext)callerArray[i].Value; if (context == null) { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(context.CreateCopy(), s_runHandlerCallback, handler); } } } }
/// <summary> /// Starts monitoring for network changes. Upon a change, <see cref="HttpConnectionPool.OnNetworkChanged"/> will be /// called for every <see cref="HttpConnectionPool"/> in the <see cref="HttpConnectionPoolManager"/>. /// </summary> public void StartMonitoringNetworkChanges() { if (_networkChangeCleanup != null) { return; } // Monitor network changes to invalidate Alt-Svc headers. // A weak reference is used to avoid NetworkChange.NetworkAddressChanged keeping a non-disposed connection pool alive. var poolsRef = new WeakReference <ConcurrentDictionary <HttpConnectionKey, HttpConnectionPool> >(_pools); NetworkAddressChangedEventHandler networkChangedDelegate = delegate { if (poolsRef.TryGetTarget(out ConcurrentDictionary <HttpConnectionKey, HttpConnectionPool>?pools)) { foreach (HttpConnectionPool pool in pools.Values) { pool.OnNetworkChanged(); } } }; var cleanup = new NetworkChangeCleanup(networkChangedDelegate); if (Interlocked.CompareExchange(ref _networkChangeCleanup, cleanup, null) != null) { // We lost a race, another thread already started monitoring. GC.SuppressFinalize(cleanup); return; } if (!ExecutionContext.IsFlowSuppressed()) { using (ExecutionContext.SuppressFlow()) { NetworkChange.NetworkAddressChanged += networkChangedDelegate; } } else { NetworkChange.NetworkAddressChanged += networkChangedDelegate; } }
internal static void Start(NetworkAvailabilityChangedEventHandler caller) { lock (syncObject) { if (s_availabilityCallerArray == null) { s_availabilityCallerArray = new ListDictionary(); addressChange = new NetworkAddressChangedEventHandler(NetworkChange.AvailabilityChangeListener.ChangedAddress); } if (s_availabilityCallerArray.Count == 0) { isAvailable = NetworkInterface.GetIsNetworkAvailable(); NetworkChange.AddressChangeListener.UnsafeStart(addressChange); } if ((caller != null) && !s_availabilityCallerArray.Contains(caller)) { s_availabilityCallerArray.Add(caller, ExecutionContext.Capture()); } } }
/// <summary> /// Constructor of the NetInfo class /// </summary> /// <param name="exceptionhandler">The exception handler, trigger when exception occurs</param> /// <param name="devicePath"> xenstore device path of NIC device</param> /// <param name="attrPath"> xenstore path NIC device data info report back to</param> /// <param name="session"> wmi session, mainly used to access xenstore</param> public NetInfo(IExceptionHandler exceptionhandler, string devicePath, string attrPath, AWmiSession session) { wmisession = session; this.exceptionhandler = exceptionhandler; updating = new Object(); this.devicePath = devicePath; this.attrPath = attrPath; netDeviceItem = wmisession.GetXenStoreItem(devicePath); netAttrItem = wmisession.GetXenStoreItem(attrPath); netDeviceItem.Watch(onXenstoreNetChanged); addrChangeHandler = new NetworkAddressChangedEventHandler(onVmNicAddrChange); NetworkChange.NetworkAddressChanged += addrChangeHandler; netStaticIpSetting = wmisession.GetXenStoreItem(STATIC_IP_FEATURE_MONITOR_KEY); netStaticIpSetting.Watch(onXenstoreStaticIpSettingChanged); // trigger the first update needsRefresh = true; }
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_callerArray) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { int blocking; // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { blocking = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if (Socket.OSSupportsIPv6) { blocking = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } if ((caller != null) && (!s_callerArray.ContainsKey(caller))) { s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null); } if (s_isListening || s_callerArray.Count == 0) { return; } if (!s_isPending) { int length; SocketError errorCode; if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, SafeNativeOverlapped.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle = s_ipv4Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket, s_ipv4SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, SafeNativeOverlapped.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle = s_ipv6Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket, s_ipv6SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } }
internal static void UnsafeStart(NetworkAddressChangedEventHandler caller) { StartHelper(caller, false, StartIPOptions.Both); }
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_callerArray) { // setup changedEvent and native overlapped struct. if(s_ipv4Socket == null){ Socket.InitializeSockets(); int blocking; if(Socket.OSSupportsIPv4){ blocking = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false); UnsafeNclNativeMethods.OSSOCK.ioctlsocket(s_ipv4Socket, IoctlSocketConstants.FIONBIO,ref blocking); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if(Socket.OSSupportsIPv6){ blocking = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false); UnsafeNclNativeMethods.OSSOCK.ioctlsocket(s_ipv6Socket,IoctlSocketConstants.FIONBIO,ref blocking); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } if ((caller != null) && (!s_callerArray.Contains(caller))) { s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null); } //if s_listener is not null, it means we are already actively listening if (s_isListening || s_callerArray.Count == 0) { return; } if(!s_isPending){ int length; SocketError errorCode; if(Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) !=0){ s_registeredWait = ThreadPool.UnsafeRegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true ); errorCode = (SocketError) UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking( s_ipv4Socket.DangerousGetHandle(), (int) IOControlCode.AddressListChange, null, 0, null, 0, out length, SafeNativeOverlapped.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(s_ipv4Socket, s_ipv4Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if(Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) !=0){ s_registeredWait = ThreadPool.UnsafeRegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true ); errorCode = (SocketError) UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking( s_ipv6Socket.DangerousGetHandle(), (int) IOControlCode.AddressListChange, null, 0, null, 0, out length, SafeNativeOverlapped.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } errorCode = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(s_ipv6Socket, s_ipv6Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } }
public void AddAddressChangedEventHandler(NetworkAddressChangedEventHandler handler) { this.OnAddAddressChangedEventHandler(handler); }
public void RemoveAddressChangeEventHandler(NetworkAddressChangedEventHandler handler) { this.OnRemoveAddressChangedEventHandler(handler); }
void Unregister (NetworkAddressChangedEventHandler d) { lock (_lock) { AddressChanged -= d; MaybeCloseSocket (); } }
void Register (NetworkAddressChangedEventHandler d) { EnsureSocket (); AddressChanged += d; }
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_callerArray) { if (s_ipv4Socket == null) { int num; Socket.InitializeSockets(); if (Socket.OSSupportsIPv4) { num = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP, true, false); UnsafeNclNativeMethods.OSSOCK.ioctlsocket(s_ipv4Socket, -2147195266, ref num); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if (Socket.OSSupportsIPv6) { num = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.IP, true, false); UnsafeNclNativeMethods.OSSOCK.ioctlsocket(s_ipv6Socket, -2147195266, ref num); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } if ((caller != null) && !s_callerArray.Contains(caller)) { s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null); } if (!s_isListening && (s_callerArray.Count != 0)) { if (!s_isPending) { int num2; if (Socket.OSSupportsIPv4 && ((startIPOptions & StartIPOptions.StartIPv4) != StartIPOptions.None)) { s_registeredWait = ThreadPool.UnsafeRegisterWaitForSingleObject(s_ipv4WaitHandle, new WaitOrTimerCallback(NetworkChange.AddressChangeListener.AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); if (UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(s_ipv4Socket.DangerousGetHandle(), 0x28000017, null, 0, null, 0, out num2, SafeNativeOverlapped.Zero, IntPtr.Zero) != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != 0x2733L) { throw exception; } } if (UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(s_ipv4Socket, s_ipv4Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange) != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && ((startIPOptions & StartIPOptions.StartIPv6) != StartIPOptions.None)) { s_registeredWait = ThreadPool.UnsafeRegisterWaitForSingleObject(s_ipv6WaitHandle, new WaitOrTimerCallback(NetworkChange.AddressChangeListener.AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); if (UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(s_ipv6Socket.DangerousGetHandle(), 0x28000017, null, 0, null, 0, out num2, SafeNativeOverlapped.Zero, IntPtr.Zero) != SocketError.Success) { NetworkInformationException exception2 = new NetworkInformationException(); if (exception2.ErrorCode != 0x2733L) { throw exception2; } } if (UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(s_ipv6Socket, s_ipv6Socket.GetEventHandle().SafeWaitHandle, AsyncEventBits.FdAddressListChange) != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } } }
public StubNetwork() { this.OnAddAddressChangedEventHandler = handler => this.addressChanged += handler; this.OnRemoveAddressChangedEventHandler = handler => this.addressChanged -= handler; }
void Register(NetworkAddressChangedEventHandler d) { EnsureSocket(); AddressChanged += d; }
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_globalLock) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0) { Blocking = false }; s_ipv4WaitHandle = new AutoResetEvent(false); } if (Socket.OSSupportsIPv6) { s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, 0) { Blocking = false }; s_ipv6WaitHandle = new AutoResetEvent(false); } } if (caller != null) { s_addressChangedSubscribers.TryAdd(caller, captureContext ? ExecutionContext.Capture() : null); } if (s_isListening || s_addressChangedSubscribers.Count == 0) { return; } if (!s_isPending) { if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.Handle, (int)IOControlCode.AddressListChange, null, 0, null, 0, out int length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket.SafeHandle, s_ipv4WaitHandle.GetSafeWaitHandle(), Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.Handle, (int)IOControlCode.AddressListChange, null, 0, null, 0, out int length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket.SafeHandle, s_ipv6WaitHandle.GetSafeWaitHandle(), Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } }
public void AddAddressChangedEventHandler(NetworkAddressChangedEventHandler handler) { NetworkChange.NetworkAddressChanged += handler; }
public NetworkChangeCleanup(NetworkAddressChangedEventHandler handler) { _handler = handler; }
public void RemoveAddressChangeEventHandler(NetworkAddressChangedEventHandler handler) { NetworkChange.NetworkAddressChanged -= handler; }