判断服务器(包含端口)或者IP地址连接是否正常

C#客户端连接服务器前先判断服务器连接是否正常

 		/// 
        /// 采用Socket方式,测试服务器连接
        /// 
        /// 服务器主机名或IP
        /// 端口号
        /// 
        public static bool TestConnection(string host, int port)
        {
            int millisecondsTimeout = 5;//等待时间
            TcpClient client = new TcpClient();
            try
            {
                var connect = client.BeginConnect(host, port, null, null);
                connect.AsyncWaitHandle.WaitOne(millisecondsTimeout);
                return client.Connected;
            }
            catch (Exception e)
            {
                //throw e;
                return false;
            }
            finally
            {
                client.Close();
            }

        }

使用Ping命令检查IP地址或域名是否可以使用

 /// 
        /// 用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令)
        /// 
        /// IP地址或域名
        /// 
        public static bool PingIpOrDomainName(string strIpOrDName)
        {
            try
            {
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 120;
                PingReply objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions);
                string strInfo = objPinReply.Status.ToString();
                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }


你可能感兴趣的:(C#)