Some times you'll need a mechanism to check whether changes to network occurring during running your application.
So as a solution for this you can add handlers to the static networkaddresschanged and networkavailabilitychanged Events implemented by theSystem.Net.NetworkInformation.NetworkChange class.
Souce Code:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Net.NetworkInformation;
Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
ADD the handlers to the NetworkChange events.
Networkchange.networkavailabilitychanged + =
networkavailabilitychanged;
Networkchange.networkaddresschanged + =
networkaddresschanged;
Console.ReadLine ();
}
Declare a method to handle networkavailabilitychanged events.
private static void NetworkAvailabilityChanged (
Object sender, Networkavailabilityeventargs e)
{
Report whether the network was now available or unavailable.
if (e.isavailable)
{
Console.WriteLine ("Network Available");
}
Else
{
Console.WriteLine ("Network unavailable");
}
}
Declare a method to handle networkadresschanged events.
private static void Networkaddresschanged (object sender, EventArgs e)
{
Console.WriteLine ("Current IP Addresses:");
Iterate through the interfaces and display information.
foreach (NetworkInterface ni in
Networkinterface.getallnetworkinterfaces ())
{
foreach (Unicastipaddressinformation addr
In NI. Getipproperties (). unicastaddresses)
{
Console.WriteLine ("-{0} (lease expires {1})",
Addr. Address, DateTime.Now +
New TimeSpan (0, 0, (int) addr. Dhcpleaselifetime));
}
}
}
}
}
Http://www.codeproject.com/Articles/206720/Simple-Network-Status-Monitor-Example
Detect changes in Network Connectivity