Brian Curless
Brian Curless

Reputation: 245

netstat -an Visual Basic

After searching the internet for days I have still no come up with what I would like.

Im looking to build a program using Visual basic that will list out all the port currently on a system.

I would like the output like netstat-an from command promt only problem is i need it to display in a ListBox.

Example 1

Private Sub GetAllPorts1()

    Dim activeConnection() As System.Net.NetworkInformation.TcpConnectionInformation = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties.GetActiveTcpConnections
    Dim portList As New ArrayList
    For Each conn As System.Net.NetworkInformation.TcpConnectionInformation In activeConnection
        ListBox1.Items.Add(conn.LocalEndPoint.Port)
    Next

End Sub

Works as expected only problem is i think its only certain ports.

Private Sub GetAllPorts2()
    Dim builder As New System.Text.StringBuilder
    Dim ipProps As System.Net.NetworkInformation.IPGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()

    For Each connection As System.Net.NetworkInformation.TcpConnectionInformation In ipProps.GetActiveTcpConnections
        builder.AppendFormat("{0} -> {1} - {2}{3}", connection.LocalEndPoint, connection.RemoteEndPoint, connection.State, Environment.NewLine)
        ListBox2.Items.Add(builder.ToString())
    Next

End Sub

This work a little better however there is way to much. Im not sure where it is getting this info.

Could someone help me out to get the output im looking for.

Ideally It would only list the ports that are being used. Such that if im running a webbrowser "80" or MSSQL "1433"

Upvotes: 1

Views: 3551

Answers (2)

Anthony Fornito
Anthony Fornito

Reputation: 424

Try moving "Dim builder As New System.Text.StringBuilder" to inside your loop.

Dim ipProps As System.Net.NetworkInformation.IPGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()
    For Each connection As System.Net.NetworkInformation.TcpConnectionInformation In ipProps.GetActiveTcpConnections
        Dim builder As New System.Text.StringBuilder
        builder.AppendFormat("{0} -> {1} - {2}{3}", connection.LocalEndPoint, connection.RemoteEndPoint, connection.State, Environment.NewLine)
        ListBox5.Items.Add(builder.ToString())
    Next

That should get rod of the extra output your seeing.

When working with looping in VB is the variable your declaring is not needed by any other part of the program put it within your element.

Upvotes: 1

ThatOneDude
ThatOneDude

Reputation: 1526

You may want to use GetTcpTable

Sample code:

Option Explicit

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Private Type MIB_TCPROW
    dwState As Long
    dwLocalAddr As Long
    dwLocalPort As Long
    dwRemoteAddr As Long
    dwRemotePort As Long
End Type

Private Const ERROR_SUCCESS            As Long = 0
Private Const MIB_TCP_STATE_CLOSED     As Long = 1
Private Const MIB_TCP_STATE_LISTEN     As Long = 2
Private Const MIB_TCP_STATE_SYN_SENT   As Long = 3
Private Const MIB_TCP_STATE_SYN_RCVD   As Long = 4
Private Const MIB_TCP_STATE_ESTAB      As Long = 5
Private Const MIB_TCP_STATE_FIN_WAIT1  As Long = 6
Private Const MIB_TCP_STATE_FIN_WAIT2  As Long = 7
Private Const MIB_TCP_STATE_CLOSE_WAIT As Long = 8
Private Const MIB_TCP_STATE_CLOSING    As Long = 9
Private Const MIB_TCP_STATE_LAST_ACK   As Long = 10
Private Const MIB_TCP_STATE_TIME_WAIT  As Long = 11
Private Const MIB_TCP_STATE_DELETE_TCB As Long = 12

Private Declare Function GetTcpTable Lib "iphlpapi.dll" _
  (ByRef pTcpTable As Any, _
   ByRef pdwSize As Long, _
   ByVal bOrder As Long) As Long

Private Declare Sub CopyMemory Lib "kernel32" _
   Alias "RtlMoveMemory" _
  (dst As Any, _
   src As Any, _
   ByVal bcount As Long)

Private Declare Function lstrcpyA Lib "kernel32" _
  (ByVal RetVal As String, ByVal Ptr As Long) As Long

Private Declare Function lstrlenA Lib "kernel32" _
  (ByVal Ptr As Any) As Long

Private Declare Function inet_ntoa Lib "wsock32" _
  (ByVal addr As Long) As Long

Private Declare Function ntohs Lib "wsock32" _
   (ByVal addr As Long) As Long  


Public Function GetInetStrFromPtr(Address As Long) As String

   GetInetStrFromPtr = GetStrFromPtrA(inet_ntoa(Address))

End Function


Private Sub Form_Load()

   With ListView1
      .View = lvwReport
      .ColumnHeaders.Add , , "Local IP Address"
      .ColumnHeaders.Add , , "Local Port"
      .ColumnHeaders.Add , , "Remote IP Address"
      .ColumnHeaders.Add , , "Remote Port"
      .ColumnHeaders.Add , , "State (dec)"
      .ColumnHeaders.Add , , "State Description"
   End With

End Sub


Private Sub ListView1_ColumnClick(ByVal ColumnHeader As MSComctlLib.ColumnHeader)

  ListView1.SortKey = ColumnHeader.Index - 1
  ListView1.SortOrder = Abs(Not ListView1.SortOrder = 1)
  ListView1.Sorted = True

End Sub


Public Function GetStrFromPtrA(ByVal lpszA As Long) As String

   GetStrFromPtrA = String$(lstrlenA(ByVal lpszA), 0)
   Call lstrcpyA(ByVal GetStrFromPtrA, ByVal lpszA)

End Function


Private Sub Command1_Click()

   Dim TcpRow As MIB_TCPROW
   Dim buff() As Byte
   Dim cbRequired As Long
   Dim nStructSize As Long
   Dim nRows As Long
   Dim cnt As Long
   Dim tmp As String
   Dim itmx As ListItem

   Call GetTcpTable(ByVal 0&, cbRequired, 1)

   If cbRequired > 0 Then

      ReDim buff(0 To cbRequired - 1) As Byte

      If GetTcpTable(buff(0), cbRequired, 1) = ERROR_SUCCESS Then

        'saves using LenB in the CopyMemory calls below
         nStructSize = LenB(TcpRow)

        'first 4 bytes is a long indicating the
        'number of entries in the table
         CopyMemory nRows, buff(0), 4

         For cnt = 1 To nRows

           'moving past the four bytes obtained
           'above, get one chunk of data and cast
           'into an TcpRow type
            CopyMemory TcpRow, buff(4 + (cnt - 1) * nStructSize), nStructSize

           'pass the results to the listview
            With TcpRow

               Set itmx = ListView1.ListItems.Add(, , GetInetStrFromPtr(.dwLocalAddr))
               itmx.SubItems(1) = ntohs(.dwLocalPort)
               itmx.SubItems(2) = GetInetStrFromPtr(.dwRemoteAddr)
               itmx.SubItems(3) = ntohs(.dwRemotePort)
               itmx.SubItems(4) = (.dwState)

              'the MSDN has a description defined only
              'for the MIB_TCP_STATE_DELETE_TCB member.
               Select Case .dwState
                  Case MIB_TCP_STATE_CLOSED:       tmp = "closed"
                  Case MIB_TCP_STATE_LISTEN:       tmp = "listening"
                  Case MIB_TCP_STATE_SYN_SENT:     tmp = "sent"
                  Case MIB_TCP_STATE_SYN_RCVD:     tmp = "received"
                  Case MIB_TCP_STATE_ESTAB:        tmp = "established"
                  Case MIB_TCP_STATE_FIN_WAIT1:    tmp = "fin wait 1"
                  Case MIB_TCP_STATE_FIN_WAIT2:    tmp = "fin wait 1"
                  Case MIB_TCP_STATE_CLOSE_WAIT:   tmp = "close wait"
                  Case MIB_TCP_STATE_CLOSING:      tmp = "closing"
                  Case MIB_TCP_STATE_LAST_ACK:     tmp = "last ack"
                  Case MIB_TCP_STATE_TIME_WAIT:    tmp = "time wait"
                  Case MIB_TCP_STATE_DELETE_TCB:   tmp = "TCB deleted"
               End Select

               itmx.SubItems(5) = tmp
               tmp = ""

            End With

         Next
      End If
   End If

End Sub

Above from mvps.org

Upvotes: 2

Related Questions