This is a mirror of official site: http://jasper-net.blogspot.com/

Ping.exe replica in C# 2.0

| Monday, February 14, 2011
Introduction
I've been working on an application that needed to connect to a webservice and exchange information with it. So before creating the proxy object, I needed to check if there is any internet connection on the client and if the webservice address can be reached. The easiest way was to call Ping.exe using the Process class and get my information from there, but it's dirty coding calling an external application for such a basic function, not to mention the security involving a call to a system component. Back in .NET Framework 1.0 or 1.1, there was no class to provide a Ping like utility; after searching in MSDN, I discovered that in C# 2.0, there is a new namespace called System.Net.NetworkInformation that has a Ping class.
So I've made a little 170 code lines console application to familiarize myself with this new class.

Background
MSDN System.Net.NetworkInformation.Ping description
C# 1.1 Ping Component by Wesley Brown on CodeProject

Using the code
The console application Main method is simple; it needs an address that is resolved by calling the DNS.GetHostEntry method. But before calling the DNS, there is a method called IsOffline that checks if the client has a valid internet connection. The IsOffline method uses the InternetGetConnectedState function from the system DLL Winnet.

Internet connection checking code:

[Flags]
enum ConnectionState : int
{
   INTERNET_CONNECTION_MODEM = 0x1,
   INTERNET_CONNECTION_LAN = 0x2,
   INTERNET_CONNECTION_PROXY = 0x4,
   INTERNET_RAS_INSTALLED = 0x10,
   INTERNET_CONNECTION_OFFLINE = 0x20,
   INTERNET_CONNECTION_CONFIGURED = 0x40
}

[DllImport("wininet", CharSet = CharSet.Auto)]
static extern bool InternetGetConnectedState(ref ConnectionState lpdwFlags,
                                            int dwReserved);

static bool IsOffline()
{
   ConnectionState state = 0;
   InternetGetConnectedState(ref state, 0);
   if (((int)ConnectionState.INTERNET_CONNECTION_OFFLINE & (int)state) != 0)
   {
       return true;
   }

   return false;
}

The ping is made by a thread that calls the StartPing method:

static void StartPing(object argument)
{
   IPAddress ip = (IPAddress)argument;

   //set options ttl=128 and no fragmentation

   PingOptions options = new PingOptions(128, true);

   //create a Ping object

   Ping ping = new Ping();

   //32 empty bytes buffer

   byte[] data = new byte[32];

Read more: Codeproject

Posted via email from Jasper-net

0 comments: