Showing posts with label network information. Show all posts
Showing posts with label network information. Show all posts

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
--}
}
Getting Local Network Information


So you want information regarding the local network adaptors and the local machines network configuration, use the static method System.Net.NetworkInformation.GetAllNetworkInterfaces. This returns objects of type NetworkInterface. The properties of the NetworkInterface object will unravel a rich set of information regarding network configuration and network statistics.

Sample Code:

using System.Net.NetworkInformation;


--if(NetworkInterface.GetIsNetworkAvailable()){

----NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

----foreach(NetworkInterface ni in interfaces){
------string NetworkName = ni.Name;
----}

--}