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:
- public static void ServerStatusBy(string url)
- {
- Ping pingSender = new Ping();
- PingReply reply = pingSender.Send(url);
- Console.WriteLine("Status of Host: {0}", url);
- if (reply.Status == IPStatus.Success)
- {
- Console.WriteLine("IP Address: {0}", reply.Address.ToString());
- Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
- Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
- Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
- Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
- }
- else
- Console.WriteLine(reply.Status);
- }
Do not forget to add following namespace:
- using System.Net.NetworkInformation;
Call this method from main:
- Console.Write("Enter server url:");
- var url = Console.ReadLine();
- Console.Clear();
- ServerStatusBy(url);
- 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.