VB.NET: Check if a TCP Port on a remote site answers requests

July 10, 2015 ยท View on GitHub

Imports System.Net.Sockets

Private Function _CheckTCPPort(ByVal sIPAdress As String, ByVal iPort As Integer, Optional ByVal iTimeout As Integer = 5000) Dim socket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) ' Connect using a timeout (default 5 seconds) Dim result As IAsyncResult = socket.BeginConnect(sIPAdress, iPort, Nothing, Nothing) Dim success As Boolean = result.AsyncWaitHandle.WaitOne(iTimeout, True)

If Not success Then
    ' NOTE, MUST CLOSE THE SOCKET
    socket.Close()
    Return False
End If
Return True

End Function