You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HostBusiness.cs 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.NetworkInformation;
  5. using System.Threading.Tasks;
  6. using SiteStatus.Dbo;
  7. namespace SiteStatus.Business
  8. {
  9. public class HostBusiness
  10. {
  11. public async Task<HostStatusDbo> GetHostStatusAsync(string host, int count, int timeout)
  12. {
  13. var hostStatus = new HostStatusDbo
  14. {
  15. Ip = host,
  16. Times = new List<long?>()
  17. };
  18. var tasks = new List<Task<PingReply>>();
  19. for (var i = 0; i < count; ++i)
  20. {
  21. try
  22. {
  23. var ping = new Ping();
  24. var pingTask = ping.SendPingAsync(host, timeout);
  25. tasks.Add(pingTask);
  26. }
  27. catch (Exception e)
  28. {
  29. hostStatus.Times.Add(null);
  30. }
  31. }
  32. foreach (var pingResult in await Task.WhenAll(tasks))
  33. {
  34. if (pingResult != null && pingResult.Status == IPStatus.Success)
  35. {
  36. hostStatus.Times.Add(pingResult.RoundtripTime);
  37. }
  38. else
  39. {
  40. hostStatus.Times.Add(null);
  41. }
  42. }
  43. try
  44. {
  45. var dnsResult = await Dns.GetHostEntryAsync(host);
  46. if (dnsResult != null)
  47. {
  48. hostStatus.Hostname = dnsResult.HostName;
  49. }
  50. else
  51. {
  52. hostStatus.Hostname = null;
  53. }
  54. }
  55. catch (Exception e)
  56. {
  57. hostStatus.Hostname = null;
  58. }
  59. return hostStatus;
  60. }
  61. }
  62. }