正如我在評論中指出的那樣,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
來源
2013-12-20 21:21:53
qwr
你調試過嗎? – qwr
@qwr是的。就像我說的,它沒有返回任何數據。 – bk320
@ user3059238,'Network.Ping'必須返回一個值,'True'或'False' –