Sunday, February 17, 2008

Simple Port Scan

The following function will check to see if connectivity is enabled for a particular host on a particular port via TCP/IP:

Function ScanPort(ByVal strHost As String, ByVal intPort As Integer) As Boolean
    Dim aobjIPs() As System.Net.IPAddress = System.Net.Dns.GetHostEntry(strHost).AddressList
    If aobjIPs.Length > 0 Then
        Dim objEndpoint As New System.Net.IPEndPoint(aobjIPs(0), intPort)
        Using s As New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
            Try
                s.Connect(objEndpoint)
                Return s.Connected
            Catch ex As Exception
                Return False
            End Try
        End Using
    Else
        Return False
    End If
End Function