我试图建立一个可以在端口上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
当我这样做时,它不会返回任何结果。没有离线或在线。
答案 0 :(得分:0)
正如我在评论中所提到的那样ping端口不起作用。因此,您只能检查远程可用性。用"ipaddress:port"
编写应该抛出错误
Ping通过发送Internet控制消息协议(ICMP)
进行操作
其他方法是使用TCP
在这里,我为Pinging port和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