Philip Lee Philip Lee - 1 year ago 144 Question

VB.Net checking if a port is open and accepting connections

I'm writing a VB.Net app which connects to a remote server and listens for data on that port.

I've got the following function which checks that the IP/port in question is listening for connections or not. When the process on the remote port is running is works fine but when it's not running rather than the exception handler running I get an ugly dialogue box in Visual Studio rather when I run it.

Any ideas why the exception handler is not firing ?

Private Function testSelectedPort(ip As String, port As Integer) As Boolean
' Function to open a socket to the specified port to see if it is listening

' Connect to socket
Dim testSocket As New System.Net.Sockets.TcpClient()

testSocket.Connect(ip, port)
' The socket is accepting connections
Return True

Catch ex As Exception
' The port is not accepting connections
Return False
End Try

Return False
End Function

The error that's being thrown in "No connection could be made because the target machine actively refused it" and it's being thrown at the testSocket.Connect(ip, port) line.

I thought that it would execute the code in the Catch section if it failed to connect ?

Answer Source

Once the exception is thrown it should be handled by the Catch-block. There are only a few exceptions that are generally not very easy to handle via Try/Catch (for instance a System.AccessViolationException), but those do not include the errors a socket might throw.

Please make sure that you haven't ticked the specific exception type to break when thrown, in the Exception Settings window

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download