using System; using System.Collections.Generic; using System.Text; using System.Net.NetworkInformation; using Apewer; namespace Apewer.Network { /// ICMP。 public class Icmp { /// 发送 PING 命令,命令中包含 32 位零数据。 /// 目标地址。 /// 等待响应的超时时间(毫秒)。 /// 命令的起始 TTL 值(在丢弃数据之前可以转发该数据的路由节点数)。 /// 是否分段。 /// 命令的返回结果。 public static Icmp Ping(string ip, int timeout = 1000, byte ttl = 255, bool df = true) { var icmp = new Icmp(); if (!string.IsNullOrEmpty(ip) && (timeout > 0)) { var vip = NetworkUtility.IsIP(ip) ? ip : NetworkUtility.Resolve(ip); var op = new Ping(); var oo = new PingOptions(); oo.DontFragment = df; oo.Ttl = ttl; byte[] bs = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; var or = op.Send((string)vip, NumberUtility.Restrict(timeout, 1, ushort.MaxValue), bs, oo); icmp._success = (or.Status == IPStatus.Success) ? true : false; icmp._address = or.Address.ToString(); icmp._time = or.RoundtripTime; icmp._ttl = or.Options.Ttl; } return icmp; } private bool _success = false; private string _address = ""; private long _time = 0; private int _ttl = 0; /// 构造函数。 public Icmp() { } /// 已成功获取目标的返回。 public bool Success { get { return _success; } } /// 返回的目标地址。 public string Addresss { get { return _address; } } /// 收到返回所经历的时间(毫秒)。 public long Time { get { return _time; } } /// 返回的 TTL 值(在丢弃数据之前可以转发该数据的路由节点数)。 public int Ttl { get { return _ttl; } } } }