The internet has fundamentally changed the majority of the applications we develop. Rarely is an application designed to exist in isolation. Instead, most apps rely on other networked apps to retrieve and store information. In this post, we’ll explore the network utility ping
and how we can utilize a C# library to test the reachability of any network host.
What Is Ping?
Written in 1983 by Mike Muuss, the design of the ping
utility is one that allows network administrators to measure, diagnose, and troubleshoot network issues. Being developed in the military, ping
naturally gets its name after the sound sonar makes and mimics the behavior of sonar itself.
Ping is a computer network administration software utility used to test the reachability of a host on an Internet Protocol (IP) network. It is available for virtually all operating systems that have networking capability, including most embedded network administration software. –Wikipedia
When invoked, ping
transmits a set of bytes, and the output shows information including the host’s IP address, the Internet Control Message Protocol (ICMP) sequence, the Time To Live (TTL), and the total response time in milliseconds.
As we can see, the output can help us diagnose whether our target host is up and responding expectedly.
Ping with .NET
While being a command-line utility on most operating systems, ping
is also implementable. The .NET Framework has an implementation of Ping
under the System.Net.NetworkInformation
namespace. We can use this class to perform the same ping
actions from our C# applications.
We get the following results from running our console application.
One strange behavior we notice is the reply buffer length is always 0. The odd behavior is because the Ping
class behaves differently based on our operating system. On Unix systems (Linux and macOS), the .NET Framework delegates to the UnixCommandLinePing
class, which does not map PingOptions
and does not read the response byte array. The difference in behavior across operating systems should be accounted for, as it could cause null reference exceptions`.
The cool thing about the Ping
implementation in .NET is the presence of the IPStatus
enum, which makes it clear what kind of response we are dealing with.
There we have it! We can ping a network host and wait for a response right from our .NET code. Give it a try and leave a comment below.