如何检测在给定TCP端口上侦听的应用程序?

时间:2012-11-12 00:00:41

标签: vb.net tcp-port

如何检测哪些应用程序(如果有)正在侦听Windows上的给定TCP端口?这是xampp这样做的:

enter image description here

我更喜欢在VB.NET中这样做,我想为用户提供关闭该应用程序的选项。

2 个答案:

答案 0 :(得分:0)

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
这对我有帮助:)。

答案 1 :(得分:0)

我没有足够的代表对已接受的答案发表评论,但我想说我认为检查异常是非常糟糕的做法!

我花了很长时间寻找一个非常类似的问题的解决方案,当我遇到IPGlobalProperties时,我正要沿着P / Invoke GetExtendedTcpTable路线走下去。 我尚未对此进行适当的测试,但这样的事情......

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

然后......

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

我希望有人发现这比我做得更快!