Using Visual Basic to run a Dos Command with Txt input

Posted on 2008-11-04
Last Modified: 2013-11-25
The dos command I want to run is ping But I would like to have a txt box that a user can input the ip address they would like to ping. I would also like the command window to appear and show the results.
Question by:reggiewolf
    LVL 30

    Expert Comment

    by:Alexandre Simões

    I've created this on a windows project so I'm using MessageBox.Show...
    Use the output variable to show the console output the way you like.

            Dim ip As String = ""
            Dim p As New System.Diagnostics.Process
            p.StartInfo.UseShellExecute = False
            p.StartInfo.CreateNoWindow = True       ' don't show the console window
            p.StartInfo.RedirectStandardOutput = True
            p.StartInfo.FileName = "ping"  ' the command to run
            p.StartInfo.Arguments = ip  ' the command arguments
            ' this output variable will hold everything that is supposed to appear on the console
            Dim output As String = p.StandardOutput.ReadToEnd()

    Open in new window

    LVL 30

    Expert Comment

    by:Alexandre Simões
    This is btw...
    LVL 96

    Expert Comment

    by:Bob Learned
    For VB.NET 2005, and greater, there is the System.Net.NetworkInformation.Ping class, so you don't need a DOS command.
    LVL 14

    Accepted Solution

    I made something quick for you that does NOT open a window, although that would be easy, but rather gives output for you in a textbox...

    Hope it'll help,

    Option Strict On
    Imports System.Text.RegularExpressions
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Runtime.InteropServices
    Public Class Form1
        Inherits System.Windows.Forms.Form
    #Region " Windows Form Designer generated code "
        Public Sub New()
            'This call is required by the Windows Form Designer.
            'Add any initialization after the InitializeComponent() call
        End Sub
        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                End If
            End If
        End Sub
        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer
        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
        Friend WithEvents Button1 As System.Windows.Forms.Button
        Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.TextBox1 = New System.Windows.Forms.TextBox
            Me.Button1 = New System.Windows.Forms.Button
            Me.TextBox2 = New System.Windows.Forms.TextBox
            Me.TextBox1.Location = New System.Drawing.Point(8, 8)
            Me.TextBox1.Name = "TextBox1"
            Me.TextBox1.TabIndex = 0
            Me.TextBox1.Text = ""
            Me.Button1.Location = New System.Drawing.Point(112, 8)
            Me.Button1.Name = "Button1"
            Me.Button1.TabIndex = 1
            Me.Button1.Text = "Ping"
            Me.TextBox2.Location = New System.Drawing.Point(8, 40)
            Me.TextBox2.Multiline = True
            Me.TextBox2.Name = "TextBox2"
            Me.TextBox2.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
            Me.TextBox2.Size = New System.Drawing.Size(272, 216)
            Me.TextBox2.TabIndex = 2
            Me.TextBox2.Text = ""
            Me.AcceptButton = Me.Button1
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(292, 266)
            Me.Name = "Form1"
            Me.Text = "Form1"
        End Sub
    #End Region
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim strPattern As String = "^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"
            Dim regCheck As New Regex(strPattern)
            If TextBox1.Text = "" Then
                MessageBox.Show("You must enter an ip to search for!")
                Exit Sub
                If regCheck.IsMatch(TextBox1.Text, 0) = False Then
                    MessageBox.Show("Invalid IP address." & vbCrLf & "Address must be ###.###.###.###")
                    Exit Sub
                End If
            End If
            TextBox2.Text &= "Pinging " & TextBox1.Text & " with 32 bytes of data:" & vbCrLf
            Dim result As ICMPClass.ICMPReplyStructure()
            ReDim result(3)
            Dim intLost As Integer = 0
            Dim intReceived As Integer = 0
            Dim intMin As Integer = Integer.MaxValue
            Dim intMax As Integer = Integer.MinValue
            Dim decAverage As Decimal = 0
            Dim i As Integer
            For i = 0 To 3
                Dim icmp As New ICMPClass
                result(i) = icmp.Ping(TextBox1.Text)
                If result(i).Status <> ICMPClass.ICMPStatusEnum.Success Then
                    TextBox2.Text &= result(i).Message & vbCrLf
                    intLost += 1
                    intReceived += 1
                    TextBox2.Text &= "Reply from: " & result(i).ReplyFrom.ToString() & " bytes=32 time=" & result(i).RoundTripTime & "ms TTL=" & result(i).TTL & vbCrLf
                    If intMin > result(i).RoundTripTime Then
                        intMin = result(i).RoundTripTime
                    End If
                    If intMax < result(i).RoundTripTime Then
                        intMax = result(i).RoundTripTime
                    End If
                End If
            For j As Integer = 0 To 3
                If result(j).Status = ICMPClass.ICMPStatusEnum.Success Then
                    decAverage += result(j).RoundTripTime
                End If
            decAverage /= intReceived
            TextBox2.Text &= vbCrLf & "Ping statistics for " & TextBox1.Text & ":" & vbCrLf & vbTab & "Packets: Sent=" & i & ", Received = " & intReceived & ", Lost = " & intLost & " (" & intReceived / i & "% loss)," & vbCrLf & "Approximate round trip times in milli-seconds:" & vbCrLf & vbTab & "Minimum = " & intMin & "ms, Maximum = " & intMax & "ms, Average = " & CInt(decAverage) & "ms" & vbCrLf & vbCrLf
        End Sub
        ' Taken from:
        '// Name: A ping class in VB.Net
        '// Description:This class allows the use
        '//     r to ping a remote host. This example us
        '//     es API calls to ICMP.dll, so compiled so
        '//     urces do not need administrative rights 
        '//     to run.
        '// By: Alan Toews
        '// Inputs:The main function in this clas
        '//     s (Ping) has two overloads, declared as 
        '//     follows:
        'Public Function Ping(ByVal Host As String, Optional ByVal Timeout As Integer = 2000, Optional ByVal TTL As Byte = 32, Optional ByVal DataSize As Long = 32) As ICMPReplyStructure
        'Public Function Ping(ByVal IP As IPAddress, ByVal opt As ICMPOptions) As ICMPReplyStructure
        '// Returns:The structure declared below 
        '//     is returned 
        '// Assumes:To use this code, add a modul
        '//     e to your project and insert the code be
        '//     low in its entirety. Examples of how it 
        '//     is used can be found in the comments wit
        '//     hin the code.
        '// Side Effects:While the code works wel
        '//     l for me, it is only an example. You wil
        '//     l likely find unhandled errors, bugs, et
        '//     c..
        '//This code is copyrighted and has    // limited warranties.Please see http://
        '//     owCode.asp?txtCodeId=3194&lngWId=10    //for details.    //**************************************
        Public Class ICMPClass
            'Enumerated list of icmp echo reply response codes
            Public Enum ICMPStatusEnum
                Success = 0
                BufferTooSmall = 11001 'Buffer Too Small 
                DestinationNetUnreachable = 11002 'Destination Net Unreachable 
                DestinationHostUnreachable = 11003 'Destination Host Unreachable 
                DestinationProtocolUnreachable = 11004 'Destination Protocol Unreachable 
                DestinationPortUnreachable = 11005 'Destination Port Unreachable 
                NoResource = 11006 'No Resources 
                BadOption = 11007 'Bad Option 
                HardwareError = 11008 'Hardware Error 
                LargePacket = 11009 'Packet Too Big 
                RequestTimedOUT = 11010 'Request Timed Out 
                BadRequest = 11011 'Bad Request 
                BadROUTE = 11012 'Bad Route 
                TtlExpiredInTransit = 11013 'TimeToLive Expired Transit 
                TtlExpiredInReassembly = 11014 'TimeToLive Expired Reassembly 
                Parameter = 11015 'Parameter Problem 
                SourceQuench = 11016 'Source Quench 
                OptionTooBig = 11017 'Option Too Big 
                BadDestination = 11018 'Bad Destination 
                NegotiatingIPSEC = 11032 'Negotiating IPSEC 
                GeneralFailure = 11050 'General Failure 
            End Enum
            'User Friendly ping command that accepts a host as either an ip address 
            'or a resolvable name. 
            'ex 1: console.WriteLine Ping("").RoundTripTime
            'ex 2: dim reply as ICMPReplyStructure
            ' reply = Ping("", 1000,16)
            ' console.WriteLine reply.ReplyFrom.ToString & " replied in " & reply.RoundTripTime & _
            '"ms. status:" & reply.status & ":" & reply.message & ". TTL=" & reply.TTL
            Public Function Ping(ByVal Host As String, Optional ByVal Timeout As Integer = 2000, Optional ByVal TTL As Byte = 32, Optional ByVal DataSize As Long = 32) As ICMPReplyStructure
                Dim IP As IPAddress
                Dim opt As ICMPOptions
                    IP = Dns.GetHostByName(Host).AddressList(0)
                Catch ex As Exception
                    Dim r As ICMPReplyStructure
                    'create a mock reply 
                    r.Message = ex.ToString
                    r.ReplyFrom = New IPAddress(0)
                    r.Status = ICMPStatusEnum.GeneralFailure
                    r.TTL = 255
                    'return the error message as a ICMP general error
                    Return r
                    Exit Function
                End Try
                opt.Timeout = Timeout
                opt.TimeToLive = TTL
                opt.DatSize = DataSize
                Return Ping(IP, opt)
            End Function
            'Code friendly Ping that actually does the work
            Public Function Ping(ByVal IP As IPAddress, ByVal opt As ICMPOptions) As ICMPReplyStructure
                Dim ICMPHandle As IntPtr
                Dim iIP As Int32
                Dim sData As String
                Dim oICMPOptions As New ICMPClass.ICMP_OPTIONS
                Dim ICMPReply As ICMP_ECHO_REPLY
                Dim iReplies As Int32
                ICMPHandle = IcmpCreateFile
                iIP = System.BitConverter.ToInt32(IP.GetAddressBytes, 0)
                sData = "X"
                oICMPOptions.Ttl = opt.TimeToLive
                iReplies = IcmpSendEcho(ICMPHandle, iIP, sData, sData.Length, oICMPOptions, ICMPReply, Marshal.SizeOf(ICMPReply), opt.Timeout)
                Dim reply As ICMPReplyStructure
                reply = FillReplyStructure(ICMPReply)
                Return reply
            End Function
            'return a people friendly message from the status code
            Public Function GetMessage(ByVal status As ICMPStatusEnum) As String
                Select Case status
                    Case ICMPStatusEnum.Success
                        Return "Success"
                    Case ICMPStatusEnum.BufferTooSmall
                        Return "Buffer Too Small"
                    Case ICMPStatusEnum.DestinationNetUnreachable
                        Return "Destination Net Unreachable"
                    Case ICMPStatusEnum.DestinationHostUnreachable
                        Return " Destination Host Unreachable"
                    Case ICMPStatusEnum.DestinationProtocolUnreachable
                        Return "Destination Protocol Unreachable"
                    Case ICMPStatusEnum.DestinationPortUnreachable
                        Return "Destination Port Unreachable"
                    Case ICMPStatusEnum.NoResource
                        Return "No Resources"
                    Case ICMPStatusEnum.BadOption
                        Return "Bad Option"
                    Case ICMPStatusEnum.HardwareError
                        Return "Hardware Error"
                    Case ICMPStatusEnum.LargePacket
                        Return "Packet Too Big"
                    Case ICMPStatusEnum.RequestTimedOUT
                        Return "Request Timed Out"
                    Case ICMPStatusEnum.BadRequest
                        Return "Bad Request"
                    Case ICMPStatusEnum.BadROUTE
                        Return "Bad Route"
                    Case ICMPStatusEnum.TtlExpiredInTransit
                        Return "TimeToLive Expired Transit"
                    Case ICMPStatusEnum.TtlExpiredInReassembly
                        Return "TimeToLive Expired Reassembly"
                    Case ICMPStatusEnum.Parameter
                        Return "Parameter Problem"
                    Case ICMPStatusEnum.SourceQuench
                        Return "Source Quench"
                    Case ICMPStatusEnum.OptionTooBig
                        Return "Option Too Big"
                    Case ICMPStatusEnum.BadDestination
                        Return "Bad Destination"
                    Case ICMPStatusEnum.NegotiatingIPSEC
                        Return "Negotiating IPSEC"
                    Case ICMPStatusEnum.GeneralFailure
                        Return "General Failure"
                End Select
            End Function
            'fill the reply structure which will be passed abck to the user with data
            'from the ICMP_ECHO_REPLY structure.
            Private Function FillReplyStructure(ByVal IER As ICMP_ECHO_REPLY) As ICMPReplyStructure
                Dim irs As ICMPReplyStructure
                irs.RoundTripTime = IER.RoundTripTime
                irs.Message = GetMessage(IER.Status)
                irs.ReplyFrom = New IPAddress(IER.Address)
                irs.Data = IER.Data
                irs.Status = IER.Status
                irs.TTL = IER.Options.Ttl
                Return irs
            End Function
            'API functions contained in ICMP.DLL these functions perform the actual pinging
            Private Declare Auto Function IcmpCreateFile Lib "ICMP.DLL" () As IntPtr
            Private Declare Auto Function IcmpSendEcho Lib "ICMP.DLL" _
            (ByVal IcmpHandle As IntPtr, ByVal DestinationAddress As Integer, _
            ByVal RequestData As String, ByVal RequestSize As Integer, _
            ByRef RequestOptions As ICMP_OPTIONS, ByRef ReplyBuffer As ICMP_ECHO_REPLY, _
            ByVal ReplySize As Integer, ByVal Timeout As Integer) As Integer
            <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
            Public Structure ICMP_OPTIONS
                Public Ttl As Byte
                Public Tos As Byte
                Public Flags As Byte
                Public OptionsSize As Byte
                Public OptionsData As IntPtr
            End Structure
            <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
            Public Structure ICMP_ECHO_REPLY
                Public Address As Integer
                Public Status As ICMPStatusEnum
                Public RoundTripTime As Integer
                Public DataSize As Short
                Public Reserved As Short
                Public DataPtr As IntPtr
                Public Options As ICMP_OPTIONS
                <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=250)> _
                Public Data As String
            End Structure
            Public Structure ICMPReplyStructure
                Public ReplyFrom As IPAddress
                Public RoundTripTime As Integer
                Public Data As String
                Public Status As ICMPStatusEnum
                Public Message As String
                Public TTL As Byte
            End Structure
            Public Structure ICMPOptions
                Public Timeout As Integer
                Public TimeToLive As Byte
                Public DatSize As Long
            End Structure
        End Class
    End Class

    Open in new window

    LVL 96

    Expert Comment

    by:Bob Learned
    Wow!! Even more code--gotta love it!! *WINK*.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
    It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
    As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
    Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

    737 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

    19 Experts available now in Live!

    Get 1:1 Help Now