Solved

Pinging a machine Name with VB.net

Posted on 2004-08-17
7
350 Views
Last Modified: 2012-05-05
I need to ping a machine name to see if available with .net.  Is there an easy way to do this with .net?   Should I use the old API call from VB 6.0 or shell it out?  ... Or there a .net way to do this?
0
Comment
Question by:courchjo
7 Comments
 
LVL 18

Assisted Solution

by:DotNetLover_Baan
DotNetLover_Baan earned 150 total points
ID: 11823476
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 350 total points
ID: 11823560
0
 

Author Comment

by:courchjo
ID: 11825537
I am using the Ping functionality from fawcette because of problem with using machine name with Baan's example, but i'm getting the error message "a non-blocking socket operation could not be completed immediately" on the second and subsequent tries.  I've tried setting the ICMPSocket = nothing and setting blocking to false and still receiveing the message.

Thanks,

Joe
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:courchjo
ID: 11825842
Oh i set ICMPSocket.Blocking = False to True and it now works.

Thanks,

Joe
0
 

Author Comment

by:courchjo
ID: 11830347
When I set ICMPSocket.Blocking = False to True It wasn't really working.  When an IPAddress is unreachable the program hangs.  
0
 
LVL 1

Expert Comment

by:lingaraj1976
ID: 14607355
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21073597.html

The above link example doesn't work.. Even though the machine is down and it says true.. I am  not understanding why this code is behaving like this..

Same code ..

Imports System.Net.Sockets
Imports System.Net
Imports System
Imports System.Runtime.InteropServices



    ' Define the structure of an ICMP packet.
    ' This structure contains packet information.
    Structure IcmpPacket

        Dim type_message As Byte                ' type of message
        Dim subCode_type As Byte                ' type of sub-code
        Dim complement_checkSum As UInt16       ' one's complement checksum for the structure
        Dim identifier As UInt16                ' identifier
        Dim sequenceNumber As UInt16            ' sequence number  
        Dim data() As Byte                      ' data


        Public Sub Initialize(ByVal type As Byte, ByVal subCode As Byte, ByVal payload() As Byte)
            Dim index As Integer
            Dim buffer_icmpPacket() As Byte
            Dim cksumBuffer() As UInt16
            Dim icmpHeaderBufferIndex As Int32 = 0
            Me.type_message = type
            Me.subCode_type = subCode
            complement_checkSum = UInt16.Parse("0")
            identifier = UInt16.Parse("45")
            sequenceNumber = UInt16.Parse("0")
            data = payload

            ' Declare a variable to store the total packet size.
            ' Call the Serialize method to count the total number of bytes in the packet.
            buffer_icmpPacket = Serialize()

            ' Resize a UInt16 array to half the size of the packet.
            ReDim cksumBuffer((buffer_icmpPacket.Length() \ 2) - 1)

            ' Initialize the UInt16 array.
            For index = 0 To (cksumBuffer.Length() - 1)
                cksumBuffer(index) = BitConverter.ToUInt16(buffer_icmpPacket, icmpHeaderBufferIndex)
                icmpHeaderBufferIndex += 2
            Next index

            'Call a method that returns a checksum.
            complement_checkSum = MCheckSum.Calculate(cksumBuffer, cksumBuffer.Length())
        End Sub

        Public Function Size() As Integer
            Return (8 + data.Length())
        End Function

        ' The Serialize method converts the packet to a byte array to calculate the total size.
        Public Function Serialize() As Byte()
            Dim b_seq() As Byte = BitConverter.GetBytes(sequenceNumber)
            Dim b_cksum() As Byte = BitConverter.GetBytes(complement_checkSum)
            Dim b_id() As Byte = BitConverter.GetBytes(identifier)
            Dim index As Int32 = 0
            Dim buffer() As Byte
            ReDim buffer(Size() - 1)

            ' Serialize the structure into the array.
            buffer(0) = type_message
            buffer(1) = subCode_type
            index += 2
            Array.Copy(b_cksum, 0, buffer, index, 2)
            index += 2
            Array.Copy(b_id, 0, buffer, index, 2)
            index += 2
            Array.Copy(b_seq, 0, buffer, index, 2)
            index += 2

            ' Copy the data.
            If (data.Length() > 0) Then
                Array.Copy(data, 0, buffer, index, data.Length())
            End If
            Return buffer
        End Function
    End Structure

    ' The CPing class.
    Public Class CPing

        Private Const DEFAULT_TIMEOUT As Integer = 1000
        Private Const SOCKET_ERROR As Integer = -1
        Private Const PING_ERROR As Integer = -1
        Private Const ICMP_ECHO As Integer = 8
        Private Const DATA_SIZE As Integer = 32
        Private Const RECV_SIZE As Integer = 128

        Private _open As Boolean = False
        Private _initialized As Boolean
        Private _recvBuffer() As Byte
        Private _packet As IcmpPacket
        Private _hostName As String
        Private _server As EndPoint
        Private _local As EndPoint
        Private _socket As Socket

        Public Sub New(ByVal hostName As String)
            Me.HostName() = hostName
            ReDim _recvBuffer(RECV_SIZE - 1)
        End Sub

        Public Sub New()
            ' Set the default host name to the local host.
            Me.HostName() = Dns.GetHostName()
            ReDim _recvBuffer(RECV_SIZE - 1)
        End Sub

        Private Overloads Sub finalize()
            ' Ensure that you close the socket.
            Me.Close()
            Erase _recvBuffer
        End Sub

        ' Get and set the current host name.
        Public Property HostName() As String
            Get
                Return _hostName
            End Get
            Set(ByVal Value As String)
                _hostName = Value
                ' If the CPing object is already open, close it and then reopen it by using a new host name.
                If (_open) Then
                    Me.Close()
                    Me.Open()
                End If
            End Set
        End Property

        ' Get the state (open or closed).
        Public ReadOnly Property IsOpen() As Boolean
            Get
                Return _open
            End Get
        End Property

        ' Create a socket to host remote end points and local end points.
        Public Function Open() As Boolean
            Dim payload() As Byte

            If (Not _open) Then
                Try
                    ' Initialize the packet.
                    ReDim payload(DATA_SIZE)
                    _packet.Initialize(ICMP_ECHO, 0, payload)

                    ' Initialize an ICMP socket.
                    _socket = New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)

                    ' Set the server end point.
                    If _hostName.ToLower.IndexOfAny("abcdefghijklmnopqrstuvwxyz-") >= 0 Then
                        _server = New IPEndPoint(Dns.GetHostByName(_hostName).AddressList(0), 0)
                    Else
                        _server = New IPEndPoint(IPAddress.Parse(_hostName), 0)
                    End If

                    ' Set the receiving end point as your client computer.
                    _local = New IPEndPoint(Dns.GetHostByName(Dns.GetHostName()).AddressList(0), 0)
                    _open = True
                Catch
                    Return False
                End Try
            End If
            Return True
        End Function

        ' Destroy the socket and end points (if necessary).
        Public Function Close() As Boolean
            If (_open) Then
                _socket.Close()
                _socket = Nothing
                _server = Nothing
                _local = Nothing
                _open = False
            End If
            Return True
        End Function

        ' Perform a PING operation.
        Public Overloads Function Ping() As Integer
            Return Ping(DEFAULT_TIMEOUT)
        End Function

        ' The Ping method performs a PING operation.
    Public Overloads Function Ping(ByVal CheckTime As Integer) As Integer

        Dim ts As TimeSpan
        Dim targetTime As DateTime = DateTime.Now.AddMinutes(CheckTime)

        ' Send the packet.
        Try
            If (SOCKET_ERROR = _socket.SendTo(_packet.Serialize(), _packet.Size(), 0, _server)) Then
                Return PING_ERROR
            End If
        Catch
            Return PING_ERROR
        End Try

        ' Poll the read buffer every millisecond.
        Do
            ts = targetTime.Subtract(DateTime.Now)

            If (_socket.Poll(1000, SelectMode.SelectRead)) Then
                _socket.ReceiveFrom(_recvBuffer, RECV_SIZE, 0, _local)
                Return True
            End If
            System.Threading.Thread.Sleep(30000)
        Loop While ts.TotalSeconds > 0
        Return False
    End Function
End Class

    ' The MCheckSum module contains the static Calculate method.
    Module MCheckSum
        <StructLayout(LayoutKind.Explicit)> _
                   Structure UNION_INT16
            <FieldOffset(0)> Dim lsb As Byte      ' Least significant byte
            <FieldOffset(1)> Dim msb As Byte      ' Most significant byte
            <FieldOffset(0)> Dim w16 As Short
        End Structure

        <StructLayout(LayoutKind.Explicit)> _
        Structure UNION_INT32
            <FieldOffset(0)> Dim lsw As UNION_INT16     ' Most significant word
            <FieldOffset(2)> Dim msw As UNION_INT16     ' Least significant word
            <FieldOffset(0)> Dim w32 As Integer
        End Structure

        ' The Calculate method calculates the checksum value.
        Public Function Calculate(ByRef buffer() As UInt16, ByVal size As Int32) As UInt16
            Dim counter As Int32 = 0
            Dim cksum32 As UNION_INT32
            Do While (size > 0)
                cksum32.w32 += Convert.ToInt32(buffer(counter))
                counter += 1
                size -= 1
            Loop

            cksum32.w32 = cksum32.msw.w16 + cksum32.lsw.w16 + cksum32.msw.w16
            Return Convert.ToUInt16(cksum32.lsw.w16 Xor &HFFFF)
        End Function
    End Module



0
 

Author Comment

by:courchjo
ID: 14699923
Hey I changed my app to use sockets.  The problem is that it doesn't work on a machine with the user logged in as a USER.  Is there a way around this?  I do not want to logon to the machine with admin rights.

thanks
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now