Ping及相关类

作者:追风剑情 发布于:2019-11-12 19:41 分类:C#

示例

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace ConsoleApp6
{
    class Program
    {
        static void Main(string[] args)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            //true: 数据包不分片
            //不能分片的情况下如果发送的数据包超过MTU,则发送失败
            options.DontFragment = true;
            //TTL是 Time To Live的缩写,
            //该字段指定IP包被路由器丢弃之前允许通过的最大网段数量,默认128
            options.Ttl = 128;

            //要发送的数据
            string data = "aaaaaaaaaaaa";
            //数组不能超过 65500 个字节
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 120;//超时时间,单位:毫秒
            //ping网络IP地址为192.168.1.103的主机
            PingReply reply = pingSender.Send("192.168.1.103", timeout, buffer, options);
            //pingSender.SendAsync();//异步方法
            if (reply.Status == IPStatus.Success)
            {
                //目标主机IP地址
                Console.WriteLine("Address: {0}", reply.Address.ToString());
                //获取发送消息并得到答复的往返时间
                Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                //被路由器转发次数
                Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                //IP数据包是否分片
                Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                //发送消息的数据缓冲区大小
                Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
            }
            else
                Console.WriteLine("目标主机Ping失败 Status={0}", reply.Status.ToString());

            Console.ReadLine();
        }
    }
}

运行测试

11111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号