/// <summary>直接對主機傳送網際網路控制訊息通訊協定 (ICMP)</summary> /// <param name="hostNameOrAddress">System.String,識別 ICMP 回應訊息的目標電腦。指定給這個參數的值可以是主機名稱或 IP 位址的字串表示。</param> /// <returns>PingResultEventArgs : 回應內容</returns> /// <remarks>本函示的TTL(Time to Live)預設為64</remarks> public static PingResultEventArgs Ping(string hostNameOrAddress) { PingResultEventArgs arg = null; using (Ping pingSender = new Ping()) { PingOptions options = new PingOptions(64, true); string data = "a".PadLeft(32, 'a'); byte[] buffer = Encoding.ASCII.GetBytes(data); try { PingReply reply = pingSender.Send(hostNameOrAddress, 120, buffer, options); arg = new PingResultEventArgs(reply); } catch (Exception ex) { arg = new PingResultEventArgs(ex); } } return(arg); }
private void PingCallback(object o) { if (_Times != 0 && _DoneTimes >= _Times) { try { if (_PingTimer != null) { _PingTimer.Dispose(); } } finally { _PingTimer = null; } return; } try { Interlocked.Increment(ref _DoneTimes); using (Ping pingSender = new Ping()) { PingOptions options = new PingOptions(this.TimeToLive, true); string data = "a".PadLeft(this.DataLength, 'a'); byte[] buffer = Encoding.ASCII.GetBytes(data); try { PingReply reply = pingSender.Send(this.HostNameOrAddress, this.Timeout, buffer, options); if (OnResult != null) { PingResultEventArgs arg = new PingResultEventArgs(reply); foreach (EventHandler <PingResultEventArgs> del in this.OnResult.GetInvocationList()) { try { del.BeginInvoke(this, arg, new AsyncCallback(PingResultCallback), del); } catch (Exception exx) { Debug.Print(exx.Message); } } } } catch (Exception ex) { if (OnException != null) { PingResultEventArgs arg = new PingResultEventArgs(ex); foreach (EventHandler <PingResultEventArgs> del in this.OnException.GetInvocationList()) { try { del.BeginInvoke(this, arg, new AsyncCallback(PingResultCallback), del); } catch (Exception exx) { Debug.Print(exx.Message); } } } } } if (_Times != 0 && _DoneTimes >= _Times) { if (_PingTimer != null) { _PingTimer.Dispose(); _PingTimer = null; } if (OnFinished != null) { foreach (EventHandler del in this.OnFinished.GetInvocationList()) { try { del.BeginInvoke(this, new EventArgs(), new AsyncCallback(EventCallback), del); } catch (Exception exx) { Debug.Print(exx.Message); } } } } } catch { } }