1

Possible Duplicate:
check whether internet connection is available with C#

I just want to know which methods we have to use to detect programmatically (C#) if MS Windows has alive Internet/red connection or doesn't.

Is it possible to do?

Thank you!

For example: if I put down WIFI how I can know that there is any connection?

Community
  • 1
  • 1
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 1
    similar: http://stackoverflow.com/questions/2916243/detect-when-network-cable-unplugged –  Jul 06 '12 at 19:30
  • Also I found this answer which is also good! http://stackoverflow.com/questions/843810/fastest-way-to-test-internet-connection – NoWar Jul 06 '12 at 19:41

2 Answers2

2

Take a look at the Ping class

       Ping pingSender = new Ping ();
        PingOptions options = new PingOptions ();

        // Use the default Ttl value which is 128,
        // but change the fragmentation behavior.
        options.DontFragment = true;

        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes (data);
        int timeout = 120;
        PingReply reply = pingSender.Send ("www.google.com", timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine ("Address: {0}", reply.Address.ToString ());
            Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
        }
Micah Armantrout
  • 6,781
  • 4
  • 40
  • 66
0

I use the following method to check for connectivity:

public bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead("http://www.google.com"))
            {
                Console.WriteLine("You Have connectity!");
                return true;
            }
        }
        catch
        {
            Console.WriteLine("No internet connection found.");
            return false;
        }
    }

The method attempts to load Google's URL and returns true if it loads, false if it does not.

Robert H
  • 11,520
  • 18
  • 68
  • 110