Daily Knowledge Drop
A Ping
class is available in the System.Net.NetworkInformation namespace - this class facilitates performing ping operations (as the name suggests), on a hostname or IP address from code.
Usage
The usage of the class is straightforward - declare an instance of Ping
, and call the SendPingAsync method:
using System.Net.NetworkInformation;
var looping = true;
// format asynchronously on a separate thread
Task.Run(async () =>
{
// create an instance of the Ping class
Ping pinger = new Ping();
// loop until the user presses a key
while (looping)
{
// ping and get the response
PingReply response = await pinger
.SendPingAsync("alwaysdeveloping.net");
// extract response information
Console.WriteLine($"Ping to '{response.Address}' took " +
$"{response.RoundtripTime}milliseconds and the response " +
$"was: `{response.Status}`");
// wait 250ms before pinging again
await Task.Delay(250);
}
});
// wait for a key press
// and then cancel the looping above
Console.ReadKey();
looping = false;
A sample response:
Ping to '192.11.119.201' took 604 milliseconds and was: 'Success'
Ping to '192.11.119.201' took 307 milliseconds and was: 'Success'
Ping to '192.11.119.201' took 307 milliseconds and was: 'Success'
Ping to '192.11.119.201' took 321 milliseconds and was: 'Success'
Ping to '192.11.119.201' took 311 milliseconds and was: 'Success'
Ping to '0.0.0.0' took 0 milliseconds and was: 'TimedOut'
Ping to '192.11.119.201' took 307 milliseconds and was: 'Success'
Ping to '192.11.119.201' took 620 milliseconds and was: 'Success'
Ping to '192.11.119.201' took 308 milliseconds and was: 'Success'
Notes
While there are better and more featureful (and more expensive) 3rd party tools available for monitoring the status and uptime of a website, with Ping
a simple, small application could be written to ping on an interval (as in the above example) and send out an alert if numerous timeouts are received.
References
Daily Drop 153: 05-09-2022
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.On This Page