C# Ping network check network connectivity
class Program
{
static async Task Main(string[] args)
{
bool ret = await PingNet("192.168.2.205");
Console.ReadKey();
}
/// <summary>
///Ping the network to check network connectivity
/// </summary>
/// <param name="ip">The IP address</param>
/// <param name="num">The number of ping</param>
/// <param name="timeout">Timeout for each ping</param>
/// <returns>Bool true: passed false: failed</returns>
static async Task<bool> PingNet(string ip, int num = 10.int timeout = 2000)
{
List<bool> pingRets = new List<bool> ();/ / ping results
Ping pingSender = new Ping();
for (int i = 0; i < num; i++)
{
PingReply replyRet = await pingSender.SendPingAsync(ip, timeout);
if (replyRet.Status == IPStatus.Success)
pingRets.Add(true);
else
pingRets.Add(false);
Thread.Sleep(50);
}
if (pingRets.Contains(true))
return true;
else
return false;
}
Copy the code
reference
- (6 messages) C#- asynchronous Ping check network connectivity _guo1wu3shi4 column -CSDN blog