Results 1 to 18 of 18

Thread: How to ping a machine in VB .net

  1. #1

    Thread Starter
    Addicted Member Porsche944's Avatar
    Join Date
    Apr 2005
    Location
    Ann Arbor
    Posts
    182

    Question How to ping a machine in VB .net

    I have a module that will ping a machine given a hostname or an ip address. Is there an eaiser way to ping a machine using vb .net? I know you can use wsh to open a shell and execute the ping command from a command prompt window then use the ReadAll to get the information ping sends back and from there you can determine if the ping was sucessful or not.

    How would I do this in VB .Net or is there a better way to ping machines in .net?

  2. #2
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: How to ping a machine in VB .net

    This might be a good starting point... (from MSDN)

    VB Code:
    1. Try
    2.     Dim siteUri As New System.Uri("http://www.google.com")
    3.     Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(siteUri)
    4.     webRequest.Proxy = New System.Net.WebProxy("YourProxySetting")
    5.     Dim webResponse As System.Net.WebResponse = webRequest.GetResponse()
    6. Catch ex As Exception
    7.     ' The Web request failed.
    8. End Try
    I don't live here any more.

  3. #3

    Thread Starter
    Addicted Member Porsche944's Avatar
    Join Date
    Apr 2005
    Location
    Ann Arbor
    Posts
    182

    Re: How to ping a machine in VB .net

    that code would probably not work on pining a local machine on our lan here using a host name however.


    Correct?

  4. #4
    pathfinder NotLKH's Avatar
    Join Date
    Apr 2001
    Posts
    2,397

    Re: How to ping a machine in VB .net

    Found some semiFunctional Code @ http://www.developerfusion.com/show/2857/


    The Gent failed to include a structure.
    So I tweaked it.

    Make a new class, and insert this code:
    {edited to remove some comments. TOO BIG!}
    VB Code:
    1. Option Explicit On
    2.  
    3. Imports System
    4. Imports System.Net
    5. Imports System.Net.Sockets
    6.  
    7.  
    8. Public Class clsPing
    9.  
    10.     Public Structure stcError
    11.         Dim Number As Integer
    12.         Dim Description As String
    13.     End Structure
    14.     'suggested by sholliday, here: [url]http://www.developerfusion.com/forums/topic.aspx?id=21482[/url]
    15.     'Although, This WAS hidden in the code:
    16.     '*
    17.     '* --- ICMP Echo Header Format ---
    18.     '* (first 8 bytes of the data buffer)
    19.     '*
    20.     '* Buffer (0) ICMP Type Field
    21.     '* Buffer (1) ICMP Code Field
    22.     '*     (must be 0 for Echo and Echo Reply)
    23.     '* Buffer (2) checksum hi
    24.     '*     (must be 0 before checksum calc)
    25.     '* Buffer (3) checksum lo
    26.     '*     (must be 0 before checksum calc)
    27.     '* Buffer (4) ID hi
    28.     '* Buffer (5) ID lo
    29.     '* Buffer (6) sequence hi
    30.     '* Buffer (7) sequence lo
    31.     '* Buffer (8)..(n)  Ping Data
    32.     '*
    33.     Public Enum ICMPType
    34.         ICMP_ECHO_REPLY = 0
    35.         ICMP_DESTINATION_UNREACHABLE = 3
    36.         ICMP_REDIRECT = 5
    37.         'ICMP_ECHO_REQUEST = 8
    38.         ICMP_TIME_EXCEEDED = 11
    39.         ICMP_PARAMETER_PROBLEM = 12
    40.         ICMP_TIMESTAMP_REQUEST = 13
    41.         ICMP_TIMESTAMP_REPLY = 14
    42.         'EchoReply = 0
    43.         'Unreachable = 3
    44.         Echo = 8
    45.     End Enum
    46.     Public Const PING_SUCCESS As Long = 0
    47.     Public Const PING_ERROR As Long = (-1)
    48.     Public Const PING_ERROR_BASE As Long = &H8000
    49.     Public Const PING_ERROR_HOST_NOT_FOUND As Long = PING_ERROR_BASE + 1
    50.     Public Const PING_ERROR_SOCKET_DIDNT_SEND As Long = PING_ERROR_BASE + 2
    51.     Public Const PING_ERROR_HOST_NOT_RESPONDING As Long = PING_ERROR_BASE + 3
    52.     Public Const PING_ERROR_TIME_OUT As Long = PING_ERROR_BASE + 4
    53.  
    54.     Private Const ICMP_ECHO As Integer = 8
    55.     Private Const SOCKET_ERROR As Integer = -1
    56.  
    57.     Private udtError As stcError
    58.  
    59.     Private Const intPortICMP As Integer = 7
    60.     Private Const intBufferHeaderSize As Integer = 8
    61.     Private Const intPackageHeaderSize As Integer = 28
    62.  
    63.     Private intDataSize As Byte
    64.     Private ipheLocalHost As System.Net.IPHostEntry
    65.     Private ipheHost As System.Net.IPHostEntry
    66.  
    67.     Public Property DataSize() As Byte
    68.         Get
    69.             Return intDataSize
    70.         End Get
    71.         Set(ByVal Value As Byte)
    72.             intDataSize = Value
    73.         End Set
    74.     End Property
    75.  
    76.     Public ReadOnly Property Identifier() As Byte
    77.         Get
    78.             Return 0
    79.         End Get
    80.     End Property
    81.  
    82.     Public ReadOnly Property Sequence() As Byte
    83.         Get
    84.             Return 0
    85.         End Get
    86.     End Property
    87.  
    88.     Public ReadOnly Property LocalHost() As System.Net.IPHostEntry
    89.         Get
    90.             Return ipheLocalHost
    91.         End Get
    92.     End Property
    93.  
    94.     Public Property Host() As Object
    95.         Get
    96.             Return ipheHost
    97.         End Get
    98.         Set(ByVal Value As Object)
    99.             If (Value.GetType.ToString.ToLower = "system.string") Then
    100.                 Try
    101.                     ipheHost = System.Net.Dns.GetHostByName(Value)
    102.                 Catch
    103.                     udtError.Number = PING_ERROR_HOST_NOT_FOUND
    104.                     udtError.Description = "Host " & ipheHost.HostName & " not found."
    105.                     ipheHost = Nothing
    106.                 End Try
    107.             ElseIf (Value.GetType.ToString.ToLower = "system.net.iphostentry") Then
    108.                 ipheHost = (Value)
    109.             Else
    110.                 ipheHost = Nothing
    111.             End If
    112.         End Set
    113.     End Property
    114.  
    115.     Public Sub New()
    116.         intDataSize = 32
    117.         udtError = New stcError()
    118.         ipheLocalHost = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
    119.         ipheHost = Nothing
    120.     End Sub
    121.  
    122.     Public Function Ping() As Long
    123.  
    124.         Dim intCount As Integer
    125.         Dim aReplyBuffer(255) As Byte
    126.  
    127.         Dim intNBytes As Integer = 0
    128.  
    129.         Dim intEnd As Integer
    130.         Dim intStart As Integer
    131.  
    132.         Dim epFrom As System.Net.EndPoint
    133.         Dim epServer As System.Net.EndPoint
    134.         Dim ipepServer As System.Net.IPEndPoint
    135.  
    136.         ipepServer = New System.Net.IPEndPoint(ipheHost.AddressList(0), 0)
    137.         epServer = CType(ipepServer, System.Net.EndPoint)
    138.  
    139.         epFrom = New System.Net.IPEndPoint(ipheLocalHost.AddressList(0), 0)
    140.  
    141.  
    142.         DataSize = Convert.ToByte(DataSize + intBufferHeaderSize)
    143.  
    144.         If (DataSize Mod 2 = 1) Then
    145.             DataSize += Convert.ToByte(1)
    146.         End If
    147.         Dim aRequestBuffer(DataSize - 1) As Byte
    148.  
    149.         aRequestBuffer(0) = Convert.ToByte(ICMPType.Echo)
    150.  
    151.  
    152.         BitConverter.GetBytes(Identifier).CopyTo(aRequestBuffer, 4)
    153.  
    154.         BitConverter.GetBytes(Sequence).CopyTo(aRequestBuffer, 6)
    155.  
    156.         Dim i As Integer
    157.         For i = 8 To DataSize - 1
    158.             aRequestBuffer(i) = Convert.ToByte(i Mod 8)
    159.         Next i
    160.  
    161.         Call CreateChecksum(aRequestBuffer, DataSize, aRequestBuffer(2), aRequestBuffer(3))
    162.  
    163.         Try
    164.  
    165.             Dim sckSocket As New System.Net.Sockets.Socket( _
    166.                                             Net.Sockets.AddressFamily.InterNetwork, _
    167.                                             Net.Sockets.SocketType.Raw, _
    168.                                             Net.Sockets.ProtocolType.Icmp)
    169.             sckSocket.Blocking = False
    170.  
    171.  
    172.             intStart = System.Environment.TickCount
    173.             sckSocket.SendTo(aRequestBuffer, 0, DataSize, SocketFlags.None, ipepServer)
    174.             intNBytes = sckSocket.ReceiveFrom(aReplyBuffer, SocketFlags.None, epServer)
    175.             intEnd = System.Environment.TickCount
    176.  
    177.             If (intNBytes > 0) Then
    178.                 udtError.Number = (aReplyBuffer(19) * &H100) + aReplyBuffer(20)
    179.                 Select Case aReplyBuffer(20)
    180.                     Case 0 : udtError.Description = "Success"
    181.                     Case 1 : udtError.Description = "Buffer too Small"
    182.                     Case 2 : udtError.Description = "Destination Unreahable"
    183.                     Case 3 : udtError.Description = "Dest Host Not Reachable"
    184.                     Case 4 : udtError.Description = "Dest Protocol Not Reachable"
    185.                     Case 5 : udtError.Description = "Dest Port Not Reachable"
    186.                     Case 6 : udtError.Description = "No Resources Available"
    187.                     Case 7 : udtError.Description = "Bad Option"
    188.                     Case 8 : udtError.Description = "Hardware Error"
    189.                     Case 9 : udtError.Description = "Packet too Big"
    190.                     Case 10 : udtError.Description = "Reqested Timed Out"
    191.                     Case 11 : udtError.Description = "Bad Request"
    192.                     Case 12 : udtError.Description = "Bad Route"
    193.                     Case 13 : udtError.Description = "TTL Exprd In Transit"
    194.                     Case 14 : udtError.Description = "TTL Exprd Reassemb"
    195.                     Case 15 : udtError.Description = "Parameter Problem"
    196.                     Case 16 : udtError.Description = "Source Quench"
    197.                     Case 17 : udtError.Description = "Option too Big"
    198.                     Case 18 : udtError.Description = "Bad Destination"
    199.                     Case 19 : udtError.Description = "Address Deleted"
    200.                     Case 20 : udtError.Description = "Spec MTU Change"
    201.                     Case 21 : udtError.Description = "MTU Change"
    202.                     Case 22 : udtError.Description = "Unload"
    203.                     Case Else : udtError.Description = "General Failure"
    204.  
    205.                 End Select
    206.             Else
    207.                 'NotLKH added this:
    208.                 udtError.Number = -2
    209.                 udtError.Description = "NoReturnedData"
    210.             End If
    211.             sckSocket.Close()
    212.             sckSocket = Nothing
    213.  
    214.             Return (intEnd - intStart)
    215.         Catch oExcept As Exception
    216.  
    217.         End Try
    218.  
    219.     End Function
    220.  
    221.     Public Function GetLastError() As stcError
    222.         Return udtError
    223.     End Function
    224.  
    225.     Private Sub CreateChecksum(ByRef data() As Byte, ByVal Size As Integer, ByRef HiByte As Byte, ByRef LoByte As Byte)
    226.         Dim i As Integer
    227.         Dim chk As Integer = 0
    228.  
    229.         For i = 0 To Size - 1 Step 2
    230.             chk += Convert.ToInt32(data(i) * &H100 + data(i + 1))
    231.         Next
    232.  
    233.         chk = Convert.ToInt32((chk And &HFFFF&) + Fix(chk / &H10000&))
    234.         chk += Convert.ToInt32(Fix(chk / &H10000&))
    235.         chk = Not (chk)
    236.  
    237.         HiByte = Convert.ToByte((chk And &HFF00) / &H100)
    238.         LoByte = Convert.ToByte(chk And &HFF)
    239.     End Sub
    240.  
    241. End Class

    And the following shows how to use it.

    VB Code:
    1. Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    2.         MsgBox(PING_OR_DIE("igen1"))             'returns true
    3.         MsgBox(PING_OR_DIE("192.167.33.93"))        'returns false
    4.         MsgBox(PING_OR_DIE("igen3"))                     'returns false
    5.     End Sub
    6.     Public Function PING_OR_DIE(ByRef mIP As String) As Boolean
    7.  
    8.         Try
    9.             Dim MyPing As clsPing
    10.             MyPing = New clsPing()
    11.             MyPing.Host = mIP
    12.             Dim a As Long = MyPing.Ping()
    13.             If MyPing.GetLastError.Number = 29184 Then
    14.                 MyPing = Nothing
    15.                 Return True
    16.             Else
    17.                 MyPing = Nothing
    18.                 Return False
    19.             End If
    20.         Catch ex As Exception
    21.         End Try
    22.     End Function
    BTW, If the returned Value is Not 29184, then it didn't connect.
    29184 = Success!


    -Lou

  5. #5
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: How to ping a machine in VB .net


  6. #6
    pathfinder NotLKH's Avatar
    Join Date
    Apr 2001
    Posts
    2,397

    Re: How to ping a machine in VB .net

    Mendhak,
    Is something wrong with the above code?
    As far as I know, it works.

    the thread you point to ends with:
    Quote Originally Posted by jsun9
    The code works identically to the other code on this forum?*** You can ping once, you get some erroneous number then you can't ping after that.
    ***referring to the code posted right at the beginning of that thread
    Hmmm, the class you posted is the same, {ICMP is a different tweak, but near'nuff}

    Yours works, doesn't it?

  7. #7
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: How to ping a machine in VB .net

    Yes, it works, but I've had some problems with it too. I think I had modified it to return a -1 if there was a request timed out. Did you try it?

  8. #8
    pathfinder NotLKH's Avatar
    Join Date
    Apr 2001
    Posts
    2,397

    Re: How to ping a machine in VB .net

    Yours is more direct, being the first lines of code in the Ping() routine:
    VB Code:
    1. Public Function Ping() As Long
    2.  
    3.  
    4.  
    5.         If ipheHost Is Nothing Then
    6.             Return -1
    7.             Exit Function
    8.  
    9.         End If


    I think Mine works similarly, as an else in the following:

    VB Code:
    1. If (intNBytes > 0) Then
    2.                 udtError.Number = (aReplyBuffer(19) * &H100) + aReplyBuffer(20)
    3.                 Select Case aReplyBuffer(20)
    4.                     Case 0 : udtError.Description = "Success"
    5.                     Case 1 : udtError.Description = "Buffer too Small"
    6.                     Case 2 : udtError.Description = "Destination Unreahable"
    7.                     [size=1][i]yada yada yada[/i][/size]
    8.             Else
    9.                 'NotLKH added this:
    10.                 udtError.Number = -2
    11.                 udtError.Description = "NoReturnedData"
    12.             End If

    You might want to put the error value -1 into the udtError.Number before you return, along with a comment into the udtError.Description.

    Your snippet though is good. I think I'll throw a slightly modified version of it into mine.

    -Lou

  9. #9
    pathfinder NotLKH's Avatar
    Join Date
    Apr 2001
    Posts
    2,397

    Re: How to ping a machine in VB .net

    Quote Originally Posted by mendhak
    Yes, it works, but I've had some problems with it too.
    I am not an expert in Net, but I noticed the following:


    VB Code:
    1. End If
    2.            sckSocket.Close
    3.  
    4.            Return (intEnd - intStart)
    5.        Catch oExcept As Exception
    6.            '
    7.        End Try
    8.  
    9.    End Function

    At the end of the ping routine at the website I found the above code at.

    the class you posted had this at the end of the Ping routine:

    VB Code:
    1. End If
    2.             Return (intEnd - intStart)
    3.         Catch oExcept As Exception
    4.             '
    5.         End Try
    6.     End Function


    I don't know how important it is, but would the absence of the sckSocket.Close directive leave the socket open, thus potentially causeing problems later on?


    BTW, I tweaked that area to the following:

    VB Code:
    1. End If
    2.             sckSocket.Close()
    3.             sckSocket = Nothing
    4.  
    5.             Return (intEnd - intStart)
    6.         Catch oExcept As Exception
    7.  
    8.         End Try
    9.  
    10.     End Function

    Just an automatic reaction when I saw the .Close().
    Think setting the sckSocket to nothing is benificial in any way?


  10. #10
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: How to ping a machine in VB .net

    It's just some modified code, so I wasn't thorough with it

    But the answer to your question depends upon the socket class being used, if the GC comes along, ideally, it shouldn't pose much of a problem. However, what you did is good. Safe. Yes, we likes safe....

  11. #11
    pathfinder NotLKH's Avatar
    Join Date
    Apr 2001
    Posts
    2,397

    Re: How to ping a machine in VB .net

    Darn!
    Its buggy, alright.

    If it can't ping something once, it seems determined to be unable to ping just about anything after that.

    Unless you shut it down and restart it.

    SOMETHING just isn't being completely disposed of!

  12. #12
    New Member
    Join Date
    Sep 2008
    Posts
    1

    Re: How to ping a machine in VB .net

    Hi all,

    Nub here but,

    I visited this webby http://www.developerfusion.co.uk/show/2857/2/ and found that it ping class is working.

    not sure isit the sckSocket.close or sckSocket = nothing that is causing some of the bugs of unable to ping after the 1st ping.

  13. #13
    New Member
    Join Date
    Jan 2010
    Posts
    2

    Re: How to ping a machine in VB .net

    I realize this is an old post but I'm using the OPs ping class and it works fine except when run against the local machine.

    I have an app I've developed that will run Radia commands as per selected option and run those commands against either a single machine or a list loaded from a text file. Either case, it errors on and tosses the debug to this line:
    Code:
                ' Send the packet.
                If (SOCKET_ERROR = _socket.SendTo(_packet.Serialize(), _packet.Size(), 0, _server)) Then
                    Return PING_ERROR
                End If
    Anyone able to help me over this one item? I'm not well enough versed in the ICMP or TCP methods and parameters so any insights would be great.

  14. #14
    Pro Grammar chris128's Avatar
    Join Date
    Jun 2007
    Location
    England
    Posts
    7,604

    Re: How to ping a machine in VB .net

    Is there any reason why you cant just use the Ping command that is part of the .NET framework? Its easier to use, requires about 200 less lines of code, and more reliable..

    vb Code:
    1. Dim pingsender As New Net.NetworkInformation.Ping
    2. If pingsender.Send("HostnameHere").Status = Net.NetworkInformation.IPStatus.Success Then
    3.      MessageBox.Show("Ping reply received")
    4. End If
    My free .NET Windows API library (Version 2.2 Released 12/06/2011)

    Blog: cjwdev.wordpress.com
    Web: www.cjwdev.co.uk


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

    Re: How to ping a machine in VB .net

    Here is what I use in my program:

    vb Code:
    1. Private Function IsDestinationReachable(ByVal hostnameOrAddress As String) As Boolean
    2.         Dim reachable As Boolean = False
    3.         Try
    4.             reachable = My.Computer.Network.IsAvailable AndAlso _
    5.                         My.Computer.Network.Ping(hostnameOrAddress, 10000)
    6.         Catch pingException As System.Net.NetworkInformation.PingException
    7.         Catch genericNetworkException As System.Net.NetworkInformation.NetworkInformationException
    8.             ' Fail silently and return false
    9.         End Try
    10.         Return reachable
    11.     End Function

    http://stateofidleness.com/?p=89

  16. #16
    New Member
    Join Date
    Jun 2009
    Posts
    9

    Re: How to ping a machine in VB .net

    Quote Originally Posted by chris128 View Post
    vb Code:
    1. Dim pingsender As New Net.NetworkInformation.Ping
    2. If pingsender.Send("HostnameHere").Status = Net.NetworkInformation.IPStatus.Success Then
    3.      MessageBox.Show("Ping reply received")
    4. End If
    I was searching for a very simple way to check my network availability when I stumbled upon this thread. This code snippet accomplished what I was trying to achieve perfectly. Thanks for posting this!

  17. #17

  18. #18
    Junior Member richy12312's Avatar
    Join Date
    Oct 2009
    Location
    UK
    Posts
    31

    Re: How to ping a machine in VB .net

    this is what i used
    vb Code:
    1. If My.Computer.Network.Ping(TextBox3.Text) Then
    2.             Label5.Text = ("Ping was successful")
    3.             Exit Sub
    4.         Else
    5.             Label5.Text = ("Ping failed")
    6.             Exit Sub
    7.         End If

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