Detect changes in Network Connectivity

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.