none
How to check internet connectivity RRS feed

  • Question

  • Hi,

    I used this code to check connection status in a for loop:

    WebRequest w = WebRequest.Create("http://www.google.com");
    w.Credentials = CredentialCache.DefaultNetworkCredentials;
    HttpWebResponse response = (HttpWebResponse)w.GetResponse();
    string gg = response.StatusCode.ToString();
    Console.WriteLine(gg);

    but after the second round it stopped working. why?

    Is there any other way to check internet connectivity?

    thanks; 


    Mahd!

    Wednesday, September 19, 2012 6:59 PM

Answers

  • The connection is still open and you can only have one connection with the same set of source IP address, destination IP address, and port number.  Simple solution.  Close the connection between calls, or don't create a new connection evvery time you do the test.  One use tthe create the first time you make the test.


    jdweng

    • Marked as answer by Mahdijalilvand Thursday, September 20, 2012 7:59 AM
    Wednesday, September 19, 2012 9:33 PM

All replies

  • The connection is still open and you can only have one connection with the same set of source IP address, destination IP address, and port number.  Simple solution.  Close the connection between calls, or don't create a new connection evvery time you do the test.  One use tthe create the first time you make the test.


    jdweng

    • Marked as answer by Mahdijalilvand Thursday, September 20, 2012 7:59 AM
    Wednesday, September 19, 2012 9:33 PM
  • Why do you use WebRequest to check connectivity. You can use below API for that,

    System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

    hope this helps.

    Please mark this post as answer if it solved your problem. Happy Programming!


    • Edited by Adavesh Thursday, September 20, 2012 4:19 AM
    Thursday, September 20, 2012 4:18 AM
  • HiMahd,

    NetworkInterface.GetIsNetworkAvailable(), described in the article (which only tests if the network is available; not the Internet, directly), eventually uses wininet.dll's InternetGetConnectedState() which can be PInvoked as follows:

    [DllImport("wininet.dll")]
    internal static extern bool InternetGetConnectedState(ref uint flags, uint dwReserved);
     
    uint num1 = 0;
    Boolean isNetworkConnected = 
     UnsafeWinINetNativeMethods.InternetGetConnectedState(ref num1, 0);


    Regards, http://www.shwetalodha.blogspot.in/

    Thursday, September 20, 2012 5:01 AM
  • Thanks for the clue you've given me. I'm using this line and it's working:

    w.GetResponse().Close();


    Mahd!

    Thursday, September 20, 2012 8:01 AM