代码有注解。看不懂请留言。
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class Form1
Private timeoutObject As ManualResetEvent
Private ssocket As Socket
Private isConn As Boolean
Public Function CheckFtp(ByVal ip As String, ByVal ftpuser As String, ByVal ftppas As String, ByRef errmsg As String, Optional port As Integer = 21, Optional timeout As Integer = 2000) As Boolean
'*********输入数据检查开始*********
If ftpuser.Trim.Length = 0 Then
errmsg = "FTP用户名不能为空,请检查设置!"
Return False
End If
If ftppas.Trim.Length = 0 Then
errmsg = "FTP密码不能为空,请检查设置!"
Return False
End If
Dim address As IPAddress = Nothing
Try
address = IPAddress.Parse(ip)
Catch ex As Exception
errmsg = String.Format("FTP服务器IP:{0}解析失败,请检查是否设置正确!", ip)
Return False
End Try
'*********输入数据检查结束*********
isConn = False
Dim ret As Boolean = False
Dim result(1024) As Byte
'连接返回,用户名返回,密码返回,退出返回
Dim pingStatus As Integer = 0
Dim userStatus As Integer = 0
Dim pasStatus As Integer = 0
Dim exitStatus As Integer = 0
timeoutObject = New ManualResetEvent(False)
Try
Dim receivelength As Integer
ssocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
ssocket.SendTimeout = timeout
ssocket.ReceiveTimeout = timeout
Try
ssocket.BeginConnect(New IPEndPoint(address, port), New AsyncCallback(AddressOf callBackMethod), ssocket)
If timeoutObject.WaitOne(timeout, False) = False Then '阻止当前线程
ssocket.Close()
ssocket = Nothing
pingStatus = -1 '超时返回状态码-1,并返回false值
End If
If isConn = True Then '连接状态
pingStatus = 200
Else
pingStatus = -1
End If
Catch ex As Exception
pingStatus = -1
End Try
If pingStatus = 200 Then '状态码200 - TCP连接成功
receivelength = ssocket.Receive(result)
pingStatus = getFtpReturnCode(result, receivelength) ' 连接状态
If pingStatus = 220 Then '状态码220 - FTP返回欢迎语
ssocket.Send(Encoding.Default.GetBytes(String.Format("{0}{1}", "USER " + ftpuser, Environment.NewLine)))
receivelength = ssocket.Receive(result)
userStatus = getFtpReturnCode(result, receivelength)
If userStatus = 331 Then
ssocket.Send(Encoding.Default.GetBytes(String.Format("{0}{1}", "PASS " + ftppas, Environment.NewLine)))
receivelength = ssocket.Receive(result)
pasStatus = getFtpReturnCode(result, receivelength)
If pasStatus = 230 Then
errmsg = String.Format("FTP:{0}@{1}登陆成功", ip, port)
ret = True
ssocket.Send(Encoding.Default.GetBytes(String.Format("{0}{1}", "QUIT", Environment.NewLine))) '登出FTP
receivelength = ssocket.Receive(result)
exitStatus = getFtpReturnCode(result, receivelength)
Else
errmsg = String.Format("FTP:{0}@{1}登陆失败,用户名或密码错误({2})", ip, port, pasStatus) '状态码230的错误
End If
Else
errmsg = String.Format("使用用户名:'{0}'登陆FTP:{1}@{2}时发生错误({3}),请检查FTP是否正常配置!", ftpuser, ip, port, userStatus) '状态码331的错误
End If
Else
errmsg = String.Format("FTP:{0}@{1}返回状态错误({2}),请检查FTP服务是否正常运行!", ip, port, pingStatus) '状态码220的错误
End If
Else
errmsg = String.Format("无法连接FTP服务器:{0}@{1},请检查FTP服务是否启动!", ip, port) '状态码200的错误
End If
Catch ex As Exception
'连接出错
errmsg = String.Format("FTP:{0}@{1}连接出错:", ip, port) + ex.Message
'Common.logger(errmsg) '写日志
ret = False
Finally
If ssocket IsNot Nothing Then
ssocket.Close() '关闭socket
ssocket = Nothing
End If
End Try
Return ret
End Function
Private Sub callBackMethod(ByVal asyncResult As IAsyncResult)
Try
ssocket = asyncResult.AsyncState
If ssocket IsNot Nothing Then
ssocket.EndConnect(asyncResult)
isConn = True
End If
Catch ex As Exception
isConn = False
Finally
timeoutObject.Set()
End Try
End Sub
''' <summary>
''' 传递FTP返回的byte数组和长度,返回状态码(Integer)
''' </summary>
''' <param name="retByte"></param>
''' <param name="retLen"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function getFtpReturnCode(ByVal retByte() As Byte, ByVal retLen As Integer) As Integer
Try
Dim str As String = Encoding.ASCII.GetString(retByte, 0, retLen).Trim
MsgBox(Encoding.UTF8.GetString(retByte)) '查看每次返回情况
Return Integer.Parse(str.Substring(0, 3))
Catch ex As Exception
Return -1
End Try
End Function
End Class