Using Visual Basic to run a Dos Command with Txt input

The dos command I want to run is ping 192.168.1.1. 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.
reggiewolfAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Technology SpecialistCommented:
Hi,

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.


cheers,
Alex
        Dim ip As String = "192.168.1.1"
 
        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
 
        p.Start()
 
        ' this output variable will hold everything that is supposed to appear on the console
        Dim output As String = p.StandardOutput.ReadToEnd()
        p.WaitForExit()
 
        MessageBox.Show(output)

Open in new window

0
Alexandre SimõesManager / Technology SpecialistCommented:
This is VB.net btw...
0
Bob LearnedCommented:
For VB.NET 2005, and greater, there is the System.Net.NetworkInformation.Ping class, so you don't need a DOS command.
0
jake072Commented:
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,

Jake
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()
        MyBase.New()
 
        'This call is required by the Windows Form Designer.
        InitializeComponent()
 
        '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
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    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.SuspendLayout()
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(8, 8)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.TabIndex = 0
        Me.TextBox1.Text = "xxx.xxx.xxx.xxx"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(112, 8)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 1
        Me.Button1.Text = "Ping"
        '
        'TextBox2
        '
        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 = ""
        '
        'Form1
        '
        Me.AcceptButton = Me.Button1
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.TextBox2)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.TextBox1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)
 
    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
 
        Else
 
            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
        TextBox2.Update()
 
        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
 
            Else
 
                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
 
            TextBox2.Update()
 
        Next
 
        For j As Integer = 0 To 3
            If result(j).Status = ICMPClass.ICMPStatusEnum.Success Then
                decAverage += result(j).RoundTripTime
            End If
        Next
 
        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: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3194&lngWId=10
    '//**************************************
    '//     
    '// 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
    'and
    '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://
    '//     www.Planet-Source-Code.com/vb/scripts/Sh
    '//     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. 
        'Usage:
        'ex 1: console.WriteLine Ping("192.168.0.1").RoundTripTime
        'ex 2: dim reply as ICMPReplyStructure
        ' reply = Ping("192.168.0.1", 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
            Try
                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

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bob LearnedCommented:
Wow!! Even more code--gotta love it!! *WINK*.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.