Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Continuous ping on listbox items

Status
Not open for further replies.

Shift838

IS-IT--Management
Jan 27, 2003
987
0
0
US
All. I am trying to make a program that I can import a text file of servers into a list view and do a non-stop continuous ping on each of the items in a listview.

The list view gives me multiple columns that I can put data in, server name, Reply status, last timeout, roundtrip time, and current ping total time.

i have already been able to import the servers into the listview with no issues. I want to do a ping on each of the servers in the list view. I figured i need to do a listview.items.count -1 to get the exact number of servers in the item list of column 0.

I already have ping code that works with a single server name. how could i incorporate the below code to do a constant ping and never stop on each server going line by line, pulling the reply of (success or failure) putting the last timeout (current date/time), round trip in milliseconds and current total time of the current ping.

to use the below code I use the below.

I know i need to somehow get the servername out of the listview on column one and code it to cycle through it with an endless loop some how. I will also want to enable the check boxes so I can delete the ones that are selected. I have not clue how to do that. any help is greatly appreciated..

Code:
PingSystem(txthostname2.Text)

Code:
Sub PingSystem(ByVal HostName As String)
        'Ping the system and display results to the txtPingResult control

        'Clear any previous ping results
        txtpingresults.Text = ""

        Dim pingsender As New Ping
        Dim options As New PingOptions

        'Modify the default fragmentation behavior
        options.DontFragment = True

        'Create a buffer of 32 bytes of data to be transmitted.      
        Dim data As String = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
        Dim buffer As Byte() = Encoding.ASCII.GetBytes(data)
        Dim timeout As Integer = 120

        Try
            'Attempt ping
            Dim reply As PingReply = pingsender.Send(HostName, timeout, buffer, options)
            'Ping the target system 4 times to check for consistent results
            For i As Integer = 1 To 4
                If (reply.Status = IPStatus.Success) Then
                    txtpingresults.Text += String.Format("Reply from:{1}: Bytes={2} time{3} TTL={4}{0}", _
                        vbCrLf, reply.Address.ToString, reply.Buffer.Length, GetMs(reply.RoundtripTime), reply.Options.Ttl)
                Else
                    txtpingresults.Text += String.Format("Ping Failed:{1}{0}", vbCrLf, reply.Status.ToString)
                End If
                Me.Refresh()
                'Pause for 1 second before pinging again
                System.Threading.Thread.Sleep(1000)
            Next
        Catch ex As Exception
            txtpingresults.Text += String.Format("Ping Failed on host:{1}{0}Error:{2}{0}Detail:{3}{0}", vbCrLf, HostName, ex.Message, ex.InnerException)
        End Try


    End Sub

 
i have gotten most of the ping to work. I am wondering how I can update the listview subitems (columns) when the ping happens. I am currently importing a text file to add the items (servernames) to the list view with the below code.

Ping module is below and working as well.

I need to be able to update the listview. The list view has 4 the servers that are imported as items. I have a total of 4 colums (Server names, Ping Result, Last Time Out, and Roundtrip time).

I cannot figure out how to get the subitems (ping reslult, last time out and roundtrip time) to update with the results that need to be based on the selected item (Servername)

Help please..

Code:
'imports a text file that contains server names into the listview via a Tool Strip Menu Item.

Private Sub ImportServerListToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportServerListToolStripMenuItem.Click
        Dim fd As OpenFileDialog = New OpenFileDialog()
        Dim strFileName As String

        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        fd.FilterIndex = 2
        fd.RestoreDirectory = True

        If fd.ShowDialog() = DialogResult.OK Then
            strFileName = fd.FileName
        End If


        If File.Exists(strFileName) Then

            Dim serverline As String
            Dim ServerImport As New System.IO.StreamReader(strFileName)

            Do While ServerImport.Peek() <> -1
                serverline = ServerImport.ReadLine()
                lstServers.Items.Add(serverline, 0)

            Loop

            MsgBox("Servers imported!")


            Dim servertotal As Integer

            servertotal = lstServers.Items.Count

            ServerImport.Close()
        Else
            MsgBox("FILE NOT FOUND!  Check your Server import file paths!")
        End If
    End Sub

Code:
'ping module
Imports System.Net.NetworkInformation
Imports System.Text
Module MultiPing
    Sub MultiPingSystem(ByVal HostName As String)
        'Ping the system and display results to the txtPingResult control

        'Clear any previous ping results
        pingresults = ""

        Dim pingsender As New Ping
        Dim options As New PingOptions

        'Modify the default fragmentation behavior
        options.DontFragment = True

        'Create a buffer of 32 bytes of data to be transmitted.      
        Dim data As String = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
        Dim buffer As Byte() = Encoding.ASCII.GetBytes(data)
        Dim timeout As Integer = 120

        Try
            'Attempt ping
            Dim reply As PingReply = pingsender.Send(HostName, timeout, buffer, options)
            'Ping the target system 4 times to check for consistent results
            'For i As Integer = 1 To 4
            If (reply.Status = IPStatus.Success) Then
                pingresults = "Success"

                lasttimeout = ""
                roundtriptime = GetMs(reply.RoundtripTime)

                'pingresults += String.Format("Reply from:{1}: Bytes={2} time{3} TTL={4}{0}", _
                'vbCrLf, reply.Address.ToString, reply.Buffer.Length, GetMs(reply.RoundtripTime), reply.Options.Ttl)
            Else
                pingresults = "Ping Failed"
            End If

            'Pause for 1 second before pinging again
            System.Threading.Thread.Sleep(1000)
            'Next
        Catch ex As Exception
            pingresults = "Ping Failed"
        End Try
    End Sub
    Function GetMs(ByVal ResponseTime As Integer) As String
        'accept and integer value and return a friendly string
        '  reflecting number of milliseconds
        If ResponseTime = 0 Then
            Return "<1ms"
        Else
            Return String.Format("={0}ms", ResponseTime.ToString)
        End If
    End Function
End Module

Code:
'Start pings on multiple servers

Private Sub cmdStartPing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStartPing.Click
        Dim serverlist, x As Integer
        Dim servers As String


        serverlist = lstServers.Items.Count - 1
        Dim lv As ListViewItem = lstServers.Items(serverlist)
        Dim lvstr As String = lv.Text.ToString
        
        For x = 0 To serverlist
            
            servers = lstServers.Items(x).Text

            
            lstServers.Focus()
            lstServers.Items.Item(x).Selected = True
            
            MultiPingSystem(servers)
            

            
        Next
    End Sub
 
[sub]I just did something like this a couple days ago. I used a form with 2 ListView controls (ListView1 is a list of teh computer names to check, ListView2 is the results; views displayed side-by-side/overlapping to hide ListView1 scrollbars) tied to a single Vscrollbar and such, and mine checks to see if a program is running on the remote machine along with logged in username (run with admin rights to get those), and it works OK. I still need to thread or background my pings to keep the program from freezing up while running the checks but this does work. It also isn't the prettiest thing but I'm not done with it yet. I wrote this in VB Express 2010, and it looks like you and I both found teh MS article on the Ping.Sender. :)

I still have a couple bugs to work out yet myself, like why this "If ListView1.SelectedItems(0).SubItems(1).Text = "Y" Then" doesn't always seem to work. Once an "N" value is encountered in the subitem, then it stays as "N" for the rest of the checks even if a listed machine after it is "Y". That subitme in the machine list marks it as a PC (Y) or not (N) and if not bypasses checking for the running program or the username.

Code:
Public Sub CheckIt()
        ListView1.TopItem.Selected = True

        If My.Computer.Network.IsAvailable() Then
            ListView2.Items.Clear()
            ListView1.Focus()
            ListView1.Refresh()
            ListView1.Update()

            For i As Int32 = 0 To ListView1.Items.Count - 1 Step 1

                Dim host As String = ListView1.SelectedItems(0).Text
                If IsComputerOnline(host) Then
                    Try
                        Dim objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & host & "\root\cimv2")
                        Dim colComputer = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
                        For Each objComputer In colComputer
                            TempStr(0) = "Online"
                            If ListView1.SelectedItems(0).SubItems(1).Text = "Y" Then
                                TempStr(2) = objComputer.UserName.ToString.Substring(4, objComputer.UserName.ToString.Length - 4)
                                TempStr(1) = IsProcessRunning(host).ToString
                            Else
                                TempStr(2) = "N/A"
                                TempStr(1) = "N/A"
                            End If
                            TempStr(3) = replypingms
                            TempNode = New ListViewItem(TempStr)
                            ListView2.Items.Add(TempNode)
                            ListView2.Items(i).BackColor = Color.White
                            ListView2.Items(i).ForeColor = Color.Black
                        Next
                    Catch
                        TempStr(0) = "Online"
                        TempStr(1) = "AUTH Fail"
                        TempStr(2) = "AUTH Fail"
                        TempStr(3) = replypingms
                        TempNode = New ListViewItem(TempStr)
                        ListView2.Items.Add(TempNode)
                        ListView2.Items(i).BackColor = Color.White
                        ListView2.Items(i).ForeColor = Color.Black
                    End Try
                Else
                    TempStr(0) = "* OFFLINE *"
                    TempStr(1) = Nothing
                    TempStr(2) = "* UNREACHABLE *"
                    TempStr(3) = Nothing
                    TempNode = New ListViewItem(TempStr)
                    ListView2.Items.Add(TempNode)
                    ListView2.Items(i).BackColor = Color.Black
                    ListView2.Items(i).ForeColor = Color.White
                End If
                Try
                    ListView1.Items(ListView1.SelectedItems(0).Index + 1).Selected = True
                Catch
                End Try
            Next
        Else
            For i As Int32 = 0 To ListView1.Items.Count - 1 Step 1
                Dim host As String = ListView1.SelectedItems(0).Text
                TempStr(0) = "** FAIL **"
                TempStr(1) = "Network Offline"
                TempStr(2) = "Check your connection"
                TempNode = New ListViewItem(TempStr)
                ListView2.Items.Add(TempNode)
                ListView2.Items(i).BackColor = Color.Red
                ListView2.Items(i).ForeColor = Color.Yellow
                Try
                    ListView1.Items(ListView1.SelectedItems(0).Index + 1).Selected = True
                Catch
                End Try
            Next
        End If
        ListView2.Refresh()

        ListView1.TopItem.Selected = True
        VScrollBar1.Maximum = ListView2.Items.Count - 1
    End Sub

    Public Function IsComputerOnline(hostname As String)
        ' check for the computer on the network
        'PingReply = Nothing
        Try
            Dim pingSender As New Ping()
            Dim options As New PingOptions()

            ' Use the default Ttl value which is 128,
            ' but change the fragmentation behavior.
            options.DontFragment = True
            options.Ttl = 128

            ' Create a buffer of 32 bytes of data to be transmitted.
            Dim data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
            Dim buffer() As Byte = Encoding.ASCII.GetBytes(Data)
            Dim timeout As Integer = 120
            Dim Reply As PingReply = pingSender.Send(hostname, timeout, buffer, options)
            If Reply.Status = IPStatus.Success Then
                GetPingMs(hostname)
                Return True
            Else
                Return False
            End If

        Catch
            Return False
        End Try
    End Function

    Public Shared Function GetPingMs(ByRef hostNameOrAddress As String)
        Dim ping As New System.Net.NetworkInformation.Ping
        Try
            Form1.replypingms = ping.Send(hostNameOrAddress).RoundtripTime
            Return True
        Catch
            Return False
        End Try
    End Function

So maybe some of my crap-code can help you out. For the results, I store them in TempStr (Dim TempStr(3) As String) and then assemble them in TempNode (Dim TempNode As ListViewItem = Nothing), then add TempNode to the ListView2 as an item (ListView2.Items.Add(TempNode)). First, when I start a new round of checks, I clear the items from the list with ListView2.Items.Clear() instead of the whole listview so I don't trash the columns, then it adds each result to the view as it cycles through them.[/sub]
 
gawd, that made a mess of the code didn't it. Maybe this'll work better...
Code:
  Public Sub CheckIt()
        ListView1.TopItem.Selected = True

        If My.Computer.Network.IsAvailable() Then
            ListView2.Items.Clear()
            ListView1.Focus()
            ListView1.Refresh()
            ListView1.Update()

            For i As Int32 = 0 To ListView1.Items.Count - 1 Step 1

                Dim host As String = ListView1.SelectedItems(0).Text
                If IsComputerOnline(host) Then
                    Try
                        Dim objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & host & "\root\cimv2")
                        Dim colComputer = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
                        For Each objComputer In colComputer
                            TempStr(0) = "Online"
                            If ListView1.SelectedItems(0).SubItems(1).Text = "Y" Then
                                TempStr(2) = objComputer.UserName.ToString.Substring(4, objComputer.UserName.ToString.Length - 4)
                                TempStr(1) = IsProcessRunning(host).ToString
                            Else
                                TempStr(2) = "N/A"
                                TempStr(1) = "N/A"
                            End If
                            TempStr(3) = replypingms
                            TempNode = New ListViewItem(TempStr)
                            ListView2.Items.Add(TempNode)
                            ListView2.Items(i).BackColor = Color.White
                            ListView2.Items(i).ForeColor = Color.Black
                        Next
                    Catch
                        TempStr(0) = "Online"
                        TempStr(1) = "AUTH Fail"
                        TempStr(2) = "AUTH Fail"
                        TempStr(3) = replypingms
                        TempNode = New ListViewItem(TempStr)
                        ListView2.Items.Add(TempNode)
                        ListView2.Items(i).BackColor = Color.White
                        ListView2.Items(i).ForeColor = Color.Black
                    End Try
                Else
                    TempStr(0) = "* OFFLINE *"
                    TempStr(1) = Nothing
                    TempStr(2) = "* UNREACHABLE *"
                    TempStr(3) = Nothing
                    TempNode = New ListViewItem(TempStr)
                    ListView2.Items.Add(TempNode)
                    ListView2.Items(i).BackColor = Color.Black
                    ListView2.Items(i).ForeColor = Color.White
                End If
                Try
                    ListView1.Items(ListView1.SelectedItems(0).Index + 1).Selected = True
                Catch
                End Try
            Next
        Else
            For i As Int32 = 0 To ListView1.Items.Count - 1 Step 1
                Dim host As String = ListView1.SelectedItems(0).Text
                TempStr(0) = "** FAIL **"
                TempStr(1) = "Network Offline"
                TempStr(2) = "Check your connection"
                TempNode = New ListViewItem(TempStr)
                ListView2.Items.Add(TempNode)
                ListView2.Items(i).BackColor = Color.Red
                ListView2.Items(i).ForeColor = Color.Yellow
                Try
                    ListView1.Items(ListView1.SelectedItems(0).Index + 1).Selected = True
                Catch
                End Try
            Next
        End If
        ListView2.Refresh()

        ListView1.TopItem.Selected = True
        VScrollBar1.Maximum = ListView2.Items.Count - 1
    End Sub

    Public Function IsComputerOnline(hostname As String)
        ' check for the computer on the network
        'PingReply = Nothing
        Try
            Dim pingSender As New Ping()
            Dim options As New PingOptions()

            ' Use the default Ttl value which is 128,
            ' but change the fragmentation behavior.
            options.DontFragment = True
            options.Ttl = 128

            ' Create a buffer of 32 bytes of data to be transmitted.
            Dim data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
            Dim buffer() As Byte = Encoding.ASCII.GetBytes(Data)
            Dim timeout As Integer = 120
            Dim Reply As PingReply = pingSender.Send(hostname, timeout, buffer, options)
            If Reply.Status = IPStatus.Success Then
                GetPingMs(hostname)
                Return True
            Else
                Return False
            End If

        Catch
            Return False
        End Try
    End Function

    Public Shared Function GetPingMs(ByRef hostNameOrAddress As String)
        Dim ping As New System.Net.NetworkInformation.Ping
        Try
            Form1.replypingms = ping.Send(hostNameOrAddress).RoundtripTime
            Return True
        Catch
            Return False
        End Try
    End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top