UPDATE:
In C# 2.0 or later, just use the System.Net.NetworkInformation.Ping class:
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
ping.PingCompleted += new System.Net.NetworkInformation.PingCompletedEventHandler(ping_PingCompleted);
ping.SendAsync("127.0.0.1", null);
}
static void ping_PingCompleted(object sender, System.Net.NetworkInformation.PingCompletedEventArgs e)
{
if (e.Reply.Status == System.Net.NetworkInformation.IPStatus.Success)
{
System.Diagnostics.Debug.WriteLine("Reply received.");
}
else
{
System.Diagnostics.Debug.WriteLine("Host unreachable…");
}
}
A google search will bring this article from C# Help up, since many have copied it:
Ouch… this is a lot of code just to check if a host is up or not. I’m baffled as to why it isn’t in the framework. Perhaps I need to check out 2.0. In the mean time, the WMI Ping provider is more C# code friendly (notice I didn’t say better performance).
Here is some code for those who care not about sockets, performance or geek factor, but do want some clean, maintainable code:
private bool isMachineReachable(string hostNameOrIP)
{
string wqlTemplate = "SELECT StatusCode FROM Win32_PingStatus WHERE Address = ‘{0}’";
System.Management.ManagementObjectSearcher query = new ManagementObjectSearcher();
query.Query = new ObjectQuery(String.Format(wqlTemplate, hostNameOrIP));
query.Scope = new ManagementScope("//localhost/root/cimv2");
ManagementObjectCollection pings = query.Get();
foreach(ManagementObject ping in pings)
{
if( Convert.ToInt32(ping.GetPropertyValue("StatusCode")) == 0)
return true;
}
return false;
}
Filed under: Administration
I’ve tried your code and it seems to be returning false positives on some machines.