C# Ping类的例子,可用于测试网络,主机响应时间等

http://blog.csdn.net/andrew_wx/article/details/6628501

using System.Net.NetworkInformation;  
namespace PingExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_StartPing_Click(object sender, EventArgs e)
        {
            this.lst_PingResult.Items.Clear();
            //远程服务器IP
            string ipStr = txt_IPAddress.Text.ToString().Trim();
            //构造Ping实例
            Ping pingSender = new Ping();
            //Ping 选项设置
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            //测试数据
            string data = "test data abcabc";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            //设置超时时间
            int timeout = 120;
            //调用同步 send 方法发送数据,将返回结果保存至PingReply实例
            PingReply reply = pingSender.Send(ipStr, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                lst_PingResult.Items.Add("答复的主机地址:" + reply.Address.ToString());
                lst_PingResult.Items.Add("往返时间:" + reply.RoundtripTime);
                lst_PingResult.Items.Add("生存时间(TTL):" + reply.Options.Ttl);
                lst_PingResult.Items.Add("是否控制数据包的分段:" + reply.Options.DontFragment);
                lst_PingResult.Items.Add("缓冲区大小:" + reply.Buffer.Length);
            }
            else
                lst_PingResult.Items.Add(reply.Status.ToString());
        }
    }
}

 

posted @ 2017-03-22 09:02  c#菜鸟之行  阅读(7342)  评论(0编辑  收藏  举报