Visual basic ICMP Pinger? - vb.net

I am building an ICMP Pinger in visual basic.
I would like to be able to determine the destination address, time out, size of packets, and how many packets to send.
I only have a small amount of programming knowledge, does anybody have any suggestions? Or a more efficient way to run the program?
Here is what i have that is working so far.
Option Explicit On
Option Infer Off
Imports System.Net.NetworkInformation
Imports System.ComponentModel
Public Class Form1
Private WithEvents bwPing As New BackgroundWorker
Private pingTarget As String
Private pingsize As Integer
Private numOfpings As Integer
Dim timeout As Integer
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' start pinger
bwPing.WorkerReportsProgress = True
bwPing.WorkerSupportsCancellation = True
pingTarget = TextBox2.Text
timeout = ComboBox4.Text
If Not bwPing.IsBusy Then bwPing.RunWorkerAsync()
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" By failing to prepare, you are preparing to fail. ", MsgBoxStyle.Exclamation)
ElseIf ComboBox3.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How many troops are you sending in? ", MsgBoxStyle.Exclamation)
ElseIf ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How strong are your soldiers? ", MsgBoxStyle.Exclamation)
Else : numOfpings = CInt(ComboBox3.Text)
pingsize = CInt(ComboBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' cancel pinger
bwPing.CancelAsync()
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
' clear
ListBox1.Items.Clear()
ComboBox1.Text = ""
ComboBox3.Text = ""
ProgressBar1.Value = 0
End Sub
Private Sub bwPing_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwPing.DoWork
' ping worker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim packet(pingsize) As Byte
For i As Integer = 0 To numOfpings - 1
bwPing.ReportProgress(i + 1)
Dim ping As New Ping
Dim reply As PingReply = ping.Send(pingTarget, timeout)
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
Else
ListBox1.Items.Add("You hit " & pingTarget & " in " & reply.RoundtripTime.ToString() & " ms with " & pingsize & " bytes.")
System.Threading.Thread.Sleep(500)
End If
If worker.CancellationPending Then Exit For
Next
End Sub
Private Sub bwPing_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bwPing.ProgressChanged
' update results
Me.ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = numOfpings
End Sub
Private Sub bwPing_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bwPing.RunWorkerCompleted
' finished
Me.ListBox1.Items.Add("*!* The battle is over, but not the war *!*")
bwPing.CancelAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class

Related

loop data in textbox from serial data vb.net

I'm newbie to VB.net. my case is, i need to display data from serial port to text box. In continuous loop. How do i do that?
I have wrote simple program to display the data. i can display the data once in the textbox, but not continuously.
serialport1 is where i get data from port 1. serialport2 is data from port 2.
SerialPort2.Write("!12,F" & vbCr)
data "!11,F" and "!12,F" is a command to my 2 device.
TextBox2.Text and TextBox5.Text is where i want to continuously display my data.
here is the code;
Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class Form2
Dim myPort As Array
Dim myport1 As Array
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
'------------------------------------------------
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
myport1 = IO.Ports.SerialPort.GetPortNames()
ComboBox1.Items.AddRange(myPort)
ComboBox2.Items.AddRange(myport1)
btnwrite.Enabled = False
End Sub
'------------------------------------------------
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles btninit.Click
SerialPort1.Encoding = System.Text.Encoding.GetEncoding(28591) ' convert to ascii
SerialPort1.PortName = ComboBox1.Text
SerialPort1.BaudRate = TextBox3.Text
SerialPort1.Open()
SerialPort2.Encoding = System.Text.Encoding.GetEncoding(28591) ' convert to ascii
SerialPort2.PortName = ComboBox2.Text
SerialPort2.BaudRate = TextBox3.Text
SerialPort2.Open()
btninit.Enabled = False
btnwrite.Enabled = True
btnwrite2.Enabled = True
btnclose.Enabled = True
End Sub
'------------------------------------------------
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnwrite.Click
SerialPort1.Write("!11,F" & vbCr) 'concatenate with \n
End Sub
Private Sub btnwrite2_Click(sender As Object, e As EventArgs) Handles btnwrite2.Click
SerialPort2.Write("!12,F" & vbCr) 'concatenate with \n
End Sub
Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub SerialPort2_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
ReceivedText1(SerialPort2.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String) 'input from ReadExisting
If Me.TextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox2.Text &= [text] 'append text
End If
End Sub
Private Sub ReceivedText1(ByVal [text] As String) 'input from ReadExisting
If Me.TextBox5.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText1)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox5.Text &= [text] 'append text
End If
End Sub
Private Sub btnclose_click(sender As System.Object, e As System.EventArgs) Handles btnclose.Click
SerialPort1.Close()
SerialPort2.Close()
btninit.Enabled = True
btnwrite.Enabled = False
btnwrite2.Enabled = False
btnclose.Enabled = False
End Sub
End Class

How to save my wlan settings?

I'm currently using Visual Studio 2012. My form code is given below with design screenshots. I am trying to make a virtual hotspot for my PC but I want to add one feature which takes previous SSID and password. My hotspot opens every time with blank text.
Here's my form design:
Form1 Design:
[
Form1 code:
Imports System.Runtime.InteropServices
Imports System.Collections.ObjectModel
Imports System.Text
Imports NativeWifi
Public Class Form1
Public Const WM_NCLBUTTONDOWN As Integer = &HA1
Public Const HT_CAPTION As Integer = &H2`
<DllImportAttribute("user32.dll")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Msg As Integer, ByVal wParam As Integer, _
ByVal lParam As Integer) As Integer
End Function
<DllImportAttribute("user32.dll")> _
Public Shared Function ReleaseCapture() As Boolean
End Function`
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim wlan = New WlanClient()
Dim connectedSsids As Collection(Of [String]) = New Collection(Of String)()
For Each wlanInterface As WlanClient.WlanInterface In wlan.Interfaces
Dim ssid As Wlan.Dot11Ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid
connectedSsids.Add(New [String](Encoding.ASCII.GetChars(ssid.SSID, 0, CInt(ssid.SSIDLength))))
For Each item As String In connectedSsids
Label1.Text = item
Next
Next
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Me.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
ReleaseCapture()
SendMessage(Handle, WM_NCLBUTTONDOWN, _
HT_CAPTION, 0)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If Form2.TextBox1.Text = "" Then
MsgBox("Hotspot name cant be empty", MsgBoxStyle.Critical)
End If
If Form2.TextBox2.TextLength < 8 Then
MsgBox("Password should be 8+ character", MsgBoxStyle.Critical)
If Form2.TextBox2.Text = "" Then
MsgBox("Password cant be empty", MsgBoxStyle.Critical)
End If
Else
Dim process As New Process()
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = True
process.Start("cmd", String.Format("/c {0} & {1} & {2}", "netsh wlan set hostednetwork mode=allow ssid=" & Form2.TextBox1.Text & " key=" & Form2.TextBox2.Text, "netsh wlan start hostednetwork", "pause"))
Form2.CheckBox1.Enabled = False
Form2.TextBox1.Enabled = False
Form2.TextBox2.Enabled = False
MsgBox("Hotspot started Successfully", MsgBoxStyle.Information)
End If
Catch
MsgBox("Failed to Establish a hotspot", MsgBoxStyle.Exclamation)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Process.Start("CMD", "/C netsh wlan stop hostednetwork")
Form2.CheckBox1.Enabled = True
Form2.TextBox1.Enabled = True
Form2.TextBox2.Enabled = True
MsgBox("Hotspot stopped Successfully", MsgBoxStyle.Information)
End Sub
Private Sub Clsbtn_Click(sender As Object, e As EventArgs) Handles Clsbtn.Click
Me.Close()
End Sub
Private Sub Minbtn_Click(sender As Object, e As EventArgs) Handles Minbtn.Click
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
End Sub
Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
Me.Hide()
Form2.Show()
End Sub
End Class
Form2 Design:
[

Visual Basic Pinger

I have this pinger up and running well, but cannot think of a way for the program to tell me if a ping reply has failed. I would like it to display in the listbox when there is an error.
Any help would be greatly appreciated.
Option Explicit On
Option Infer Off
Imports System.Net.NetworkInformation
Imports System.ComponentModel
Public Class Form1
Private WithEvents bwPing As New BackgroundWorker
Private pingTarget As String
Private pingsize As Integer
Private numOfpings As Byte
Dim timeout As Integer
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' start pinger
bwPing.WorkerReportsProgress = True
bwPing.WorkerSupportsCancellation = True
pingTarget = TextBox2.Text
timeout = ComboBox4.Text
If Not bwPing.IsBusy Then bwPing.RunWorkerAsync()
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" By failing to prepare, you are preparing to fail. ", MsgBoxStyle.Exclamation)
ElseIf ComboBox3.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How many troops are you sending in? ", MsgBoxStyle.Exclamation)
ElseIf ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How strong are your soldiers? ", MsgBoxStyle.Exclamation)
Else : numOfpings = CInt(ComboBox3.Text)
pingsize = CInt(ComboBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' cancel pinger
bwPing.CancelAsync()
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
' clear
ListBox1.Items.Clear()
ComboBox1.Text = ""
ComboBox3.Text = ""
ProgressBar1.Value = 0
End Sub
Private Sub bwPing_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwPing.DoWork
' ping worker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim packet(pingsize) As Byte
For i As Integer = 0 To numOfpings - 1
bwPing.ReportProgress(i + 1)
Dim ping As New Ping
Dim reply As PingReply = ping.Send(pingTarget, timeout, packet)
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
Else
ListBox1.Items.Add("You hit " & pingTarget & " in " & reply.RoundtripTime.ToString() & " ms with " & pingsize & " bytes.")
System.Threading.Thread.Sleep(500)
End If
If worker.CancellationPending Then Exit For
Next
End Sub
Private Sub bwPing_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bwPing.ProgressChanged
' update results
Me.ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = numOfpings
End Sub
Private Sub bwPing_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bwPing.RunWorkerCompleted
' finished
Me.ListBox1.Items.Add("*!* The battle is over, but not the war *!*")
Me.ListBox1.Items.Add("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
bwPing.CancelAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class
In general, try to remember that you can check an object for any events it has. Typically, when an object has a completed event, somewhere in the event args, pertinent things, such as completion status, will be provided to you there, in those arguments. That being said, handle the ping completed event.
Side Note* Setting CheckForIllegalCrossThreadCalls to false is not a good idea, use delegates instead.
Example(for ping)
Option Strict On
Option Explicit On
Option Infer Off
Imports System.Net
Imports System.Net.NetworkInformation
Public Class Form1
Private a As New Ping
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler a.PingCompleted, AddressOf a_PingCompleted
End Sub
Private Sub a_PingCompleted(sender As Object, e As PingCompletedEventArgs)
If e.Reply.Status.ToString = "Success" Then
MsgBox("Round Trip Time: " & e.Reply.RoundtripTime.ToString & "ms")
Else
MsgBox(e.Reply.Status.ToString)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Google's ip address
a.SendAsync(New IPAddress({74, 125, 224, 105}), 100)
End Sub
End Class

vb For loop repeat a certain number of times

So I am making a port scanner and have a min and max port, but can't get the port scanner to stop scanning when it reaches the maximum port?
I have tried doing an Exit For when port reaches portmax.
Here is the code:
Public Class Form1
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim counter As Integer
Button2.Enabled = False
'set counter explained before to 0
counter = 0
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
Dim host As String
Dim counter As Integer
Dim portmin As Integer = TextBox3.Text
Dim portmax As Integer = TextBox2.Text
'Set the host and port and counter
counter = counter + 1 'counter is for the timer
host = TextBox1.Text
For port As Integer = portmin To portmax
' Next part creates a socket to try and connect
' on with the given user information.
Dim hostadd As System.Net.IPAddress = _
System.Net.Dns.GetHostEntry(host).AddressList(0)
Dim EPhost As New System.Net.IPEndPoint(hostadd, port)
Dim s As New System.Net.Sockets.Socket( _
System.Net.Sockets.AddressFamily.InterNetwork, _
System.Net.Sockets.SocketType.Stream, _
System.Net.Sockets.ProtocolType.Tcp)
Try
s.Connect(EPhost)
Catch
End Try
If Not s.Connected Then
ListBox1.Items.Add("Port " + port.ToString + " is not open")
Else
ListBox1.Items.Add("Port " + port.ToString + " is open")
ListBox2.Items.Add(port.ToString)
End If
Label3.Text = "Open Ports: " + ListBox2.Items.Count.ToString
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
'stop button
Timer1.Stop()
Timer1.Enabled = False
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Add("Scanning: " + TextBox1.Text)
ListBox1.Items.Add("-------------------")
Button2.Enabled = True
Button1.Enabled = False
Timer1.Enabled = True
Timer1.Start()
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
End Sub
End Class
I would really appreciate any help
thanks,
Try to stop the Timer while in the scanning.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Enabled = False
'Your code
Timer1.Enabled = True
End Sub
If thats the problem, and looks like it, you should consider using a Try/Catch block:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Try
Timer1.Enabled = False
'Your code
Catch ex As Exception
'Manage the error
Finally
Timer1.Enabled = True
End Try
End Sub
Try this
For port As Integer = portmin To portmax - 1

Very basic VB.Net & Serial IO issue

After searching around I am still having issues with reading data from a serial port in VB.Net/VS2010. I know the Serial Port works, I can write to the port fine but when reading from it, nothing happens. I have only been programming for the last 3 weeks so am still trying to get my head around it all.
The program must run to capture data from a door logger, I will then be outputting the data to a database (not yet implemented - I want to get this part sorted first).
I have tried using several terminal programs as well as another device which outputs data onto the serial line, with nothing displaying in the textbox tbxIn.
Any help would be greatly appreciated.
Code is below:
Imports System.IO.Ports
Imports System.IO.Ports.SerialPort
Public Class Form1
Dim comPort As IO.Ports.SerialPort = Nothing
Dim sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
tbxIn.Text = e.ToString
End Sub
End Class
PRetty sure this will get you what you need. You DON't need the Serial1 component on the designer. Remove that and use this code:
Private comPort As IO.Ports.SerialPort = Nothing
Private sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
'must add handler
AddHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
'remove handler
RemoveHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
tbxIn.Text = e.ToString
End Sub