0

I wrote this function to check if an internet connection is available:

    bool IsOnline()
    {
        try
        {
            var request = (HttpWebRequest)WebRequest.CreateHttp("http://www.google.com/");
            request.Timeout = 2000;

            var response = (HttpWebResponse)request.GetResponse();
            return ((int)response.StatusCode) < 400;
        }
        catch (Exception) { return false; }      
    }

It seems to work in almost all cases however under my work network it return false after a timeout error while the connection is available.

Note: - this function return false but I can go online with a webbrowser component in my WPF application - the connection is pretty good. (so it is impossible to spend more than 2sec in loading google.com) - I'm behind a proxy configured correctly in Control Panel/Internet Options/Connection

Any ideas?

Roberto
  • 504
  • 11
  • 23
  • pls see this answer.. http://stackoverflow.com/questions/749311/httpwebrequest-one-proxy-and-one-not and also this http://stackoverflow.com/questions/1155363/how-to-autodetect-use-ie-proxy-settings-in-net-httpwebrequest – Amitd Dec 03 '12 at 16:10
  • they said that by default IE proxy is used so it should work in my case but it doesn't – Roberto Dec 03 '12 at 16:16
  • Is there a corporate firewall at your work place ? Check the response object for ResponseUri and Statuscode property – Amitd Dec 03 '12 at 16:22
  • Yes. I'm behind a corporate firewall, but the other applications that I installed on my pc can connect to the internet. – Roberto Dec 03 '12 at 16:37
  • I cannot read response status because I get a Timeout exception – Roberto Dec 03 '12 at 16:37
  • How do you know it is a timeout exception? In the code you post you are not checking the exception. – paparazzo Dec 03 '12 at 16:49
  • @Blam I edit the code in order to read the exception. It is a System.Net.WebException with message "The operation has timed out" – Roberto Dec 03 '12 at 16:57

2 Answers2

0

in regular cases 407 means you have a proxy blocking you... although it does not generates a time out... its a "fast" reply and not even considered a exception...

try this:

            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.Proxy = new WebProxy("PROXY ip HERE", true, null, System.Net.CredentialCache.DefaultNetworkCredentials);                

            HttpClient cli = new HttpClient(clientHandler);

            cli.BaseAddress = new Uri("http://google.com");

            HttpResponseMessage response = cli.GetAsync("").Result;  // Blocking call!

            textBox1.Text = response.Content.ReadAsStringAsync().Result;

btw this uses Web API...

edit: becaerfull! error 401 (unautorized), 500 (internal server error) are bigger than 400 and does not in any way represent absense of connectivity!!!

Leonardo
  • 10,737
  • 10
  • 62
  • 155
  • It works! and it works also the function that I posted before if I set the proxy manually. But why it does not take the IE settings? – Roberto Dec 03 '12 at 16:49
  • well... i dont know... but i had to guess its because your creating a webrequest out of nothing, and this is kind of the expect behavior for me... its more logical than "myRequest.UseIEDefaults=false"... imho... pls dont forget to mark as answer if this solved your problem... – Leonardo Dec 03 '12 at 17:02
  • well.. I cannot hard-code my proxy address in the program. I need to use the IE one – Roberto Dec 03 '12 at 17:14
  • you can keep those settings in app.config http://ryanfarley.com/blog/archive/2004/07/13/879.aspx – Amitd Dec 03 '12 at 17:38
  • or, upon receiving a 407 you can prompt the user for the proxy settings... or auto-set... – Leonardo Dec 03 '12 at 18:08
  • That's the point.. how to auto-set. Documentation says that it should be automatical, but it isn't ..or I'm loosing something – Roberto Dec 04 '12 at 07:51
  • Ok I've understand the problem. WebRequest.GetSystemWebProxy(); has the right proxy address with the flag ByPassOnLocal set to true. Unfortunately www.google.com is interpreted as local. If I force through the debugger the flag to false than it works. Unfortunately it seems that there isn't any public method to set this flag – Roberto Dec 04 '12 at 08:43
  • if google.com is being reconized as local its because you said so! In the proxy settings there must be google.com on the bypass list... check it out and make sure to remove... – Leonardo Dec 04 '12 at 12:56
0

As workaround I changed my function in this way:

bool IsOnline()
{
    try
    {
        var request = (HttpWebRequest)WebRequest.CreateHttp("http://www.google.com/");
        request.Timeout = 2000;

        var registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", false);
        var proxy = (string)registry.GetValue("ProxyServer");
        var isProxyEnabled = (int)registry.GetValue("ProxyEnable");
        if (isProxyEnabled>0)
        {
            request.Proxy = new WebProxy(proxy, true, null, System.Net.CredentialCache.DefaultNetworkCredentials);
        }

        var response = (HttpWebResponse)request.GetResponse();
        return ((int)response.StatusCode) < 400;
    }
    catch (Exception) { return false; }      
}

If I try to use WebRequest.GetSystemWebProxy() I get a IWebProxy (WrappedWebProxy) that has the same settings as the one that I manually build but it does not work. It recognize all addresses as local also if I do not have check the "Bypass proxy server for local addresses".

Then if I change through the debugger the bypasslocal flag it works. It's so strange that looks like a bug.

Roberto
  • 504
  • 11
  • 23