Results 1 to 40 of 40

Thread: [2008] Ping multiple IP's

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jan 2008
    Posts
    120

    [2008] Ping multiple IP's

    Ok so for a while now ive had a program that pings about 15 computers on my network, but the way i have it is pretty messy, id like to somehow make the code a bit cleaner.

    so what i have is something like this

    vb Code:
    1. Private Sub Ping()
    2.         If My.Settings.server1ip <> String.Empty Then
    3.             Dim MyPing As New System.Net.NetworkInformation.Ping
    4.             Dim MyPingResult As System.Net.NetworkInformation.PingReply = MyPing.Send(My.Settings.server1ip)
    5.             If MyPingResult.Status = Net.NetworkInformation.IPStatus.Success Then
    6.                 Me.txtServer1Status.ForeColor = Color.Green
    7.                 Me.txtServer1Status.Text = ("Online")
    8.                 Me.txtServer1Reply.Text = (MyPingResult.RoundtripTime.ToString & " ms")
    9.                 If MyPingResult.RoundtripTime.ToString > 200 Then
    10.                     Me.txtServer1Reply.ForeColor = Color.Red
    11.                 Else
    12.                     If MyPingResult.RoundtripTime.ToString > 100 Then
    13.                         Me.txtServer1Status.ForeColor = Color.Orange
    14.                     End If
    15.                 End If
    16.             Else
    17.                 Me.txtServer1Status.ForeColor = Color.Red
    18.                 Me.txtServer1Status.Text = ("Failed")
    19.             End If
    20.         Else
    21.             Me.txtServer1Status.Text = ("No IP Entered")
    22.         End If
    23.     End Sub

    so what i have is i copy that code 10 times and rename each sub to ping1 ping2 ping 3 etc. then i have a button with code like this

    vb Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    2.         Ping()
    3.         Ping2()
    4.         Ping3()
    5.         Ping4()
    6.         Ping5()
    7.         Ping6()
    8.         Ping7()
    9.  
    10.     End Sub

    so that runs all my pings... now as you can see its a mess, and im sure its not the best way to go about it. so is there a way i can mold all that into 1 sub? i dont want to ping a range of computers, i want to ping a specific 15-20 ip's.

    thanks in advance.

  2. #2
    PowerPoster 2.0 Negative0's Avatar
    Join Date
    Jun 2000
    Location
    Southeastern MI
    Posts
    4,367

    Re: [2008] Ping multiple IP's

    Have your Ping function take the status textbox as a parameter. Then you modify the textbox in your ping function.

  3. #3
    New Member
    Join Date
    Oct 2008
    Posts
    1

    Re: [2008] Ping multiple IP's

    Do you have a screen shot of this program. I'm going to see if I can replicate what you have.

  4. #4
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    One way you could do this would be to create a separate thread for each ping, that way you are not waiting on the response of your first ping, before the second one happens.

    Here is some code that I got from a Microsoft example on their Coding For Fun website a while back, in your button push put this:

    Code:
            '
            ' The NetScan will perform the pings on separate threads
            '
            Dim ns As NetScan = New NetScan()
    
            '
            ' Event handler for when each ping completes.
            '
            AddHandler ns.PingComplete, AddressOf PingComplete
    
            '
            ' Event handler for when all pings have completed.
            '
            AddHandler ns.NetScanComplete, AddressOf NetScanComplete
    
            '
            ' Disable the "Scan" button while the pings are running, and start the pings.
            '
            scanButton.Enabled = False
            ns.Start(New PingRange(startIP, endIP))
    Where the worker methods are declared as:

    Code:
        Private Sub PingComplete(ByVal s As Object, ByVal ev As NetScanCompletedEventArgs)
            If ev.Reply.Status = IPStatus.Success Then
    
                Dim li As ListViewItem = New ListViewItem(New String() {ev.Reply.Address.ToString(), ev.Reply.RoundtripTime.ToString(CultureInfo.InvariantCulture) + " ms"})
                resultsListView.Items.Add(li)
            End If
        End Sub
    
        Private Sub NetScanComplete(ByVal s As Object, ByVal ev As EventArgs)
            scanButton.Enabled = True
        End Sub
    And then, in another class, have the following:

    Code:
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.Windows.Forms
    Imports System.Net
    Imports System.Net.NetworkInformation
    Imports System.Threading
    
    Public Class NetScan
        Inherits Control
    
        '
        ' Fired when each ping completes
        ' 
        Public Event PingComplete As EventHandler(Of NetScanCompletedEventArgs)
    
        '
        ' Fired when all pings complete
        '
        Public Event NetScanComplete As EventHandler(Of EventArgs)
    
        '
        ' Limits the number of pings happening simultaniously
        '
        Const THREAD_COUNT As Integer = 200
        Private pingBlock As Semaphore = New Semaphore(0, THREAD_COUNT)
    
        ''' <summary>
        ''' Constructor
        ''' </summary>
        Public Sub New()
            '
            ' Needed before Control.Invoke will work.
            '
            Dim i As IntPtr = Me.Handle
    
            '
            ' All items in the semaphore start out locked.  This releases them all.
            '
            pingBlock.Release(THREAD_COUNT)
        End Sub
    
        ''' <summary>
        ''' Starts ping operations on a background thread.
        ''' </summary>
        ''' <param name="pr">Contains the starting and ending IP address for the pings.</param>
        Public Sub Start(ByVal pr As PingRange)
            Dim t As Thread = New Thread(New ParameterizedThreadStart(AddressOf pingWorker_DoWork))
            t.Start(New PingRange(pr.StartRange, pr.EndRange))
    
        End Sub
    
        ''' <summary>
        ''' Loops through the IP address and does the pings.
        ''' </summary>
        ''' <remarks></remarks>
        ''' <param name="o">Start and end IP addresses to ping.</param>
        Private Sub pingWorker_DoWork(ByVal o As Object)
            Dim pingRange As PingRange = CType(o, PingRange)
    
            '
            ' Get the starting and ending address as a byte array to make it easier to
            ' loop through.
            '
            Dim startRange As Byte() = pingRange.StartRange.GetAddressBytes()
            Dim endRange As Byte() = pingRange.EndRange.GetAddressBytes()
    
            '
            ' Each thread that's spawned will be put in this list so that it's easy to
            ' know when they've all completed.
            '
            Dim threads As LinkedList(Of Thread) = New LinkedList(Of Thread)()
    
            '
            ' Loop through each octet in the IP address, and ping on a background thread.
            '
            For o0 As Byte = startRange(0) To endRange(0)
                For o1 As Byte = startRange(1) To endRange(1)
                    For o2 As Byte = startRange(2) To endRange(2)
                        For o3 As Byte = startRange(3) To endRange(3)
    
                            pingBlock.WaitOne()
                            Dim t As Thread = New Thread(New ParameterizedThreadStart(AddressOf DoPing))
                            t.Start(New IPAddress(New Byte() {o0, o1, o2, o3}))
                            threads.AddTail(t)
                        Next o3
                    Next o2
                Next o1
            Next o0
    
            '
            ' Wait until all the pings are done.
            '
            For Each ln As Thread In threads
                ln.Join()
            Next
    
            '
            ' Raise an event saying the pings are done on the main UI thread.
            '
            Try
    
                Me.Invoke(New RaiseNetScanCompleteHandler(AddressOf RaiseNetScanComplete))
    
            Catch ex As InvalidOperationException
    
                ' Can happen if the application is closed while pings are going on in 
                ' the background.  Safe to ignore.
            End Try
        End Sub
    
        Private Delegate Sub RaiseNetScanCompleteHandler()
    
        ''' <summary>
        ''' Fire an event to the client on the same thread that they invoked this  
        ''' object on so that the UI can be safely updated.
        ''' </summary>
        Private Sub RaiseNetScanComplete()
            RaiseEvent NetScanComplete(Me, New EventArgs())
        End Sub
    
        ''' <summary>
        ''' Perform the actual ping, and release the semaphore so that another thread
        ''' can go.
        ''' </summary>
        ''' <param name="o">IP address to ping</param>
        Private Sub DoPing(ByVal o As Object)
            Dim ip As IPAddress = CType(o, IPAddress)
            Dim newPing As Ping = New Ping()
            Dim pr As PingReply = newPing.Send(ip)
            pingBlock.Release()
    
            Try
    
                Me.Invoke(New PingResults(AddressOf Results), New Object() {pr})
    
            Catch ex As InvalidOperationException
    
                ' Can happen if the application is closed while pings are going on in 
                ' the background.  Safe to ignore.
            End Try
        End Sub
    
        Protected Delegate Sub PingResults(ByVal pr As PingReply)
    
        ''' <summary>
        ''' Fire an event when each ping completes so that the client can show
        ''' progress
        ''' </summary>
        ''' <param name="pr">Ping Results</param>
        Sub Results(ByVal pr As PingReply)
    
            Dim e As NetScanCompletedEventArgs = New NetScanCompletedEventArgs()
            e.Reply = pr
            RaiseEvent PingComplete(Me, e)
        End Sub
    End Class
    Also:

    Code:
    Imports System
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.Net.NetworkInformation
    
    Public Class NetScanCompletedEventArgs
        Inherits EventArgs
    
        Private _reply As PingReply
    
        Public Property Reply() As PingReply
            Get
                Return _reply
            End Get
            Set(ByVal value As PingReply)
                _reply = value
            End Set
        End Property
    End Class
    And one more:

    Code:
    Imports System.Collections.Generic
    Imports System.Text
    Imports System.Net
    
    Public Class PingRange
        Private _startRange As IPAddress
        Public Property StartRange() As IPAddress
            Get
                Return _startRange
            End Get
    
            Set(ByVal value As IPAddress)
                _startRange = value
            End Set
        End Property
    
        Private _endRange As IPAddress
        Public Property EndRange() As IPAddress
    
                get
    
                Return _endRange
            End Get
    
            Set(ByVal value As IPAddress)
    
                _endRange = value
            End Set
        End Property
    
        Public Sub New(ByVal startRange As IPAddress, ByVal endRange As IPAddress)
            _startRange = startRange
            _endRange = endRange
        End Sub
    
        Public Sub New(ByVal startRange As Long, ByVal endRange As Long)
            _startRange = New IPAddress(startRange)
            _endRange = New IPAddress(endRange)
        End Sub
    End Class
    I used the above in an application that I created and was able to get near real time representations of the current status of 10 computers which were connected over our business VPN.

    Hope this helps!!

    Gary

  5. #5
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: [2008] Ping multiple IP's

    That NetScan class looks pretty good. The OP can modify it slightly to ping a collection of IP addresses instead of an IP range, since most servers in an intranet environment do not have their IP addesses in sequence.
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  6. #6
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Quote Originally Posted by stanav
    That NetScan class looks pretty good. The OP can modify it slightly to ping a collection of IP addresses instead of an IP range, since most servers in an intranet environment do not have their IP addesses in sequence.
    Hey,

    That is basically exactly what I did to modify it as well. I passed in a collection of IP Addresses and looped through each one and pinged that IP address.

    The example that I took that class from was designed to find all the computers on your network. i.e. you give a subnet and it will go and find all the computers on your network.

    I don't have the code I modified to hand, but from what I remember, it wasn't that difficult.

    Gary

  7. #7
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] Ping multiple IP's

    i missed where it used the mask.

    if my mask is
    255.255.255.252
    and the range is 192.168.1.1 - 192.168.1.254
    it should only ping
    192.168.1.1
    192.168.1.2

    anything above 192.168.1.3 is in a different network
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  8. #8
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    Sorry, the example that I pasted from doesn't use a subnet mask, it simply pings everything between the start and end IP Address. Lets say your IP Address was 192.168.1.12, and you wanted to find every computer on your network and you had a subnet mask of 255.255.225.0, then you would put 192.168.1.0 in the start and 192.168.1.255 in the end. It doesn't take a mask into consideration. I guess it could be modified to take that into consideration, but that is not functionality that I used, or that has been asked for.

    This is the article that the code was taken from:

    http://blogs.msdn.com/coding4fun/arc...31/914076.aspx

    The source code is no longer available for download, but the majority of the code that it contained has been pasted above.

    Gary

  9. #9
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] Ping multiple IP's

    you meant 255.255.255.0 not 255.255.225.0 right?
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  10. #10
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    yip, that is exactly what I meant. My typing has never been great!!!

  11. #11
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] Ping multiple IP's

    IMHO - it is a shame that .Address is an ObsoleteAttribute("This property has been deprecated...


    Code:
            Dim testIP As IPAddress = IPAddress.Parse("192.168.1.1")
            Dim testMask As IPAddress = IPAddress.Parse("255.255.255.255")
            Dim testadd1 As IPAddress = IPAddress.Parse("0.0.0.1")
            testMask.Address = testIP.Address And testMask.Address
            Debug.WriteLine(testMask.ToString)
            testIP.Address = testMask.Address + testadd1.Address
            Debug.WriteLine(testIP.ToString)
    I wrote an address scanner that was pretty short and took care of mask's using the .Address
    Last edited by dbasnett; Oct 16th, 2008 at 04:07 PM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  12. #12
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Just tried the above code, it works, however, .Address is marked as obselete. Is there an alternative way of doing it?

    On that note, in the code that I posted in post #4, there is threads.AddTail(t), this method is no longer supported, use threads.AddLast(t) instead.

    Gary

  13. #13
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] Ping multiple IP's

    Not that I know of.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  14. #14
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    Hi guys,

    Don't know if anyone's still checking this thread...

    I've been writing a remote control app for Cisco phones recently and realised that being able to ping a network to find valid ips in use would be very handy...

    this code looks perfect (if a little over my head)..

    I'm having a little bit of difficulty with a very basic issue...

    at the line:
    ns.Start(New PingRange(startIP, endIP))

    i get the error:
    Conversion from string "10.50.200.0" to type 'Long' is not valid.

    i suspect this is caused by how i've declared my startIP and endIP variables...

    i declared them as string... what should they be?

    if i declare them as anything else i get an error trying to read in the values from the text boxes into the variables...

    Sorry to ask such basic stuff but it would be very very helpful if someone could advise!

    Dan

  15. #15
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    No, they shouldn't be declared as a string, but rather as an IPAddress.

    You would use the following line of code to convert your string to an IPAddress:

    Code:
    Dim startIP As IPAddress = IPAddress.Parse("10.50.200.0")
    Hope that helps!!

    Gary

  16. #16
    Addicted Member
    Join Date
    Oct 2008
    Posts
    202

    Re: [2008] Ping multiple IP's

    Woudlent this be the easiest so he can keep his code:

    Code:
          Private Sub Ping(ByVal ip As String)
                  If My.Settings.server1ip <> String.Empty Then
                      Dim MyPing As New System.Net.NetworkInformation.Ping
                      Dim MyPingResult As System.Net.NetworkInformation.PingReply = MyPing.Send(ip)
                      If MyPingResult.Status = Net.NetworkInformation.IPStatus.Success Then
                          Me.txtServer1Status.ForeColor = Color.Green
                          Me.txtServer1Status.Text = ("Online")
                          Me.txtServer1Reply.Text = (MyPingResult.RoundtripTime.ToString & " ms")
                          If MyPingResult.RoundtripTime.ToString > 200 Then
                              Me.txtServer1Reply.ForeColor = Color.Red
                          Else
                              If MyPingResult.RoundtripTime.ToString > 100 Then
                                  Me.txtServer1Status.ForeColor = Color.Orange
                              End If
                          End If
                      Else
                          Me.txtServer1Status.ForeColor = Color.Red
                          Me.txtServer1Status.Text = ("Failed")
                      End If
                  Else
                      Me.txtServer1Status.Text = ("No IP Entered")
                  End If
              End Sub
    Then you do:

    Code:
    Ping("THEIP")
    Ping("THEOTHERIP")

  17. #17
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    That is a simple solution in the sense that you have to wait for one ping to finish before the next one happens. Given that each ping, by default has a timeout of 4 seconds, the code you have shown could potentially take 8 seconds to complete.

    If you are trying to ping all the IP Addresses on your network one after the other, you can see that this potentially builds up to a long period of time.

    The benefit of the code that I posted is that it starts each ping off in a separate thread, so that each Ping executes at the same time, thus you can do all the pings in the same time as it takes to do one.

    Gary

  18. #18
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    I'm using threading to do multiple pings as i dont want to wait for the previous ones to complete so i'd prefer the first option i think...

    ok so i've changed it to

    vb Code:
    1. Dim StartIP As System.Net.IPAddress = System.Net.IPAddress.Parse(TBSTARTIP.Text)

    which appears to work.. .it seems to be reading the value in the text box into the IP address...

    it then seems to run fine until the part that performs the actual ping...

    vb Code:
    1. ''' <summary>
    2.         ''' Perform the actual ping, and release the semaphore so that another thread
    3.         ''' can go.
    4.         ''' </summary>
    5.         ''' <param name="o">IP address to ping</param>
    6.         Private Sub DoPing(ByVal o As Object)
    7.             Dim ip As IPAddress = CType(o, IPAddress)
    8.             Dim newPing As Ping = New Ping()
    9.             Dim pr As PingReply = newPing.Send(ip)
    10.             pingBlock.Release()
    11.  
    12.             Try
    13.  
    14.                 Me.Invoke(New PingResults(AddressOf Results), New Object() {pr})
    15.  
    16.             Catch ex As InvalidOperationException
    17.  
    18.                 ' Can happen if the application is closed while pings are going on in
    19.                 ' the background.  Safe to ignore.
    20.             End Try
    21.         End Sub

    Or more specifically:

    vb Code:
    1. Me.Invoke(New PingResults(AddressOf Results), New Object() {pr})

    Im getting the error "Object variable or With block variable not set"

    Thanks so much for you help guys!

    Dan

  19. #19
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    So my question would be, have you declared the Results Sub that is used as the delegate method, this should be declared as follows:

    Code:
        ''' <summary>
        ''' Fire an event when each ping completes so that the client can show
        ''' progress
        ''' </summary>
        ''' <param name="pr">Ping Results</param>
        Sub Results(ByVal pr As PingReply)
    
            Dim e As NetScanCompletedEventArgs = New NetScanCompletedEventArgs()
            e.Reply = pr
            RaiseEvent PingComplete(Me, e)
        End Sub
    And have you initialised the pr varaible as such:

    Code:
    Dim pr As PingReply = newPing.Send(ip)
    Gary

  20. #20
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    Hi Gary,

    I have initialised the pr variable within the do ping sub exactly as per your statement:
    vb Code:
    1. Dim pr As PingReply = newPing.Send(ip)

    and just under the doping sub i have this:

    vb Code:
    1. Protected Delegate Sub PingResults(ByVal pr As PingReply)
    2.  
    3.         ''' <summary>
    4.         ''' Fire an event when each ping completes so that the client can show
    5.         ''' progress
    6.         ''' </summary>
    7.         ''' <param name="pr">Ping Results</param>
    8.         Sub Results(ByVal pr As PingReply)
    9.  
    10.             Dim e As NetScanCompletedEventArgs = New NetScanCompletedEventArgs()
    11.             e.Reply = pr
    12.             RaiseEvent PingComplete(Me, e)
    13.         End Sub

    which is ok right?

    thanks!

    Dan

  21. #21
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    Rather than try and fault find what you have, I thought I would be lazy

    Please find attached a complete project which will ping multiple IP addresses on a specified network subnet and display the results.

    This is the original sample code which I downloaded from this site:

    http://blogs.msdn.com/coding4fun/arc...31/914076.aspx

    Hope this helps!!

    Gary
    Attached Files Attached Files

  22. #22
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    OK,

    That's awesome,

    That's working perfectly..

    i just need one more bit of help if you would be so kind...

    i need to send an extra HTTP request to each IP while it pings, i.e. ping, and if the response is successful send an http request

    This is the code i need to add:

    Code:
     objSvrHTTP.open("GET", "http://" + IP + "/DeviceInformation", False)
            objSvrHTTP.send()
            DeviceInformation = objSvrHTTP.responseText
       If InStr(DeviceInformation, "Cisco Communicator ") > 0 Then
                PhoneType = "IP Communicator"
            ElseIf InStr(DeviceInformation, "7970") > 0 Then
                PhoneType = "7970"
            ElseIf InStr(DeviceInformation, "7960") > 0 Then
                PhoneType = "7960"
            End If
    where should i put that in my code? i've also got a slight problem in that i would need to reconvert the ip address to a string so i can send it in the http request right?

  23. #23
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    It really comes down to how you want to do this.

    You could either ping everyone on the subnet, if it works, then record the IpAddress in a list, then start looping through this list using the same technique as above (that is if you want them to execute on separate threads) and perform the HttpRequest.

    If you look at the members of the IpAddress Class:

    http://msdn.microsoft.com/en-us/libr...s_members.aspx

    You can see that you can easily get the IP Address back.

    Gary

  24. #24
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    Hey Gary,

    I've put my code in with the ping requests and stepping through it it seems to be doing the right thing!...

    my only issue now is getting the variable "PhoneType" back to the list box on the form...

    i was originally thinking i needed to pass it from the "DoPing" sub to the "PingResults" sub using the line:
    Code:
    Me.Invoke(New PingResults(AddressOf Results), New Object() {pr,PhoneType})
    then pass it from "PingResults" to "PingComplete" which is a sub on the form using:
    Code:
    RaiseEvent PingComplete(Me, e, PhoneType )
    . but i get an error when i try this.

    Any ideas of how to pass this variable back to the original form? then i think i am done

    sorry, i'm sure this should be very simple, i'm trying my utmost to understand the code you sent and i'm pretty much there but it's just this bit that's baffling me.

    VB Code:
    1. ''' <summary>
    2.     ''' Perform the actual ping, and release the semaphore so that another thread
    3.     ''' can go.
    4.     ''' </summary>
    5.     ''' <param name="o">IP address to ping</param>
    6.     Private Sub DoPing(ByVal o As Object)
    7.         Dim ip As IPAddress = CType(o, IPAddress)
    8.         Dim newPing As Ping = New Ping()
    9.         Dim pr As PingReply = newPing.Send(ip)
    10.         Dim ipstr As String
    11.         ipstr = ip.ToString
    12.         Dim PhoneType As String
    13.         Dim objSvrHTTP As MSXML2.XMLHTTP
    14.         Dim FSO
    15.         Dim DeviceInformation As String
    16.         FSO = CreateObject("Scripting.FileSystemObject")
    17.         Try
    18.  
    19.             objSvrHTTP = CreateObject("Msxml2.XMLHTTP")
    20.             PhoneType = ""
    21.             objSvrHTTP.open("GET", "http://" + ipstr + "/DeviceInformation", False)
    22.             objSvrHTTP.send()
    23.             DeviceInformation = objSvrHTTP.responseText
    24.             If InStr(DeviceInformation, "Cisco Communicator ") > 0 Then
    25.                 PhoneType = "IP Communicator"
    26.             ElseIf InStr(DeviceInformation, "7970") > 0 Then
    27.                 PhoneType = "7970"
    28.             ElseIf InStr(DeviceInformation, "7960") > 0 Then
    29.                 PhoneType = "7960"
    30.             End If
    31.  
    32.         Catch ex As Exception
    33.             PhoneType = "Not a phone!"
    34.         End Try
    35.  
    36.         pingBlock.Release()
    37.  
    38.         Try
    39.  
    40.             Me.Invoke(New PingResults(AddressOf Results), New Object() {pr})
    41.  
    42.         Catch ex As InvalidOperationException
    43.  
    44.             ' Can happen if the application is closed while pings are going on in
    45.             ' the background.  Safe to ignore.
    46.         End Try
    47.     End Sub
    48.  
    49.     Protected Delegate Sub PingResults(ByVal pr As PingReply)
    50.  
    51.     ''' <summary>
    52.     ''' Fire an event when each ping completes so that the client can show
    53.     ''' progress
    54.     ''' </summary>
    55.     ''' <param name="pr">Ping Results</param>
    56.     Sub Results(ByVal pr As PingReply)
    57.  
    58.         Dim e As NetScanCompletedEventArgs = New NetScanCompletedEventArgs()
    59.         e.Reply = pr
    60.         RaiseEvent PingComplete(Me, e, )
    61.     End Sub
    62. End Class

  25. #25
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    That isn't really what I was suggesting...

    DoPing is the worker method for the actual Ping, so while in that method, you don't actually know if the ping was successful, so in my opinion, this would be the wrong place to put it. Rather, you would want to start the HttpWebRequest at the point that you know the Ping has come back successfully, i.e.

    Code:
        Private Sub PingComplete(ByVal s As Object, ByVal ev As NetScanCompletedEventArgs)
            If ev.Reply.Status = IPStatus.Success Then
    
                Dim li As ListViewItem = New ListViewItem(New String() {ev.Reply.Address.ToString(), ev.Reply.RoundtripTime.ToString(CultureInfo.InvariantCulture) + " ms"})
                resultsListView.Items.Add(li)
            End If
        End Sub

    Once you know that the Ping came back, you should then fire off the HttpWebRequest.

    Also, a small point, it looks like you are using some older object types, for which there are newer versions in the framework, i.e. for the FileSystem you might want to look at the System.IO namespace and for the actual Request, look at the HttpWebRequest class.

    Gary

  26. #26
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    ah!

    Ok cool, that's what i tried the first time but i think i put my code outside of the if successful bit so it didnt work.

    D'OH!

    ok, that works now.

    Will that still be working on the threads created earlier as presumably each thread response is passed to this sub?

  27. #27
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    I would have to see the code that you have implemented in order to answer that fully.

    Basically, it depends on what exactly you have done. The code that I have given you will fire off each ping on a separate thread. Assuming you are doing some additional logic if a ping comes back successfully then you will need to handle the creation of new threads at that point.

    Gary

  28. #28
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    sorry, answered my own question..

    it seems to follow the threading...

    but! my thread count is set to 200.. it appears to crash if i examine a full class C subnet - i.e. more than 200 devices.

    i'm guessing the threads arent being released properly?

  29. #29
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    At the minute, the number of threads that can happen simultaneously is limited to 200, based on this line of code:

    Code:
    Const THREAD_COUNT As Integer = 200
    Don't think you would want to go much higher than that. i.e. limit the searches to only a limited number of IP addresses.

    But yes, you should make sure to release semaphore so that other threads can start, you can see that in action here:

    Code:
    pingBlock.Release()
    In the DoPing method.

    Gary

  30. #30
    Member
    Join Date
    Mar 2009
    Posts
    40

    Re: [2008] Ping multiple IP's

    Thanks for all your help Gary,

    Everything is working nicely. just got to tidy it up a bit!

    I'm going to look at that webrequest method now

    Dan

  31. #31
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Good stuff, glad to hear it!!!

  32. #32
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: [2008] Ping multiple IP's

    Ping a range of IP's
    Code:
    Imports System.Net.NetworkInformation
    Public Class Form1
        Dim listIP As List(Of String)
        Dim status As List(Of String)
        Dim count As Integer
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim anIP As String = "192.168.1.0"
            Dim aMask As String = "255.255.255.0"
            Dim aPing As Ping
            'ipRange can be found here:
            'http://www.vbforums.com/showpost.php?p=3377404&postcount=5
            listIP = ipRange(anIP, aMask)
            status = New List(Of String)
            status.AddRange(listIP.ToArray)
            For x As Integer = 1 To listIP.Count - 1
                aPing = New Ping
                AddHandler aPing.PingCompleted, AddressOf pchdlr
                status(x) = ""
                System.Threading.Interlocked.Increment(count)
                aPing.SendAsync(listIP(x), 100, x)
            Next
        End Sub
        Private Sub pchdlr(ByVal sender As Object, ByVal args As PingCompletedEventArgs)
            status(CInt(args.UserState)) = args.Reply.Status.ToString
            System.Threading.Interlocked.Decrement(count)
        End Sub
    End Class
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  33. #33
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Re: [2008] Ping multiple IP's

    Hey, I don't know if anyone's checking this thread, but I have a small question:

    I have an app that retrieves the names of the PCs on a local network, what I would like to do is ping each one... This is the code I'm using:

    vb.net Code:
    1. Private Sub tryPing()
    2.         Dim aPing As Ping = New Ping
    3.         Dim timeout As Integer = 4000
    4.         Dim buffer As Byte() = {"0", "10", "20", "30", "40", "50", _
    5.                                 "60", "70", "80", "90", "100", _
    6.                                  "110", "120", "130", "140", "150", _
    7.                                   "160", "170", "180", "190", "200"}
    8.         Dim userToken As Object = New Object
    9.         For i As Integer = 0 To pclist.Length - 1
    10.             Try
    11.                 aPing.SendAsync("\\" & pclist(i), timeout, buffer, userToken)
    12.                 lbAPIComputers.Items.Add(pclist(i))
    13.             Catch
    14.                 lbNonAcsPC.Items.Add(pclist(i))
    15.             End Try
    16.         Next
    17.     End Sub

    pcList is an array with the name of all the pcs on the network.
    lbAPIComputers is a ListBox with the names of the pc's the i've pinged and the result is a succes and the lbNonAcsPC is another ListBox with the names of the pc's i've pinged but the result isn't success...

    The problem is that after it pings the first PC it stops (?) and automatically adds the other names to lbNonAcsPC (without even pinging them, I asume).

    I've read the post #32, but I don't quite get it. Is it pinging on a different thread? How can I modify it to fit my purposes?

    Thanks in advance!!
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  34. #34
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hey,

    Have you had a look at the sample that I posted in post #21. This will do exactly what you want. It may take some "tinkering" to get it to work with the array that you are using, but it will definitely do it.

    In that sample, each ping is executed on a separate thread.

    Gary

  35. #35
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Re: [2008] Ping multiple IP's

    Hey Gary, I did try it out and also took a look at kleinma's explanation about it in the Code Bank. I got it working, thanks..!
    Last edited by tassa; Jun 23rd, 2009 at 09:44 AM.
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  36. #36
    Fanatic Member
    Join Date
    Oct 2008
    Location
    Dominican Republic
    Posts
    733

    Re: [2008] Ping multiple IP's

    Oops, sorry, double post.
    "In our profession, precision and perfection are not a dispensable luxury, but a simple necessity."
    Niklaus E. Wirth


    Rate any post that helped you, it's a good way of saying thanks
    Please specify your Visual Studio Version!

    Why rating is useful

    My Code Bank Submissions: How to determine Windows Version| Working With Mouse Events | Blocking Input Using API | Get host's IP | Minimize to system tray "animated" | Colored ListBox (custom fonts, colors, highlight) Updated -New Class! | [VS 2008] Strong encryption and hashing class - Updated! 31/August/2009 | Create a shortcut using IWshRuntimeLibrary

  37. #37
    New Member
    Join Date
    Aug 2009
    Posts
    4

    Re: [2008] Ping multiple IP's

    Thanks Gary for the posts,

    I am building a similar application, but am not pinging ranges of ip addresses, but five different ip addresses. how do i go about editing it the code.

  38. #38
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: [2008] Ping multiple IP's

    Hello,

    Welcome to the forums!!

    One way of doing this would be to modify the Start method of the NetScan class to accept a List of IPAddress, rather than an IPRange. Construct the List, and add the IP Addresses that you want into it, then in the pingWorker_DoWork method you can loop through the List and ping all the ones that you want.

    Hope that helps!!

    Gary

  39. #39
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: [2008] Ping multiple IP's

    Quote Originally Posted by obicauka View Post
    Thanks Gary for the posts,

    I am building a similar application, but am not pinging ranges of ip addresses, but five different ip addresses. how do i go about editing it the code.
    I have a codebank example on doing async ping requests to multiple IPs and listening for the results. You can find that here.

    http://www.vbforums.com/showthread.php?t=573829

  40. #40
    Frenzied Member stateofidleness's Avatar
    Join Date
    Jan 2009
    Posts
    1,780

    Re: [2008] Ping multiple IP's

    wanted to spam my project as well

    dubbed IRIS, it allows you to import ip addresses from a spreadsheet and ping them. source will be available soon!!!

    see sig!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width