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;
}
}