Alex Rivera | Logout

Fast way to check if a server is accessible over the network in C#

Asked 2009-11-02T19:36:15.300
9

I've got a project where I'm hitting a bunch of custom Windows Performance Counters on multiple servers and aggregating them into a database. If a server is down, I want to skip it, and just continue on with my day.

Currently I'm checking to see if a server is live by doing a DirectoryInfo on a share that I've got to look at later in the process anyways, then checking the .Exists property.This is my current code snippet for testing:

DirectoryInfo di = new DirectoryInfo(machine.Share_Path);
if (!di.Exists)
{
    log.Warn("Could not access " + machine.Name + "! Maybe its down?");
    continue; // Skips to the next server in my loop where this snippet exists.
}

This works, but its pretty slow. It takes about 68 seconds on average for the di.Exists bit to finish its work, and I ideally need to know within a second whether or not a server is accessible. Pinging also isn't an option since a server can be pingable but not "live" in our environment.

I'm still kind of fresh to the .NET world, so I'm open to any advice people can offer.

Thanks in advance.

-Weegee

c#
Edit
Report

1 Answer

2

Opening Socket to a specific port usually does the trick. If you really want it to be fast, be sure to set the NoDelay property on the new socket (Nagle algorithm) so there is no buffering.

Fast will largely depend on latency but this is probably the fastest way I know to connect to an endpoint. It's pretty simple to parallelize using the async methods. How fast you can check will largely depend on your network topology but in tests for 1000 servers (latency between 0-75ms) I've been able to get connectivity state in ~30 seconds. Not scientific data at all but should give you the idea.

Also, don't ever do this through UNC file shares because if the server no longer exists you will have a lot of dangling connections that take forever to timeout. So if you have a lot of servers with invalid DNS records and you try to poll them you will bring Windows down completely over time. Things like File.Exists and any file access will cause this.

answered 2011-07-01T19:38:56.543

Your Answer