' Collection of code snippets by Arne Vajhøj 
' (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
Imports System
Imports System.Net
Imports System.Runtime.InteropServices

<StructLayout(LayoutKind.Sequential,Pack:=1)> _
Public Structure ICMP_ECHO_REPLY
    Public Address As Integer
    Public Status As Integer
    Public RoundTripTime As Integer
    Public DataSize As UInt16
    Public Reserved As UInt16
    Public Data As IntPtr
    Public Options As IP_OPTION_INFORMATION
End Structure 

<StructLayout(LayoutKind.Sequential,Pack:=1)> _
Public Structure IP_OPTION_INFORMATION
    Public TTL As Byte
    Public TOS As Byte
    Public Flags As Byte
    Public OptionsSize As Byte
    Public OptionsData As IntPtr
    Public RealOptionData As Integer
End Structure 

Public Class Icmp
    Public Const IP_SUCCESS As Integer = 0
    Public Const IP_BUF_TOO_SMALL As Integer = 11001
    Public Const IP_REQ_TIMED_OUT As Integer = 11010

    <DllImport("icmp.dll")> _
    Public Shared Function IcmpCreateFile() As IntPtr
    End Function

    <DllImport("icmp.dll")> _
    Public Shared Function IcmpSendEcho(ByVal icmpHandle As IntPtr, ByVal ipAddr As Integer, ByRef requestData As Integer, ByVal requestSize As Short, ByVal optionInfo As IntPtr, ByRef replyBuffer As ICMP_ECHO_REPLY, ByVal replySize As Integer, ByVal timeout As Integer) As Integer
    End Function

    <DllImport("icmp.dll")> _
    Public Shared Function IcmpCloseHandle(ByVal icmpHandle As IntPtr) As Boolean
    End Function

    Public Shared Function Ping(ByVal host As String) As Boolean
        Dim addr As Integer = BitConverter.ToInt32(IPAddress.Parse(host).GetAddressBytes, 0)
        '.NET 1.0: Dim addr As Integer = BitConverter.ToInt32(BitConverter.GetBytes(IPAddress.Parse(host).Address), 0)
        Dim h As IntPtr = IcmpCreateFile
        Dim req As Integer = 123456789
        Dim rep As ICMP_ECHO_REPLY = New ICMP_ECHO_REPLY
        Dim retval As Integer = IcmpSendEcho(h, addr, req, 4, IntPtr.Zero, rep, 32, 10)
        IcmpCloseHandle(h)
        Return (retval <> 0 AndAlso rep.Status = IP_SUCCESS)
    End Function
End Class 

Public Class TestClass
    Public Shared Sub Main(ByVal args As String())
        Console.WriteLine("min server : " & Icmp.Ping("192.168.1.10"))
        Console.WriteLine("ikke eksisterende : " & Icmp.Ping("192.168.1.25"))
        Console.WriteLine("www.google.dk (svarer) : " & Icmp.Ping("216.239.59.104"))
        Console.WriteLine("www.eksperten.dk (svarer ikke) : " & Icmp.Ping("62.199.138.148"))
    End Sub
End Class 
