dotNoted

Icon

Observations of .Net development in the wild

The popular C# Ping Utitility

UPDATE:

In C# 2.0 or later, just use the System.Net.NetworkInformation.Ping class:

static void Main (string[] args)
{
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: 

C# Ping Utitility

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

Talking about Mapping ADSI Interfaces to the Network Management Functions

http://msdn.microsoft.com/library/en-us/netmgmt/netmgmt/mapping_adsi_interfaces_to_the_network_management_functions.asp?frame=true

Why is it that we have such a proliferation of network functions? LanManager is ancient history, by most accounts, yet we must still deal with the functions which are rooted in it.

Take enumeration of SQL Servers. There really isn’t a good way to do it in .Net. We can’t really rely on people to have published their SQL Servers in Active Directory (we could more easily if it was default on install, but it is an obscure setting). The best way is to wrap these old API functions with P/Invoke. Perhaps we’ll see this change in SQL 2005… anyone know?

Filed under: Administration