C# Ping 简单使用 (超时)

版权声明:转载请标注原文地址。【邮箱[email protected]】 https://blog.csdn.net/weixin_42032900/article/details/81186139

C# Ping 简单使用 (含超时处理)

说明,使用ping工具

1.可以用来查询域名\主机是否可以访问

2.可以用来查询域名\主机对应的ip地址


一、使用Ping类,效率比较高,相应快

程序集 System

命名空间:namespace System.Net.NetworkInformation

 class Program
    {
        static void Main(string[] args)
        {
            bool v = PingMethod("baidu.cn");
            bool v2 = PingMethod("192.168.1.140");
            bool v3 = PingMethod("192.168.12.15");
            bool v4 = PingMethod("172.18.35.253");
            bool v5 = PingMethod("127.0.0.1");
            Console.ReadLine();
        }

        /// <summary>
        /// ping命令
        /// </summary>
        /// <param name="host">发送主机名或Ip地址</param>
        /// <returns></returns>
        private static bool PingMethod(string host)
        {
            bool online = false; //是否在线
            Ping pingSender = new Ping();
            //调用同步 send 方法发送数据,将返回结果保存至PingReply实例
            PingReply reply = pingSender.Send(hostNameOrAddress:host, timeout:120); 

            if (reply.Status == IPStatus.Success)
            {
                online = true;
                Console.WriteLine("当前在线,已ping通!");

                StringBuilder sbuilder = new StringBuilder();
                sbuilder.AppendLine(string.Format("答复的主机地址: {0} ", reply.Address.ToString()));
                sbuilder.AppendLine(string.Format("往返时间: {0} ", reply.RoundtripTime));
                sbuilder.AppendLine(string.Format("生存时间(TTL): {0} ", reply.Options.Ttl));
                sbuilder.AppendLine(string.Format("是否控制数据包的分段: {0} ", reply.Options.DontFragment));
                sbuilder.AppendLine(string.Format("缓冲区大小: {0} ", reply.Buffer.Length));
                Console.WriteLine(sbuilder.ToString());
            }
            else
            {
                Console.WriteLine("不在线,ping不通!");
            }

            return online;
        }
    }

参考:
https://blog.csdn.net/zht666/article/details/24592021
https://blog.csdn.net/andrew_wx/article/details/6628501

猜你喜欢

转载自blog.csdn.net/weixin_42032900/article/details/81186139