CodePanic! > C#.NET Tips > 今ここ
■pingを送信する(非同期)
pingを非同期で送信するサンプルです。
Formにホスト名入力テキストボックスと
ping送信、停止ボタンと
結果を表示するテキストボックスを
それぞれ配置しています。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace PingTest
{
public partial class Form1 : Form
{
System.Net.NetworkInformation.Ping _ping = new System.Net.NetworkInformation.Ping();
bool _bSending = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_ping.PingCompleted += new System.Net.NetworkInformation.PingCompletedEventHandler(_ping_PingCompleted);
}
private void buttonStartStop_Click(object sender, EventArgs e)
{
buttonStartStop.Enabled = false;
if(!_bSending)
{
_bSending = true;
// Ping設定: TTL=64,データは断片化されないよう指定
System.Net.NetworkInformation.PingOptions pingOption =
new System.Net.NetworkInformation.PingOptions(64, true);
// Pingで送信するデータ
byte[] buffer = System.Text.Encoding.ASCII.GetBytes("ping test data");
// Ping送信:タイムアウト10秒
_ping.SendAsync(textBoxHostName.Text, 10000, buffer, pingOption, null);
}
else
{
_bSending = false;
_ping.SendAsyncCancel();
}
}
void _ping_PingCompleted(object sender, System.Net.NetworkInformation.PingCompletedEventArgs e)
{
if(e.Cancelled)
{
MessageBox.Show("キャンセルされました。");
return;
}
string msg;
if(e.Error != null)
{
msg = e.Error.Message;
}
else
{
// 返答あり?
if(e.Reply.Status == System.Net.NetworkInformation.IPStatus.Success)
{
msg = string.Format(
"{0} からの応答: バイト数 ={1} 時間 ={2}ms TTL={3}",
e.Reply.Address,
e.Reply.Buffer.Length,
e.Reply.RoundtripTime,
e.Reply.Options.Ttl);
}
else
{
msg = string.Format("Ping失敗 {0}", e.Reply.Status);
}
}
textBoxLog.AppendText(msg + "\r\n");
_bSending = false;
buttonStartStop.Enabled = true;
}
}
}
Copyright © 2008.07 - shougo suzaki
|