c#联网判断

引用命名空间:sing System.Net.NetworkInformation;   

 

var address = "www.baidu.com";

Ping ping = null;
try {
    ping = new Ping();

    var pingReply = ping.Send(address);
    if (pingReply == null) return false;

    return pingReply.Status == IPStatus.Success;
} finally {
    if (ping != null) {

        // 2.0 下ping 的一个bug,需要显示转型后释放
        IDisposable disposable = ping;
        disposable.Dispose();

        ping.Dispose();
    }
}

 

出处:http://blog.csdn.net/joyhen/article/details/23399245

 

根据上面的参考,我自己稍微整理了下结构,代码如下:

        /// <summary>
        /// 用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令),true表示Ping成功,false表示Ping失败!
        /// <para>请自己验证IP格式的正确性</para>
        /// </summary>
        /// <param name="IpOrDomainName">输入参数,表示IP地址或域名</param>
        /// <returns></returns>
        public static bool PingIpOrDomainName(string IpOrDomainName)
        {
            Ping objPingSender = null;
            try
            {
                objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "jack";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 500;
                PingReply objPinReply = objPingSender.Send(IpOrDomainName, intTimeout, buffer, objPinOptions);

                if (objPinReply == null)
                    return false;
                return objPinReply.Status == IPStatus.Success;
            }
            catch (Exception ex)
            {
                LogFileHelper.Instance.WriteLog(IpOrDomainName + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace, LogFileHelper.LogLevel.ERROR);
                return false;
            }
            finally
            {
                if (objPingSender != null)
                {
                    // 2.0 下ping 的一个bug,需要显示转型后释放
                    IDisposable disposable = objPingSender;
                    disposable.Dispose();
                    objPingSender.Dispose();
                }
            }
        }

 

但是在测试ip地址加端口号的形式,是无法测试通过的,例如使用192.168.1.10:1234或者用192.168.1.10,1234,则会直接报错

posted on 2017-06-15 15:48  jack_Meng  阅读(723)  评论(0编辑  收藏  举报

导航