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.

62 lines
2.3 KiB

4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.NetworkInformation;
  5. using Apewer;
  6. namespace Apewer.Network
  7. {
  8. /// <summary>ICMP。</summary>
  9. public class Icmp
  10. {
  11. /// <summary>发送 PING 命令,命令中包含 32 位零数据。</summary>
  12. /// <param name="ip">目标地址。</param>
  13. /// <param name="timeout">等待响应的超时时间(毫秒)。</param>
  14. /// <param name="ttl">命令的起始 TTL 值(在丢弃数据之前可以转发该数据的路由节点数)。</param>
  15. /// <param name="df">是否分段。</param>
  16. /// <returns>命令的返回结果。</returns>
  17. public static Icmp Ping(string ip, int timeout = 1000, byte ttl = 255, bool df = true)
  18. {
  19. var icmp = new Icmp();
  20. if (!string.IsNullOrEmpty(ip) && (timeout > 0))
  21. {
  22. var vip = NetworkUtility.IsIP(ip) ? ip : NetworkUtility.Resolve(ip);
  23. var op = new Ping();
  24. var oo = new PingOptions();
  25. oo.DontFragment = df;
  26. oo.Ttl = ttl;
  27. byte[] bs = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  28. var or = op.Send((string)vip, NumberUtility.Restrict(timeout, 1, ushort.MaxValue), bs, oo);
  29. icmp._success = (or.Status == IPStatus.Success) ? true : false;
  30. icmp._address = or.Address.ToString();
  31. icmp._time = or.RoundtripTime;
  32. icmp._ttl = or.Options.Ttl;
  33. }
  34. return icmp;
  35. }
  36. private bool _success = false;
  37. private string _address = "";
  38. private long _time = 0;
  39. private int _ttl = 0;
  40. /// <summary>构造函数。</summary>
  41. public Icmp() { }
  42. /// <summary>已成功获取目标的返回。</summary>
  43. public bool Success { get { return _success; } }
  44. /// <summary>返回的目标地址。</summary>
  45. public string Addresss { get { return _address; } }
  46. /// <summary>收到返回所经历的时间(毫秒)。</summary>
  47. public long Time { get { return _time; } }
  48. /// <summary>返回的 TTL 值(在丢弃数据之前可以转发该数据的路由节点数)。</summary>
  49. public int Ttl { get { return _ttl; } }
  50. }
  51. }