C#通過socket判斷FTP服務器是否通暢並判斷用戶名密碼是否正確


        private static ManualResetEvent timeoutObject;
        private static Socket socket = null;
        private static bool isConn = false;
        /// <summary>
        /// 通過socket判斷ftp是否通暢(異步socket連接,同步發送接收數據)
        /// </summary> 
        /// <returns></returns>
        public static bool CheckFtp(string ip, string ftpuser, string ftppas,out string errmsg, int port = 21,int timeout=2000)
        { 
            #region 輸入數據檢查
            if (ftpuser.Trim().Length==0)
            {
                errmsg = "FTP用戶名不能為空,請檢查設置!";
                return false;
            }
            if(ftppas.Trim().Length == 0)
            {
                errmsg = "FTP密碼不能為空,請檢查設置!";
                return false;
            }
            IPAddress address;
            try
            {
                address = IPAddress.Parse(ip);
            }
            catch
            {
                errmsg =string.Format("FTP服務器IP:{0}解析失敗,請檢查是否設置正確!",ip);
                return false;
            }
            #endregion
            isConn = false;  

            bool ret = false;
            byte[] result = new byte[1024];
            int pingStatus = 0, userStatus = 0, pasStatus = 0, exitStatus = 0; //連接返回,用戶名返回,密碼返回,退出返回
            timeoutObject = new ManualResetEvent(false); 
            try
            {
                int receiveLength;

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
                socket.SendTimeout = timeout;
                socket.ReceiveTimeout = timeout;//超時設置成2000毫秒

                try
                {
                    socket.BeginConnect(new IPEndPoint(address, port),new AsyncCallback(callBackMethod),socket); //開始異步連接請求
                    if(!timeoutObject.WaitOne(timeout,false))
                    {
                        socket.Close();
                        socket = null;
                        pingStatus = -1;
                    }
                    if (isConn)
                    {
                        pingStatus = 200;
                    }
                    else
                    {
                        pingStatus = -1;
                    }
                }
                catch(Exception ex)
                {
                    pingStatus = -1;
                }

                if(pingStatus==200) //狀態碼200 - TCP連接成功
                {  
                    receiveLength = socket.Receive(result);
                    pingStatus = getFtpReturnCode(result, receiveLength); //連接狀態
                    if(pingStatus==220)//狀態碼220 - FTP返回歡迎語
                    {
                        socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "USER " + ftpuser, Environment.NewLine)));
                        receiveLength = socket.Receive(result);
                        userStatus = getFtpReturnCode(result, receiveLength);  
                        if(userStatus==331)//狀態碼331 - 要求輸入密碼
                        { 
                            socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "PASS " + ftppas, Environment.NewLine)));
                            receiveLength = socket.Receive(result);
                            pasStatus = getFtpReturnCode(result, receiveLength); 
                            if(pasStatus== 230)//狀態碼230 - 登入因特網
                            { 
                                errmsg = string.Format("FTP:{0}@{1}登陸成功", ip, port);
                                ret = true;
                                socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "QUIT", Environment.NewLine))); //登出FTP
                                receiveLength = socket.Receive(result);
                                exitStatus = getFtpReturnCode(result, receiveLength);
                            }
                            else
                            { // 狀態碼230的錯誤
                                errmsg = string.Format("FTP:{0}@{1}登陸失敗,用戶名或密碼錯誤({2})", ip, port, pasStatus);
                            }
                        }
                        else
                        {// 狀態碼331的錯誤 
                            errmsg = string.Format("使用用戶名:'{0}'登陸FTP:{1}@{2}時發生錯誤({3}),請檢查FTP是否正常配置!", ftpuser, ip, port, userStatus);
                        }
                    }
                    else
                    {// 狀態碼220的錯誤 
                        errmsg = string.Format("FTP:{0}@{1}返回狀態錯誤({2}),請檢查FTP服務是否正常運行!", ip, port, pingStatus);
                    }
                }
                else
                {// 狀態碼200的錯誤
                    errmsg = string.Format("無法連接FTP服務器:{0}@{1},請檢查FTP服務是否啟動!", ip, port);
                } 
            }
            catch(Exception ex)
            { //連接出錯 
                errmsg = string.Format("FTP:{0}@{1}連接出錯:",ip,port) + ex.Message;
                Common.Logger(errmsg);
                ret = false;
            }
            finally
            {
                if (socket != null)
                {
                    socket.Close(); //關閉socket
                    socket = null;
                }
            }
            return ret;
        }
        private static void callBackMethod(IAsyncResult asyncResult)
        {
            try
            {
                socket = asyncResult.AsyncState as Socket;
                if(socket!=null)
                {
                    socket.EndConnect(asyncResult);
                    isConn = true;
                }
            }
            catch(Exception ex)
            {
                isConn = false;
            }
            finally
            {
                timeoutObject.Set();
            }
        }
        /// <summary>
        /// 傳遞FTP返回的byte數組和長度,返回狀態碼(int)
        /// </summary>
        /// <param name="retByte"></param>
        /// <param name="retLen"></param>
        /// <returns></returns>
        private static int getFtpReturnCode(byte[] retByte,int retLen)
        {
            try
            {
                string str = Encoding.ASCII.GetString(retByte, 0, retLen).Trim();
                return int.Parse(str.Substring(0, 3));
            }
            catch
            {
                return -1;
            }
        }    

 

 

小弟才疏學淺,如果不足之處請大家多多指導。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM