使用C# ping主机的方法


在我们开发项目时经常会遇到要ping主机的问题,现在我封装了一个ping主机的方法,

代码如下:      

        /// <summary>

        /// Ping指定的主机,看能否ping通
        /// </summary>
        /// <param name="Address">(主机地址)</param>
        /// <param name="TimeOut">(超时时间,默认:1s)</param>
        /// <returns>True if a response is received, false otherwise</returns>
        public static bool PingHost(string Address, int TimeOut = 1000)
        {
            using (System.Net.NetworkInformation.Ping PingSender = new System.Net.NetworkInformation.Ping())
            {
                PingOptions Options = new PingOptions();
                Options.DontFragment = true;
                string Data = "test";
                byte[] DataBuffer = Encoding.ASCII.GetBytes(Data);
                PingReply Reply = PingSender.Send(Address, TimeOut, DataBuffer, Options);
                if (Reply.Status == IPStatus.Success)
                    return true;
                return false;
            }
        }

相关内容