VB.Net checking if a port is open and accepting connections
<p>I'm writing a VB.Net app which connects to a remote server and listens for data on that port.</p>

<p>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.</p>

<p>Any ideas why the exception handler is not firing ?</p>

<pre><code>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()

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

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

        Return False
    End Function
</code></pre>

<p>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.</p>

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