private static async Task <PingResponse[]> PingAsync(string[] hostNameOrAddress, TimeSpan pingTimeout, bool resolveDns, TimeSpan dnsTimeout) { var pingResult = await Task.WhenAll(hostNameOrAddress.Select(async x => { // Resolve only when incoming is HostName. IPAddress ip = null; DnsResponse resolve = null; var isIpAddress = IPAddress.TryParse(x, out ip); if (!isIpAddress) { resolve = DnsResolver.ResolveHostName(x, dnsTimeout); if (resolve.IPAddress == null) { resolve = null; } else { ip = resolve.IPAddress; } } // Execute PingAsync PingReply reply = null; using (var ping = new Ping()) { try { reply = await ping.SendPingAsync(ip, (int)pingTimeout.TotalMilliseconds, _buffer, _options); } catch { // ping throw should never stop operation. just return null. } } // set RoundtripTime long roundTripTime = 0; if (reply != null) { roundTripTime = reply.RoundtripTime; } // set Status var status = IPStatus.DestinationHostUnreachable; if (reply != null) { status = reply.Status; } // set IsSuccess var isSuccess = status == IPStatus.Success; // return when PingFailed || HostName || OmitResolveDns if (!isSuccess || !isIpAddress || !resolveDns) { return new PingResponse { HostNameOrAddress = x, IPAddress = ip, Status = status, RoundTripTime = roundTripTime, IsSuccess = isSuccess, IsResolved = resolve != null, } } ; // Resolve Dns only for success host entry. var host = x; resolve = DnsResolver.ResolveIP(ip, dnsTimeout); if (resolve != null) { host = resolve.HostName; } return(new PingResponse { HostNameOrAddress = host, IPAddress = ip, Status = status, RoundTripTime = roundTripTime, IsSuccess = true, IsResolved = resolve != null, }); }).ToArray()); return(pingResult); }
private async void CheckStatus() { Console.WriteLine("Checking Status..."); boolPinging = true; listMachinesToPing.Clear(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (!row.IsNewRow) { string computer = row.Cells["ColumnComputer"].Value.ToString(); listMachinesToPing.Add(computer); } } Console.WriteLine("Count: {0}", listMachinesToPing.Count); if (listMachinesToPing.Count > 0) { Console.WriteLine("await PingAsync()"); PingResponse[] arrResponses = null; TimeSpan ts = new TimeSpan(0, 0, 1); arrResponses = await NetworkInformationExtensions.PingAsync(listMachinesToPing.ToArray(), ts, false); foreach (PingResponse response in arrResponses) { Console.WriteLine("host: {0}, success?: {1}", response.HostNameOrAddress, response.IsSuccess); if (response.IsSuccess) { UpdateCellText(response.HostNameOrAddress.ToString(), "ColumnStatus", "Online"); } else { string status = "Unavailable"; //resolve? IPAddress ip = null; var isIpAddress = IPAddress.TryParse(response.HostNameOrAddress, out ip); if (!isIpAddress) { var resolve = DnsResolver.ResolveHostName(response.HostNameOrAddress, TimeSpan.FromMilliseconds(20)); if (resolve.IPAddress == null) { status = "Host not found"; } } UpdateCellText(response.HostNameOrAddress, "ColumnStatus", status); } } } boolPinging = false; }