Thursday, July 8, 2010

Check Internet Connectivity

How to check is your PC/ Server is connected to the internet.... there are more than one ways to do that - using wininet.dll, calling for DNS resolution, pinging a internet server, calling a web page and checking for response status and as I wanted to be sure that client is able to reach my server so put them all together.

First bit is thanks to Rydal.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Text;
using System.Security;

namepsace TestCode {
public sealed class NetworkHandler {
///
/// Private constructor to prevent compiler from generating one
/// since this class only holds static methods and properties
///

NetworkHandler() { }
///
/// SafeNativeMethods Class that holds save native methods
/// while suppressing unmanaged code security
///

[SuppressUnmanagedCodeSecurityAttribute]
internal static class SafeNativeMethods {
// Extern Library
// UnManaged code - be careful.
[DllImport("wininet.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
///
/// Determines if there is an active connection on this computer
///

///
public static bool HasActiveConnection() {
int desc;
return InternetGetConnectedState(out desc, 0);
}
}
}
}

and the function to check the connectivity
 
#region checkConnectivity
public bool CheckInternetConnection() {
bool isInternetOn = false;
isInternetOn = NetworkHandler.SafeNativeMethods.HasActiveConnection();
if(isInternetOn) {
try {
IPHostEntry obj = Dns.GetHostEntry(strServer);
isInternetOn = true;
} catch {
isInternetOn = false; // host not reachable.
}
}
if(isInternetOn) {
try {
HttpWebRequest reqFP = (HttpWebRequest) HttpWebRequest.Create(strServer);
HttpWebResponse rspFP = (HttpWebResponse) reqFP.GetResponse();
if(HttpStatusCode.OK == rspFP.StatusCode) {
// HTTP = 200 - Internet connection available, server online
rspFP.Close();
isInternetOn = true;
} else {
// Other status - Server or connection not available
rspFP.Close();
isInternetOn = false; // host not reachable.
}
} catch(WebException) {
// Exception - connection not available
isInternetOn = false; // host not reachable.
}
}
return isInternetOn;
}
#endregion

No comments:

Post a Comment