Deprecated: Function set_magic_quotes_runtime() is deprecated in /customers/jogear.net/jogear.net/httpd.www/textpattern/lib/txplib_db.php on line 14
jogear.net: Checking Connectivity With .NET CF
Skip to Content »

 Checking Connectivity With .NET CF

  • 2009-05-04 11:30

This is from the MSDN Tips and Tricks webcast of January 12, 2005. Slightly rewritten and completely untested. Just for reference.

enum ConnectionStatus
{
    Offline,
    OnlineTargetNotFound,
    OnlineTargetFound,
}

ConnectionStatus GetConnectionStatus(String url)
{
    try
    {
        //
        // If the device is set to loopback, then no connection exists.
        //
        String hostName = System.Net.Dns.GetHostName();
        System.Net.IPHostEntry host = System.Net.Dns.GetHostByName(hostName);
        String ipAddress = host.AddressList.ToString();

        if(ipAddress == System.Net.IPAddress.Parse("127.0.0.1").ToString())
        {
            return ConnectionStatus.Offline;
        }

        //
        // Now we know we're online. Use a web request and check
        // for a response to see if the target can be found or not.
        // N.B. There are blocking calls here.
        //
        System.Net.WebResponse webResponse = null;
        try
        {
            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);
            webRequest.Timeout = 10000;
            webResponse = webRequest.GetResponse();

            return ConnectionStatus.OnlineTargetFound;
        }
        catch(Exception)
        {
            return ConnectionStatus.OnlineTargetNotFound;
        }
    }
    catch(Exception)
    {
        return ConnectionStatus.Offline;
    }
}