Tuesday, June 15, 2004

How to Ping in C# using System.Management

If you are using Windows XP, Windows Server 2003 or above perhaps you might want to avoid using unsupported code for emulating the Ping.exe utility that comes with Windows. Microsoft has introduced the new Win32_PingStatus WMI class. You can use the System.Management classes to access an Win32_PingStatus object directly or generate a wrapper by using the Management Strongly Typed Class Generator Tool.
Following the second option, open the Visual Studio .NET Command Prompt and type:

C:\>mgmtclassgen.exe Win32_PingStatus

This will generate the file "PingStatus.CS". Create a new C# project and add the "PingStatus.CS" file. Use the PingStatus class as follows:

using System;
using ROOT.CIMV2.Win32;
sealed class MyPing {
static void Main(string[] args)
{
if(args.Length == 0)
{
Console.Error.WriteLine("Usage: myping");
return;
}
PingStatus ping = Ping(args[0]);
// Check if we got an answer
if(ping.PrimaryAddressResolutionStatus == 0)
{
Console.WriteLine("Resolved: {0}", ping.ProtocolAddress);
}
else
{
Console.Error.WriteLine("Error: '{0}' not resolved.", ping.Address);

}
}
static PingStatus Ping(string address)
{
string condition = string.Format("Address='{0}'", address);
foreach(PingStatus ping in PingStatus.GetInstances(condition))
{
return ping;
}
return null;
}}


The C# code above pings an address (IP or host name) and checks if it got an answer. Please check the Win32_PingStatus WMI class documentation on the
MSDN for property descriptions and status codes.