C# Ping Command: Simple Usage Example

In C#, the ping command can be implemented using the Ping class in the System.Net.NetworkInformation namespace. Here is a simple example code demonstrating how to use the ping command in C#.

using System;
using System.Net.NetworkInformation;

class Program
{
    static void Main()
    {
        Ping pingSender = new Ping();
        PingReply reply = pingSender.Send("www.example.com");

        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine("Ping成功,延迟为:" + reply.RoundtripTime + "ms");
        }
        else
        {
            Console.WriteLine("Ping失败,错误信息:" + reply.Status);
        }
    }
}

In the example above, we first create an instance of the Ping class, then use the Send method to send a ping command to the specified host (“www.example.com”). Then we check the Status property of the PingReply object to determine if the ping was successful, if successful, we output the latency time, otherwise we output an error message.

Please note that when using the Ping class, administrator privileges may be required, so in certain situations, exceptions may be thrown. Ensure that your application has sufficient permissions to perform the ping operation.

bannerAds