2013-12-20 106 views
0

我試圖做一個服務器狀態檢查器,可以在端口上ping通。VB.NET ping端口

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    If My.Computer.Network.Ping("192.168.2.10:21") Then 
     PictureBox1.BackColor = Color.LimeGreen 
     Label1.Text = "Online!" 
     Label1.ForeColor = Color.LimeGreen 

    Else 
     PictureBox1.BackColor = Color.DarkRed 
     Label1.Text = "Offline!" 
     Label1.ForeColor = Color.DarkRed 
    End If 
End Sub 

當我這樣做,它不會返回任何結果。沒有離線或在線。

+2

你調試過嗎? – qwr

+0

@qwr是的。就像我說的,它沒有返回任何數據。 – bk320

+0

@ user3059238,'Network.Ping'必須返回一個值,'True'或'False' –

回答

0

正如我在評論中指出的那樣,ping與端口將不起作用。因此,您只能檢查遠程可用性。並與"ipaddress:port"寫作應該拋出錯誤

平通過發送Internet控制消息協議(ICMP)

其他方式這樣做的工作是使用TCP

在這裏,我寫了ping命令正確方法端口和Neetwork.Ping

Private Function checkport(hostname As String, port As Integer 
          ) As Boolean 
    Dim client As New TcpClient(AddressFamily.InterNetwork) 


    client.BeginConnect(hostname, port, 
         Sub(x) 
          Dim tcp As TcpClient = CType(x.AsyncState, TcpClient) 
          Try 
           tcp.EndConnect(x) 
           SetIndicators(True) 

          Catch ex As Exception 
           'error 
           SetIndicators(False) 

          End Try 
          tcp.Close() 
         End Sub, client 
         ) 


    Return (False) 
End Function 

'Cross-thread safe code using InvokeRequired Pattern 
Private Sub SetIndicators(ByVal ok As Boolean) 

    If Me.Label1.InvokeRequired Then 
     Dim d As New Action(Of Boolean)(AddressOf SetIndicators) 
     Me.Invoke(d, ok) 
    Else 
     If ok = True Then 
      Label1.Text = "Online!" 
      Label1.ForeColor = Color.LimeGreen 
     Else 
      Label1.Text = "Offline!" 
      Label1.ForeColor = Color.DarkRed 
     End If 
    End If 
End Sub 

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
    Try 
     ' If My.Computer.Network.Ping("192.168.1.1") Then 

      ' Label1.Text = "Online!" 
      ' Label1.ForeColor = Color.LimeGreen 

     ' Else 
      ' Label1.Text = "Offline!" 
      ' Label1.ForeColor = Color.DarkRed 
     ' End If 
     SetIndicators(My.Computer.Network.Ping("stackoverflow.com")) 
    Catch ex As Exception 
     'error occured 
     MessageBox.Show(ex.Message) 

    End Try 

End Sub 

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click 
    'result can be returned late according connection timeout 
    checkport("stackoverflow.com", 450) 
End Sub 

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click 
    'should return online cause http port accessible 
    checkport("stackoverflow.com", 80) 
End Sub 
+0

這不僅僅是檢查一個端口是否在路由器上打開?不知道這回答OP的帖子。當我的局域網上的服務器正在運行並且未運行時,已經嘗試過它測試端口21 - 返回「在線!」當服務器是開啓和關閉 - 大概是因爲端口21是打開+在我的路由器轉發? – stigzler

+0

首先,如果您使用DHCP,請檢查遠程本地IP地址的正確性。其次,檢查路由器。這不僅僅是檢查路由器上的端口是否打開?無論如何,它只會在連接到偵聽21(ftp)的服務器時纔會在線。在大多數路由器中,只有一個端口被偵聽(80),我們用它來配置路由器本身。 – qwr