PingCheckerAsync

PingCheckerAsync

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;

namespace MyApp.Utility
{
	/// <summary>
	/// Ping送信クラス(非同期処理用)
	/// </summary>
	public class PingCheckerAsync
	{
		#region 変数
		
		/// <summary>
		/// Pingオブジェクト
		/// </summary>
		Ping ping = null;
		
		/// <summary>
		/// Ping送信完了イベント
		/// </summary>
		/// <example>
		/// 
		/// (例)イベント登録メソッド
		/// 
		/// if (e.Cancelled)
		///	{
		///		Console.WriteLine("Pingがキャンセルされました。");
		///	}
		///	else if (e.Error != null)
		///	{
		///		Console.WriteLine("エラー:" + e.Error.Message);
		///	}
		///	else
		///	{
		///		//結果を取得
		///		if (e.Reply.Status == System.Net.NetworkInformation.IPStatus.Success)
		///		{
		///			Console.WriteLine("Reply from {0}:bytes={1} time={2}ms TTL={3}",
		///				e.Reply.Address, e.Reply.Buffer.Length,
		///				e.Reply.RoundtripTime, e.Reply.Options.Ttl);
		///		}
		///		else
		///		{
		///			Console.WriteLine("Ping送信に失敗。({0})", e.Reply.Status);
		///		}
		///	}
		///	
		/// </example>
		public event PingCompletedEventHandler PingCompleted  = null;

		#endregion

		#region コンストラクタ
		/// <summary>
		/// コンストラクタ
		/// </summary>
		public PingCheckerAsync()
		{
			this.ping = new Ping();
			this.ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted);
		}
		#endregion

		#region メソッド
		
		#region Ping完了処理
		/// <summary>
		/// Ping完了処理
		/// </summary>
		/// <param name="sender">送信元オブジェクト</param>
		/// <param name="e">イベントオブジェクト</param>
		void ping_PingCompleted(object sender, PingCompletedEventArgs e)
		{
			this.PingCompleted(sender, e);
		} 
		#endregion

		#region Pingをキャンセルする
		/// <summary>
		/// Pingをキャンセルする
		/// </summary>
		public void SendAsyncCancel()
		{
			this.ping.SendAsyncCancel();
		}
		#endregion

		#region Pingを送信する
		/// <summary>
		/// Pingを送信する
		/// </summary>
		/// <param name="hostNameOrAddress">ホスト名または IP アドレスの文字列形式</param>
		/// <param name="timeOut">タイムアウト(ミリ秒単位)</param>
		public void SendAsync(string hostNameOrAddress, Int32 timeOut)
		{
			//パラメータチェック
			if (string.IsNullOrEmpty(hostNameOrAddress))
			{
				throw new ArgumentException("param:[hostNameOrAddress]がnullまたは空文字");
			}

			if (timeOut < 0)
			{
				throw new ArgumentException("param:[timeOut]が0未満");
			}

			//Pingのオプションを設定
			//TTLを64、フラグメンテーションを無効にする
			System.Net.NetworkInformation.PingOptions opts = new System.Net.NetworkInformation.PingOptions(64, true);
			
			//Pingで送信する32バイトのデータを作成
			byte[] bs = System.Text.Encoding.ASCII.GetBytes(new string('A', 32));
			
			//Pingを送信する
			this.ping.SendAsync(hostNameOrAddress, timeOut, bs, opts, null);
		}
		#endregion	

		#endregion

	}
}