pearcewg
pearcewg

Reputation: 9613

Simple way to ping webserver to see if operational/alive?

I have a distributed website (.NET, IIS) that has a dynamic number of servers around the world.

I want to build a [simple] utility which will sit at our home location, and every so often "ping" the web servers to see if they are operational. I will then log this result for each server into the database, to show current status and a history of any detected downtime.

What is the best way to do this? Connect via HTTP from .NET? I want this to be not much code (ideally), and run as a service.

Any links or sample code would be greatly appreciated.

Is this a standard practice? Or do distributed apps typically do something different? (like phone home instead of being pinged).

Upvotes: 3

Views: 3177

Answers (2)

Alex Aza
Alex Aza

Reputation: 78457

You could use WebRequest class for this.

var request = WebRequest.Create("http://google.com");
using (var response = request.GetResponse())
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
    var responseText = streamReader.ReadToEnd();

    // validate that responseText has content that you would expect
}

I recommend to check content of the page to make sure that your website is deployed correctly. Web site can return StatusCode HttpStatusCode.OK, while showing IIS welcome page instead of the page you expected to see, if site was redeployed incorrectly.

Upvotes: 0

IAmTimCorey
IAmTimCorey

Reputation: 16757

Here is a SO question that is close to yours:

Best way to test if a website is alive from a C# applicaiton

Basically, you can check the website status using the following code:

WebRequest request = WebRequest.Create("http://localhost/myContentSite/test.aspx");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response == null || response.StatusCode != HttpStatusCode.OK)
{
   Console.WriteLine("You have a problem");
}

As for the best way to do it, I would recommend going with a phone-home model if it is possible in your situation. That way you won't have to care who has been added. They will just automatically show up when they first check in. If, however, you don't have full control of all of your websites' code (or if you have already launched them), it would probably be better to go with a centralized monitoring solution that tests the site's availability. This will reduce the amount of changes you need to make to systems. Finally, if you want to truly check to be sure a site is live, check remotely instead of sending out an "I'm alive" message. This will ensure that the firewall, etc. is also working since a site might be able to send out but it might not be reachable from external networks.

Upvotes: 3

Related Questions