Wednesday, October 18, 2006

Checking Network Connectivity


During my application i need to know if the network goes offline or is online.

How i do this is by using the handlers NetworkAddressChanged and NetworkAvailabilityChanged events implemented by the System.Net.NetworkInformation.NetworkChange class.

This NetworkChange class was introduced in .NET framework 2.0. It allows us to build logic in our applications that detect network changes and network availability.

Sample Code:

using System.Net.NetworkInformation;

//handlers
NetworkChange.NetworkAvailabilityChanged += NetworkAvailabilityChanged;
NetworkChange.NetworkAddressChanged += NetworkAddressChanged;

private static void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e){
--if(e.IsAvailable){
----//network is available
--} else{
----//network is down
--}
}

private static void NetworkAddressChanged(object sender, EventArgs e){
--foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()){
----//get the ip address using the property UnicastAddresses.Address
--}
}

No comments: