C# check whether the server ip and port are unblocked and accessible

 		/// <summary>
        /// 检查服务器和端口是否可以连接
        /// </summary>
        /// <param name="ipString">服务器ip</param>
        /// <param name="port">端口</param>
        /// <returns></returns>
        public static bool CheckConnect(string ipString, int port)
        {
    
    
            System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient()
            {
    
     SendTimeout = 1000 };
            IPAddress ip = IPAddress.Parse(ipString);
            try
            {
    
    
                tcpClient.Connect(ip, port);
            }
            catch (Exception ex)
            {
    
    
                //LogHelpter.AddLog($"连接服务{ipString}:{port}失败,设置的超时时间{tcpClient.SendTimeout}毫秒");
                //连接失败
                return false;
            }
            bool right = tcpClient.Connected;
            tcpClient.Close();
            tcpClient.Dispose();
            return right;
        }

Guess you like

Origin blog.csdn.net/u011511086/article/details/114299800