Question

How do I detect what application, if any, is listening on a given TCP port on Windows? Here's xampp doing this:

enter image description here

I'd prefer to do this in VB.NET, and I want to offer the user the option to close that app.

Was it helpful?

Solution 2

Dim hostname As String = "server1"
Dim portno As Integer = 9081
Dim ipa As IPAddress = DirectCast(Dns.GetHostAddresses(hostname)(0), IPAddress)
Try
    Dim sock As New System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
    sock.Connect(ipa, portno)
    If sock.Connected = True Then
        ' Port is in use and connection is successful
        MessageBox.Show("Port is Closed")
    End If

    sock.Close()
Catch ex As System.Net.Sockets.SocketException
    If ex.ErrorCode = 10061 Then
        ' Port is unused and could not establish connection 
        MessageBox.Show("Port is Open!")
    Else
        MessageBox.Show(ex.Message)
    End If
End Try

this helped me :)

OTHER TIPS

I don't have enough rep to comment on the accepted answer, but I would say that I think checking for an exception to occur is pretty bad practice!

I spent quite a while searching for a solution to a very similar problem, and was about to go down the P/Invoke GetExtendedTcpTable route when I happened upon IPGlobalProperties. I haven't tested this properly yet, but something like this...

Imports System.Linq
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Windows.Forms

And then...

Dim hostname = "server1"
Dim portno = 9081
Dim ipa = Dns.GetHostAddresses(hostname)(0)
Try
  ' Get active TCP connections - the GetActiveTcpListeners is also useful if you're starting up a server...
  Dim active = IPGlobalProperties.GetIPGlobalProperties.GetActiveTcpConnections
  If (From connection In active Where connection.LocalEndPoint.Address.Equals(ipa) AndAlso connection.LocalEndPoint.Port = portno).Any Then
    ' Port is being used by an active connection
    MessageBox.Show("Port is in use!")
  Else
    ' Proceed with connection
    Using sock As New Sockets.Socket(Sockets.AddressFamily.InterNetwork, Sockets.SocketType.Stream, Sockets.ProtocolType.Tcp)
      sock.Connect(ipa, portno)
      ' Do something more interesting with the socket here...
    End Using
  End If

Catch ex As Sockets.SocketException
  MessageBox.Show(ex.Message)
End Try

I hope someone finds this useful quicker than I did!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top