I've been looking into using sockets for a few web based test applets. I've cobbled a quick piece of test code together as follows to get a feel for how .NET works, however it is not behaving as I would expect with regards to exceptions.
When szHost is a valid or invalid FQDN or a valid IP address the function performs as expected . However if an invalid IP address is supplied (that is the host does not exist) I would expect the Connect method to throw a SocketException but it never does. It just continues on as if it successfully established a connection which it could not possibly have done.
I must be missing something obvious because this seems like it should be trivial. I've mucked around with the different ways of using Connect (ipEndPoint etc.) but the result is the same. Any thoughts?
When szHost is a valid or invalid FQDN or a valid IP address the function performs as expected . However if an invalid IP address is supplied (that is the host does not exist) I would expect the Connect method to throw a SocketException but it never does. It just continues on as if it successfully established a connection which it could not possibly have done.
I must be missing something obvious because this seems like it should be trivial. I've mucked around with the different ways of using Connect (ipEndPoint etc.) but the result is the same. Any thoughts?
Code:
Public Function TcpSocketTest(ByVal szHost As String, ByVal nPort As Int32, ByRef szResponseData As String, ByRef szResponseBytes As Int32) As Boolean
TcpSocketTest = False
szResponseData = String.Empty
szResponseBytes = 0
Try
Dim objTcpClient As New TcpClient
Dim objNetworkStream As NetworkStream
Dim bData = New Byte(1024) {}
Dim nBytes As Int32
objTcpClient.Connect(szHost, nPort)
objNetworkStream = objTcpClient.GetStream()
If objNetworkStream.DataAvailable Then
nBytes = objNetworkStream.Read(bData, 0, bData.Length)
szResponseData = System.Text.Encoding.ASCII.GetString(bData, 0, nBytes)
End If
objTcpClient.Close()
TcpSocketTest = True
szResponseBytes = nBytes
objNetworkStream = Nothing
objTcpClient = Nothing
Catch e As ArgumentNullException
szResponseData = e.Message.ToString()
Catch e As SocketException
szResponseData = e.Message.ToString()
End Try
End Function