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

I'd prefer to do this in VB.NET, and I want to offer the user the option to close that app.
On
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!
this helped me :)