How to Check Whether API Server is up or Down

Introduction

In this article we will create a small utility using C# that tells us whether our API server is up or down.

Purpose

Our purpose is to check the API server so, we can make a request for our resources. It is recommended that before making any request to the server (API server in our case), we should ensure that our server is ready and up to handle our requests.

Throughout this article we will create a tiny utility to satisfy that purpose.

Requirements

So, what do we require? We just want to know the status of our Web API server.

Creation of Utility

Let's create a simple console app that tells us the status of our API server:

Open Visual Studio

Create a C# console application, name it "knowserverstatus" .


Add the following method:

  1. public static void ServerStatusBy(string url)    
  2. {    
  3.    Ping pingSender = new Ping();    
  4.    PingReply reply = pingSender.Send(url);    
  5.    Console.WriteLine("Status of Host: {0}", url);    
  6.    if (reply.Status == IPStatus.Success)    
  7.    {    
  8.       Console.WriteLine("IP Address: {0}", reply.Address.ToString());    
  9.       Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);    
  10.       Console.WriteLine("Time to live: {0}", reply.Options.Ttl);    
  11.       Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);    
  12.       Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);    
  13.    }    
  14.    else    
  15.    Console.WriteLine(reply.Status);    

Do not forget to add following namespace:
  1. using System.Net.NetworkInformation;  

Call this method from main:

  1. Console.Write("Enter server url:");    
  2. var url = Console.ReadLine();    
  3. Console.Clear();    
  4. ServerStatusBy(url);    
  5. Console.ReadLine(); 
Run it and we will get the following output:



Elaboration of code

Let's elaborate on the preceding code. Here PING sends an Internet Control Message Protocol (ICMP) request to the requested server host/URL and waits to receive the response back. If the value of Status is success then that means our server is up and running.

Here PingReply returns all properties, described as:

Property Description
Address Gets the address of Host
Buffer Gets the buffer of data received, its an array of bytes
PingOption It handles how data transmitted
RoundTrip Gets the number of milliseconds to send ICMP echo request
Status Gets the status of request. If not Success , in other words Host is not up

Conclusion

In this article we discussed all about the PingReply class and using this class, we created a utility to know the status of our server.

Up Next
    Ebook Download
    View all
    Learn
    View all