Ich habe mitbekommen, dass ab und zu auf diesen Post verwiesen wird. Da ich dieses Beispiel aber für nicht besonders gut geschrieben halte (kein Wunder; mein erstes Projekt), poste ich mal ein aktuelleres, kürzeres, besseres Beispiel.
Imports System.Net
Imports System.Net.NetworkInformation
Public Class PingChecker
Public Event CheckCompleted(ByVal sender As Object, ByVal successResults As _
PingCheckResult())
Private mSuccessResults As List(Of PingCheckResult)
Private mRunningPings As List(Of Ping)
Private mID As Long = 0
Public Sub GetLocalIPs(Optional ByVal timeout As Integer = 8000)
GetLocalIPs(0, 1, 0, 255, timeout)
End Sub
Public Sub GetLocalIPs(ByVal n1Start As Integer, ByVal n1End As Integer, _
Optional ByVal timeout As Integer = 8000)
GetLocalIPs(n1Start, n1End, 0, 255, timeout)
End Sub
Public Sub GetLocalIPs(ByVal n1Start As Integer, ByVal n1End As Integer, _
ByVal n2Start As Integer, ByVal n2End As Integer, Optional ByVal timeout _
As Integer = 8000)
mSuccessResults = New List(Of PingCheckResult)
mRunningPings = New List(Of Ping)
mID += 1
For n1 As Integer = n1Start To n1End
For n2 As Integer = n2Start To n2End
Dim ping As New Ping
mRunningPings.Add(ping)
AddHandler ping.PingCompleted, AddressOf ping_PingCompleted
ping.SendAsync("192.168." & n1 & "." & n2, timeout, mID)
Next
Next
End Sub
Private Sub ping_PingCompleted(ByVal sender As Object, ByVal e As _
System.Net.NetworkInformation.PingCompletedEventArgs)
If e.Reply.Status = IPStatus.Success And CLng(e.UserState) = mID Then
Dim result As New PingCheckResult
result.Address = e.Reply.Address
result.Delay = e.Reply.RoundtripTime
mSuccessResults.Add(result)
End If
Dim ping As Ping = CType(sender, Ping)
If mRunningPings.Contains(ping) Then mRunningPings.Remove(ping)
ping.Dispose()
If mRunningPings.Count = 0 Then RaiseEvent CheckCompleted(Me, _
mSuccessResults.ToArray)
End Sub
End Class
Public Class PingCheckResult
Private mAddress As IPAddress
Private mDelay As Long = 0
Public Property Address() As IPAddress
Get
Return mAddress
End Get
Set(ByVal value As IPAddress)
mAddress = value
End Set
End Property
Public Property Delay() As Long
Get
Return mDelay
End Get
Set(ByVal value As Long)
mDelay = value
End Set
End Property
End Class Anwendung (ListView hat 2 Columns; n1Start etc sind TextBoxen):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Dim checker As New PingChecker
AddHandler checker.CheckCompleted, AddressOf checker_CheckCompleted
checker.GetLocalIPs(CInt(n1Start.Text), CInt(n1End.Text), CInt( _
n2Start.Text), CInt(n2End.Text))
End Sub
Private Sub checker_CheckCompleted(ByVal sender As Object, ByVal results As _
PingCheckResult())
For Each result As PingCheckResult In results
ListView1.Items.Add(New ListViewItem(New String(1) _
{result.Address.ToString, result.Delay.ToString}))
Next
End Sub Maas |