Get "real" IP address with VB.NET? - vb.net

I'm looking for a function that will give me my real IP, not my local IP. the function i currently have, returns the ip in network and sharing center which is 192.168.2.100
But if I go to whatismyip, then it gives my real IP.
How could I get this using VB.NET?
thanks

To Combine the answers above"
Create a php file and paste this in it:
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
save it as curip.php and upload it to your server.
In your VB.net project create a module.
Declare the imports section at the very top
Imports System.Net
Imports System.IO
And create your function:
Public Function GetIP() As String
Dim uri_val As New Uri("http://yourdomain.com/curip.php")
Dim request As HttpWebRequest = HttpWebRequest.Create(uri_val)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim myIP As String = reader.ReadToEnd()
response.Close()
Return myIP
End Function
Now anywhere in your code you can issue
Dim myIP = GetIP()
as use the value from there as you wish.

There's no way to do this just with VB.Net. You need to find a website that will tell you (perhaps one of your own?) or you need to interface with your router.
If you have a web site that is capable of running any sort of web page applications you can create a web page that simply outputs the client's (as in the computer connecting to the page) IP address.
I have one of my own:
http://etoys.netortech.com/devpages/ip.asp
Though I can't guarantee it will always be there which is why you should make your own.
From there it's a simple matter of using a HttpWebRequest to download the content of the page.

I'm probably just being crotchety here, but I can't help but think that your "real" IP address is the one returned by ifconfig (ipconfig) on your local machine. 192.168.2.100 in your case. Whatever NAT translation or tunneling goes on between you and the remote endpoint shouldn't matter, and if it does, there's a good chance you're doing something that could make your application only work in your current environment.

I would use a publicly available site which returns your public IP address in response.
The key factors here are:
Availability of the service. Running your own service guarantees full control over it and knowledge of when it is available and when it's not. But in some cases it might be just too much work for such a simple task.
Minimizing additional clutter contained in the response. There are plenty sites allowing you to get your public IP address, but they often do that in the form of a HTML page. Extracting the small fragment of the page containing the IP address might need additional code.
Keeping in mind these two factors I would recommend this URL: http://wtfismyip.com/text It has the advantage of returning only the IP address in textual form. There are also versions for:
JSON: http://wtfismyip.com/json
XML: http://wtfismyip.com/xml
Pick the format that is easier for you to parse.

You DON'T need to use a php file just use a site that shows your ip like ip-adress.com and then get the ip from there with webrequest and then use GetBetween function.
have fun :)

Using PHP it can be done simply:
As "shaiss" shared the PHP code, this is the VB.net code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myip As HttpWebRequest = HttpWebRequest.Create("http://YourHosting.com/curip.php")
Dim grab As HttpWebResponse = myip.GetResponse()
Dim stream As Stream = grab.GetResponseStream
Dim SR As New StreamReader(stream)
TextBox1.Text = SR.ReadToEnd()
End Sub
End Class
This is just an example with:
1 - Form
1 - TextBox
1 - Button(s)
Hope this helps!

I had the same question and searched a bit only to remember that I can do this with WebBrowser!
Private Sub getExtIP() Handles activeProjectsWB.DocumentCompleted
If gotIP = False And populateProjectCollectionBLN = True Then
If activeProjectsWB.ReadyState = WebBrowserReadyState.Interactive Or activeProjectsWB.ReadyState = WebBrowserReadyState.Complete Then
Dim unformattedExtIP As String = activeProjectsWB.Document.GetElementsByTagName("title").Item(0).OuterHtml
Dim onlyIPAddress As String = String.Empty
For Each character In unformattedExtIP
Dim result As Integer = 0
If Not (Integer.TryParse(character, result) = 0) Or character = "." Then
onlyIPAddress = onlyIPAddress & character
End If
Next
extIP = onlyIPAddress
gotIP = True
End If
End If
End Sub
This subroutine only is triggered when you navigate to a webpage using WebBrowser.Navigate().
The gotIP boolean exists because I have another subroutine that activates on any document completion. I don't want it to be triggered more than once. If you are unfamiliar with WebBrowser, you check to make sure the web page is loaded enough with ReadyState. If you don't, you may get an exception (because content isn't loaded).
You can use whichever site you like. This site is good because it puts your IP address in the title. That's good because there's going to be one title tag. In the event you can't use this site (or one that has a unique tag with your content within it), use a For Each loop.
For Each instance As HtmlElement In activeProjectsWB.Document.GetElementsByTagName("InsertTagHere")
'do something to find the tag that contains your IP address
Next

Related

List(Of...) WebBrowser - How to declare Web Browsers based on number of strings in an array

I am trying to grab images from a number of similar URLs (The urls do not end in an image format like .jpg). The number of URLs can vary, and is determined by counting the number of strings in an array of strings.
The best method I have found for downloading images from a website is taken from here:
https://www.codeguru.com/columns/vb/how-to-use-visual-studio-2012-to-download-images-from-websites.htm
This was working perfectly, however now I need to be able to declare more web browsers, depending on how many urls have to be visited to grab images for downloading. The following is what I would like to be able to do:
Dim photonumbers() As String = {"hdshshaga","sjshaghah","akajaha"}
Dim WebBrowsers As New List(Of WebBrowser)
Dim x As Integer
For x = 0 To photonumbers.Count - 1 Step 1
WebBrowsers.Add("wb"&x.ToString) 'I understand I am trying to add a string to a list of webbrowsers, but is there a way to declare a new webbrowser with this name?
Next
The reason I want to declare a new webbrowser for each url is that I cannot get the code from the above link to work as a single function solution. Instead you have to download the URL onto the web browser using one subroutine (eg.Triggered by a Button click), and then save all images from that webbrowser with the next subroutine. If anyone is able to advise me on how to change this code to a single function so that it can be called for each string, that would be even better.
Dim photonumbers() As String = {"hdshshaga", "sjshaghah", "akajaha"}
Dim WebBrowsers As New List(Of WebBrowser)
For Each photonumber As String In photonumbers
WebBrowsers.Add(New WebBrowser() With {.Name = "wb" & photonumber})
Next

TCP Client to Server communication

All I'm looking for is a simple TCPClient/Listner example on Windows Form VB.Net. I'm a newbie and Microsoft TCPClient/Listner class examples are not what I am looking for. All I am looking is for the TCPClient to send a message and for a TCPListener to get the message and to send a message back "I got your message" ?
A little help would be great. I have some codes, but is only to send message to server and not back from server to client..
Any help will be very appreciated..
TCP communication is stream-based, which means it doesn't handle any packets. Due to this, messages that you receive might be either partial or lumped together.
You could for example send:
Hello!
How are you?
But you might receive:
Hello!How are you?
or:
Hello!How ar
e you?
(or something similar)
To fix this you must apply something called "length-prefixing". Length-prefixing (or length prefixing) means that before you send a message, you put its length (amount of characters/bytes) in the beginning of it. By doing so, the endpoint will know exactly how many bytes to read for each message. Thus there will be no problems with messages being partial or lumped together.
This is not the most straightforward thing to do as a beginner, as to get it to work properly on both sides you have to structure your code just right. So I've created two classes that will take care of this for you. See the examples below on how to use them for simple text message-based communication.
Link to source: http://www.mydoomsite.com/sourcecodes/ExtendedTcpClient.zip
Link to C# source : http://www.mydoomsite.com/sourcecodes/ExtendedTcpClient%20CSharp.zip
EDIT (2019-11-08)
Some time ago I made an upgraded version of this with a bit better code structure and error handling. For those of you interested, the new code can be downloaded here (VB.NET only):
https://www.mydoomsite.com/sourcecodes/ExtendedTcpClient%202.0.zip
Example usage
Note that in those examples Client does not refer to the client side, but to the TcpClient.
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 will need a TcpListener and a Timer to check for incoming connections.
Dim Listener As New TcpListener("0.0.0.0", 5555) 'Listen for any connection on port 5555.
Dim WithEvents Tmr As New System.Windows.Forms.Timer
Then you need to subscribe to the timer's Tick event.
Private Sub Tmr_Tick(sender As System.Object, e As System.EventArgs) Handles Tmr.Tick
End Sub
In there you check for incoming connections via the Listener.Pending() method. When you are to accept a connection you first declare a new
instance of the ExtendedTcpClient. The class requires to have a
form as its owner, in this application Me is the current form.
Then you use the ExtendedTcpClient.SetNewClient() method with
Listener.AcceptTcpClient() as its argument to apply the
TcpClient from the listener. Put this code in the Tmr_Tick sub:
If Listener.Pending() = True Then
Client = New ExtendedTcpClient(Me)
Client.SetNewClient(Listener.AcceptTcpClient())
End If
Now the client and server are connected to each other.
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
All received data are presented in an array of bytes.
In the PacketReceived sub you can 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.PlainText Then
TextBox1.AppendText("Message recieved: " & System.Text.Encoding.Default.GetString(e.Packet.Contents) & Environment.NewLine)
End If
System.Text.Encoding.Default.GetString() will convert a byte array to normal text.
In the PacketReceived sub you can also make it send "Message received" to the client.
Dim ResponsePacket As New TcpMessagePacket(System.Text.Encoding.Default.GetBytes("Message received."), TcpMessagePacket.PacketHeader.PlainText)
ResponsePacket.Send(Client.Client) 'Get the ExtendedTcpClient's underlying TcpClient.
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 do pretty much the same as the server side, though you won't be needing a TcpListener nor a Timer.
Dim WithEvents Client As New ExtendedTcpClient(Me) 'The current form as its owner.
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 text to the server you'd do something like this (in for example a button):
Dim MessagePacket As New TcpMessagePacket(System.Text.Encoding.Default.GetBytes(TextBox2.Text), TcpMessagePacket.PacketHeader.PlainText)
MessagePacket.Send(Client.Client)
TextBox2 includes the text you want to send.
Lastly, you will need to subscribe to the PacketReceived event here too to check for responses from the server. In there you receive text just like the server does.
Private Sub Client_PacketReceived(sender As Object, e As ExtendedTcpClient.PacketReceivedEventArgs) Handles Client.PacketReceived
If e.Packet.Header = TcpMessagePacket.PacketHeader.PlainText Then
TextBox1.AppendText(System.Text.Encoding.Default.GetString(e.Packet.Contents) & Environment.NewLine) 'Prints for example "Message received." from the server.
End If
End Sub
And now everything should be working!
Link to a complete example project (only client-to-server): http://www.mydoomsite.com/sourcecodes/TCP%20Messaging%20System.zip
Link to C# example: http://www.mydoomsite.com/sourcecodes/CSharp%20TCP%20Messaging%20System.zip
If you want to add more headers to the class (the headers indicate to you what kind of data each packet contains), 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)

Make pc specific hash in vb.net

I want to make a program, which generate the same string each time, and it must be different on any each pc. So like HWID. After I have the string I send it into a php file on a remote host, the php handle it, and store it in the database.
On the first run it will make a new row in the table, but after 2nd run, it will select the row where the POST-ed hash = the hash in the table, and it has banned - not banned function. So if I give back 0 the pc is not banned, so program start to run, if I give back 1 the program close.
This is all made, my problem is, I generate hwid from processorid, and send it to the php. the processorid can be the same on different computers sometimes. So if I give fake ban, the users will be angry for me...
The question is:
How to generate a hash, which will be always the same on the pc which run the application, but different on each pc?
I know I can make it if I store a special id on the pc for example in the registry, but if somebody reinstall the pc, he can use again the service. If I generate hwid, it will takes him more time to find out how to access again to the service.
I dont think this really has anything to do with PHP, but entirely about the client side steps.
To do what it sounds like you want, you want to use a hardware signature made up of several things so that if one or two are unavailable, the result is still valid. This will use a form of the WMI polling procedure from the answer on your last question:
Private Shared Function GetHardwareItemInfo(item As String, wmiclass As String) As String
Dim data As String = ""
Dim query As String = String.Format("Select {0} From {1}", item, wmiclass)
Using mbs As ManagementObjectSearcher = New ManagementObjectSearcher(query)
For Each mo As ManagementObject In mbs.Get
For Each pd As PropertyData In mo.Properties
' should be only one
If String.Compare(pd.Name, item, StringComparison.InvariantCultureIgnoreCase) = 0 Then
' value is object, test for Nothing
If pd.Value IsNot Nothing Then
data = pd.Value.ToString
End If
Exit For
End If
Next
Next
End Using
Return data
End Function
This allows you to poll for different items in different wmi classes using the same code. Example:
' get the serialnumber item from the baseboard class:
answer = GetHardwareItemInfo("serialNumber", "Win32_BaseBoard")
For a hardware signature:
Get and store the info for each item
Combine them into one string
Convert the string to a byte array
Use crypto to hash the byte array
convert the result to a base64 string
There are other ways. For instance you could encode the result as a Hex string, but the above is what the code shows. First, these are the namespaces you need:
Imports System.Security.Cryptography
Imports System.Management
Imports System.Text
Then the procedure to get the stuff using the GetHardwareItemInfo method above:
' place to store bits of data
Dim HWStuff As New List(Of String)
Dim answer As String
' get and store some info
answer = GetHardwareItemInfo("serialNumber", "Win32_BaseBoard")
HWStuff.Add(answer)
answer = GetHardwareItemInfo("uuid", "win32_ComputerSystemProduct")
HWStuff.Add(answer)
answer = GetHardwareItemInfo("serialNumber", "Win32_OperatingSystem")
HWStuff.Add(answer)
'...etc
' glue the bits together into one string
Dim HWSig = String.Join("", HWStuff)
Dim byteHash As Byte()
' create crypto hasher
Using hasher = New SHA1Managed()
' convert the string to bytes
Dim tmpBytes = Encoding.UTF8.GetBytes(HWSig)
'hash the bytes
byteHash = hasher.ComputeHash(tmpBytes)
End Using
' encode as B64 string.
Dim HWHash = Convert.ToBase64String(byteHash)
Console.WriteLine(HWHash)
Result:
MUjeLeZtbTQ3Rc8zgFquBkOwFzA=
You could glue the string together as you get answers. But during development it helps to see the candidate info before you decide to use it or not.
Notes:
There are many many things to choose from. See WMI Win32 Classes.
Not everything needs to come from WMI. the LocalMachine name might be a good one (I have no idea of the context for this) as is the Windows Activation Key.
Other crypto hashers will produce longer hashes
This is far from foolproof.
Some things can be spoofed - the Win OS Serial number can be changed in the registry. You dont really care if the values are right, just that they do not change.
This is not copy protection. Someone could sniff out the token(s) sent from a legitimate system(s), then patch your app to send that token only.
if I store a special id...
No. Do not write anything down. Its impossible to keep a secret from the user on their own PC. Dont store the hash either - generate it every time. If you write it down it is easier to copy that value to a different machine.
I give fake ban, the users will be angry for me...
Since it sounds like you are working from a blacklist rather than a whitelist, you dont have to worry about the hash failing. The worst that will happen is that a system which should be denied access will get access. If you want to further reduce the chance of a match, use SHA512Managed; it will produce a longer hash though.
If a user changes one of the parts you are polling, they will still get in - it is quite unlikely that the hash from 2 systems will match (one white, one black).

Using Visual Basic to Select a Google Search Result in Internet Explorer

I have VB code that goes to Google, fills in the search bar, and hits the search button. Is there a way to have my program select a particular result after my search? ie. I search for "cheese", I would like for my program to select the 2nd to last result (in this case, it is wwww.chuckecheese.com)
I ended up using Sendkeys to emulate the tab and down arrow keys on the keyboard. You can then navigate to your desired search results using these 2 keys
Or you can bypass using an API and avoid ads or cost using speech recognition to improve your Dictation searches. Programming isn't programming if you aren't thinking outside the box and innovating your own solutions.
Coding comes with creativity and you won't know what that is if you don't try. This site is excellent for this very purpose and many have contributed to innovation in coding.
You will have to add a text file to your project and call it whatever you want, then change the path below in the code to your own path. The text file stays blank. The program will write your spoken search to file and then execute the search, constantly over-writing itself.
For some odd reason, this method greatly improves the fusion of speech recognition and dictation. You can speak an entire phrase and it will conduct the search. A good mic is a must and speaking clearly without background disturbances.
Imports System.Speech.Recognition
'Declarations:
Private ReadOnly Drone As New SpeechRecognitionEngine()
Private ReadOnly Qa As New DictationGrammar()
Private Sub Form1_Load(sender As Object,
e As EventArgs) Handles MyBase.Load
'Dictation Mode | Google Engine
Drone.LoadGrammarAsync(Qa)
Drone.RequestRecognizerUpdate()
Drone.SetInputToDefaultAudioDevice()
Drone.InitialSilenceTimeout = TimeSpan.FromSeconds(2.5)
Drone.BabbleTimeout = TimeSpan.FromSeconds(1.5)
Drone.EndSilenceTimeout = TimeSpan.FromSeconds(1.2)
Drone.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.5)
AddHandler Drone.SpeechRecognized, AddressOf Drone_SpeechRecognized
Drone.RecognizeAsync(RecognizeMode.Multiple)
End Sub
Private Sub Drone_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs)
Dim google As String = e.Result.Text.ToString
Select Case (google)
Case google
If google <> "+" Then
'This section will take spoken word, write to file then execute search.
Dim sb As New StringBuilder
'Be sure to change the text file path below to your path if you are new to this program.
sb.AppendLine(google)
'Add your own path below here. you can also change google to youtube and conduct youtube searches
File.WriteAllText("C:\Users\justin.ross\source\repos\ScarlettCenturium\Scarlett Centurium\Scarlett Centurium\File.txt", sb.ToString())
google = "https://www.google.com/search?q=" & Uri.EscapeUriString(google)
Dim proc As New Process()
Dim startInfo As New ProcessStartInfo(google)
proc.StartInfo = startInfo
proc.Start()
'This sendkey will close out previous tab on new search
SendKeys.Send($"^{{w}}")
Return
End If
End Select
End Sub
well you can use google api for that
goto http://code.google.com/p/google-api-for-dotnet/
download GoogleSearchAPI_0.4_alpha.zip
extract it and add reference to the dll file in your project ( in folder .net 2)
and you can use it like this
first import the library
Imports Google.API.Search
then in a sub or function put your code as
Dim rf As String = "http://www.google.com"
Dim v As New Google.API.Search.GwebSearchClient(rf)
Dim result = v.Search(TextBox1.Text, 40)
' number (40) is the amount of fetched results ( change it if you want )
For Each item In result
If item.Url.Contains("chuckecheese") Then
' your code goes here
End If
Next

VB.NET WebBrowser disable javascript

Is there a way to disable javascript webbrowser in vb.net?
works for me:
Private Function TrimScript(ByVal htmlDocText As String) As String
While htmlDocText.ToLower().IndexOf("<script type=""text/javascript"">") > -1
Dim s_index As Integer = htmlDocText.ToLower().IndexOf("<script type=""text/javascript"">")
Dim e_index As Integer = htmlDocText.ToLower().IndexOf("</script>")
htmlDocText = htmlDocText.Remove(s_index, e_index - s_index)
End While
Return htmlDocText
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(yourUrl)
Dim wb As New WebBrowser
wb.Navigate("")
Do While wb.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Dim script As String = TrimScript(result)
wb.DocumentText = script
End Sub
The short answer is: No.
The slightly longer answer is: No, the web-browser control API does not allow disabling standard browser functionality.
No really...but if you getting that annoying error message that pops up saying a script is running then you can turn the property of the webbrowser's suppress-errors "true"
Which popup message do you want to disable? If it's the alert message, try this, obviously resolving the window or frame object to your particular needs, I’ve just assumed top-level document, but if you need an iframe you can access it using window.frames(0). for the first frame and so on... (re the JavaScript part)... here is some code, assuming WB is your webbrowser control...
WB.Document.parentWindow.execScript "window.alert = function () { };", "JScript"
You must run the above code only after the entire page is done loading, i understand this is very difficult to do (and a full-proof version hasn't been published yet) however I have been doing it (full proof) for some time now, and you can gather hints on how to do this accurately if you read some of my previous answers labelled "webbrowser" and "webbrowser-control", but getting back to the question at hand, if you want to cancel the .confirm JavaScript message, just replace window.alert with window.confirm (of course, qualifying your window. object with the correct object to reach the document hierarchy you are working with). You can also disable the .print method with the above technique and the new IE9 .prompt method as well.
If you want to disable JavaScript entirely, you can use the registry to do this, and you must make the registry change before the webbrowser control loads into memory, and every time you change it (on & off) you must reload the webbrowser control out and into memory (or just restart your application).
The registry key is \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\ - the keyname is 1400 and the value to disable it is 3, and to enable it is 0.
Of course, because there are 5 zones under the Zones key, you need to either change it for the active zone or for all zones to be sure. However, you really don't need to do this if all you want to do si supress js dialog popup messages.
Let me know how you go, and if I can help further.