如何检测哪些应用程序(如果有)正在侦听 Windows 上的给定 TCP 端口?这是 xampp 这样做的:
我更喜欢在 VB.NET 中执行此操作,并且我想为用户提供关闭该应用程序的选项。
我没有足够的代表来评论接受的答案,但我会说我认为检查是否发生异常是非常糟糕的做法!
我花了很长时间寻找一个非常相似的问题的解决方案,并且当我遇到IPGlobalProperties
. 我还没有正确测试这个,但是像这样的东西......
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
我希望有人比我更快地发现这个有用!
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
这对我有帮助:)