Introduction

An application often needs to know if the machine has internet connectivity and take actions depending on that. In this sample, we are looking at the usage of the Windows NLM API in managed code so that an application can choose to respond to internet connectivity changes. There are many other specific NLM APIs for checking domain connectivity, network adapter interfaces etc., that haven't been mentioned in this article; you can refer to this link for further details. The downloadable zip file has the source code.

Using the code

For a managed code project, you need to reference the netprofm.dll in the \windows\system32\ directory. Here, m_nlm is a NetworkListManager COM object created to provide NLM functionalities. In the Main function, we can get an enumerator of all the networks and try to list their names one by one. You can use the API to list the properties of each network. Your machine might be connected to a free library hotspot, and it might also be connected to a corporate network via VPN or DirectAccess. In this case, there will be two networks listed, one with public internet access and the other with domain network access.

In the Main function, we also used AdviseforNetworklistManager to subscribe to any network connectivity changes for the machine, so that your ConnectivityChanged(NLM_CONNECTIVITY) method will be invoked if there is any network connectivity change. This is the method that you could use to take some actions if your machine gets connected to the internet. Before your application leaves the scene, you need to unsubscribe the event notifications about network connectivity changes. The event subscription method will find the connection point to get the INetworkListManager event as in the code below:

In ConnectivityChanged(NLM_CONNECTIVITY), we provide a sample to output the current machine's internet connectivity to the Console. Your app can take custom actions such as start downloading new data when connected to the internet etc.

You can use System.Net.NetworkInformation.NetworkChange to do the same.

Use the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged event to know if you are getting connected/disconnected. To know the current state use System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().

You can also use System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged event to know if your machine's address has changed.

Not true today.. The .net framework 3.5 uses the Winsock api to identify network adapter changes. In the future, the .net framework is likely to include the new Vista "Network Awareness" functionality using the Network List Manager API referenced in this article.