如何檢測Windows上的給定TCP端口上正在監聽的應用程序(如果有)?這裏的XAMPP這樣做:如何檢測給定TCP端口上正在監聽的應用程序?
我寧願做在VB.NET,我想向用戶提供關閉該應用程序的選項。
如何檢測Windows上的給定TCP端口上正在監聽的應用程序(如果有)?這裏的XAMPP這樣做:如何檢測給定TCP端口上正在監聽的應用程序?
我寧願做在VB.NET,我想向用戶提供關閉該應用程序的選項。
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
幫我:)
我沒有足夠的代表在接受的答案發表評論,但我要說的是,我想檢查出現異常是非常不好的做法!
我花了很長一段時間尋找解決方案,以解決一個非常類似的問題,並且當我碰到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
我希望有人發現了比我這個有用的更快!
您可以調用'netstat -no'並解析其輸出。 – vladr
好的事情是,我不會使用netstat等。我工作的一些項目,是用來控制Apache的MySQL和幾個更多的應用程序,所以我想在文本框中點擊開始按鈕後像「端口80被APP NAME使用Apache無法啓動。「 ? – Onlykl
不知道爲什麼這會吸引這麼多downvotes。這是一個合理的問題,比Process.Start(「netstat -no」)更好的答案。如果新用戶訪問該網站併發布可以改進的問題,請按照常見問題解答並幫助用戶改進問題和/或告訴他有什麼問題。 –