15 March, 2012

Check Network/Internet Connection Using C#


To check for a network connection in .NET use this:
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
To monitor a change in IP address or a change in network availability, use the events from the NetworkChange class:
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged

System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged
For Example.......................................................................

using System.Net.NetworkInformation;

Call following function............

public void CheckInternet()
{
        if(NetworkInterface.GetIsNetworkAvailable())
                Console.Write("Network connected!\n");
        else
                Console.Write("Network disconnected!\n");           
}

public void IsConnectedToInternet()
{
        string host = "http://www.google.com";
        bool result = false;
        Ping p = new Ping();
            try
            {
                PingReply reply = p.Send(host, 3000);
                if (reply.Status == IPStatus.Success)
                    result=true;
            }
            catch {
            }
           
        if (result==true)
                Console.Write("Internet connected!\n");
        else
                Console.Write("Internet disconnected!\n");  
 }

No comments:

Post a Comment