Get IP From Google - vb.net

I'm writing an app in vb.net that needs public IP address in text only format. I'd knew there is lots of site that give you your IP in text format. But where is always a chance of being closed or getting out of service. But the Google will not ever stop! Now I want to get my ip from google searching. For example if you search "my ip" in google it will bring your ip like this:
Sample of search
Is anyway to get IP from Google?

Thanks guys but I found a way:
At first import some namespaces:
Imports System.Net
Imports System.Text.RegularExpressions
Now lets write a function:
Dim client As New WebClient
Dim To_Match As String = "<div class=""_h4c _rGd vk_h"">(.*)"
Dim recived As String = client.DownloadString("https://www.google.com/search?sclient=psy-ab&site=&source=hp&btnG=Search&q=my+ip")
Dim m As Match = Regex.Match(recived, To_Match)
Dim text_with_divs As String = m.Groups(1).Value
Dim finalize As String() = text_with_divs.Split("<")
Return finalize(0)
It's now working and live!

Hard-coded Div Class names make me a bit nervous because they can easily change at any time, so, I expanded on Hirod Behnam's example a little bit.
I removed the Div Class pattern, replacing it with a simpler IP address search, and it'll return only the first one found, which for this search, should be the first one shown on the page (your external IP).
That also removed the need for splitting the results into the array, and those related vars. I also simplified the Google search string to the bare minimum.
It'd still probably be a nice touch to include a timeout or two for the .DownloadString() and the .Match() respectively, if speed is of the essence.
Private Function GetExternalIP() As String
Dim m As Match = Match.Empty
Try
Dim wClient As New System.Net.WebClient
Dim strURL As String = wClient.DownloadString("https://www.google.com/search?q=my+ip")
Dim strPattern As String = "\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b"
' Look for the IP
m = Regex.Match(strURL, strPattern)
Catch ex As Exception
Debug.WriteLine(String.Format("GetExternalIP Error: {0}", ex.Message))
End Try
' Failed getting the IP
If m.Success = False Then Return "IP: N/A"
' Got the IP
Return m.value
End Function

Related

vb.net TCP where dose my faulty URL request go and where can I (if I can) find it?

I have a simple TCP/IP HTML server. To access this HTML server the user needs to type the IP address of the machine the HTML server is running on also, if the user types a faulty URL as long as it starts with the correct IP-address followed by a forward slash (example: 123.456.789.0/FaultyText) it also works.
My understanding is that if I type in a web browsers address bar it broadcasts that text-string till some server says "hey I recognize this, let me react upon it" meaning (according to my understanding) the opposite is also true if a text-string is broadcast which the server does not recognize it says "This I cannot identify, I'll pass reacting upon it". This would mean the text-string must always be read to know it's at the right destination or not.
So how come if I type something random in the URL address bar, the following code snippet won't reference to it in its HTTP headers Host:, or Refrence: sections (or anywhere else for that matter of fact)?
#Region "Start Server"
Dim MyIp As String
Dim MyPort As String
Try
'If Not MyNetworkPortBase64Plain = Nothing Then
' MyIp = MyNetworkIpBase64Plain
'Else
' Dim MyComputerName As String = Dns.GetHostName()
' MyIp = Dns.GetHostByName(MyComputerName).AddressList(0).ToString()
'End If
If Not MyNetworkPortBase64Plain = Nothing Then
MyPort = MyNetworkPortBase64Plain
Else
MyPort = "8080"
End If
MyIp = (IPAddress.Any).ToString
MyHtmlServer = New TcpListener(IPAddress.Parse(MyIp), MyPort)
MyHtmlServer.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf MyNewClientSub)
#Region "Server Start/ Stop Button"
#Region "Get/ Collect Incoming Bytes"
Dim MyNetworkStream As NetworkStream = MyClient.GetStream()
Dim MyReceivingBytes(100000) As Byte
MyNetworkStream.Read(MyReceivingBytes, 0, MyReceivingBytes.Length)
Dim MyIncommingRequests As String = Encoding.ASCII.GetString(MyReceivingBytes)
Dim webClient As New System.Net.WebClient
MsgBox(MyIncommingRequests)
#End Region
How can I catch all the URL requests made?

Google searching URL and add Listbox C# vb.net

i want to using webrequest codes then adding google search result URL's listbox1. But i can't codes gives error.
Try
Dim adres As String = "https://www.google.com/search?q=" + TextBox1.Text
Dim istek As WebRequest = HttpWebRequest.Create(adres)
Dim cevap As WebResponse
cevap = istek.GetResponse()
Dim donenBilgiler As StreamReader = New StreamReader(cevap.GetResponseStream())
Dim gelen As String = donenBilgiler.ReadToEnd()
Dim titleIndexBaslangici As Integer = gelen.IndexOf("<link href") + 2
Dim titleIndexBitisi As Integer = gelen.Substring(titleIndexBaslangici).IndexOf(">")
ListBox1.Items.Add(gelen.Substring(titleIndexBaslangici, titleIndexBitisi))
Catch ex As Exception
MsgBox(ex.Message)
End Try
First, are you familliar with API, because that's what you need ! You might work this out with the way you want to make it but its really bad and no one will recommend you to continue like this!
What you need to look for is API, (google search API)! API "only" purpose is to access to some data (in database) with easy Http route (well documented), try it out!
If you keep trying to do it in your own way, the best result that you will get is a really bad html page that you will need to parse and you don't want that !

LDAP Vb.net simple query

I'm trying to create a vb.net code for a simple query through LDAP but having an issue and can't find where it is.
Dim ldapServerName As String = "xxx.test.intranet.xxx.ca"
Dim oRoot As DirectoryEntry = New DirectoryEntry("LDAP://" & ldapServerName & "/c=ca, DC=xxx,DC=corp,DC=xxx,DC=ca")
oRoot.Username = "ou=Tool,ou=applications,o=xxx,c=ca"
oRoot.Password = "something#2015"
Dim LDAPSearcher As New DirectorySearcher()
LDAPSearcher.Filter = "(&(employeenumber=6012589))"
Dim SearchResult As SearchResult = LDAPSearcher.FindOne()
Dim UserEntry As DirectoryEntry = SearchResult.GetDirectoryEntry()
EDTEST.Text = UserEntry.Properties("employeenumber").Value.ToString
it is giving me an error saying that the object is not valid. The searcher variable is in fact empty so it has to do with my query somehow.
This is my first time with LDAP¨and I have tried some of the solution i could find on the net but nothing is working so far.
Error: Object not set to an instance of an object.
Unless you're adding another attribute to search by, you don't need the AND operator in your filter syntax - a search for simply (employeenumber=6012589) should work just fine.
If do you have another attribute you'd like to search by, the filter syntax would be similiar to what you have now, only with the additional attribute :
(&(employeenumber=6012589)(objectClass=user))
EDIT:
I put together an example using the lower level System.DirectoryServices and System.DirectoryServices.Protocols namespaces. This helps break up the actual login and search functions, and will also provide better context when errors occur. For the example, I've replaced all of my variables with the ones you're using in your question. I tested this against our own Active Directory instance over unsecured port 389 using my creds and a base domain similar to the one you're using.
Imports System.DirectoryServices.Protocols
Imports System.Net
Module Module1
Sub Main()
' setup your creds, domain, and ldap prop array
Dim username As String = "ou=Tool,ou=applications,o=xxx,c=ca"
Dim pwd As String = "something#2015"
Dim domain As String = "DC=xxx,DC=corp,DC=xxx,DC=ca"
Dim propArray() As String = {"employeenumber"}
' setup your ldap connection, and domain component
Dim ldapCon As LdapConnection = New LdapConnection("xxx.test.intranet.xxx.ca:389")
Dim networkCreds As NetworkCredential = New NetworkCredential(username, pwd, domain)
' configure the connection and bind
ldapCon.AuthType = AuthType.Negotiate
ldapCon.Bind(networkCreds)
' if the above succceeded, you should now be able to issue search requests directly against the directory
Dim searchRequest = New SearchRequest(domain, "(employeenumber=6012589)", SearchScope.Subtree, propArray)
' issue the search request, and check the results
Dim searchResult As SearchResponse = ldapCon.SendRequest(searchRequest)
Dim searchResultEntry As SearchResultEntry
If (searchResult.Entries.Count > 0) Then ' we know we've located at least one match from the search
' if you're only expecting to get one entry back, get the first item off the entries list
searchResultEntry = searchResult.Entries.Item(0)
' continue to do whatever processing you wish against the returned SearchResultEntry
End If
End Sub
End Module

Creating a cross domain web service

So, I am very new to creating web services, but have successfully managed to make a simple webservice which returns information as I'd need from a database as List(Of dictionary(of string, string)) object.
For the purpose of testing, I have created this manually, my code looks like this:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Serialization
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class test
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function dic() As String
Dim newDic As New List(Of Dictionary(Of String, String))
Dim one As New Dictionary(Of String, String)
one.Add("id", "1")
one.Add("name", "the name")
one.Add("price", "5.99")
newDic.Add(one)
Dim two As New Dictionary(Of String, String)
two.Add("id", "2")
two.Add("name", "item name two")
two.Add("price", "1299")
newDic.Add(two)
Dim s As New JavaScriptSerializer
Dim str As String = s.Serialize(newDic)
Return str
End Function
End Class
This webservice "dic" gives me serialized string/list looking like this:
[{"id":"1","name":"the name","price":"5.99"},{"id":"2","name":"item name two","price":"1299"}]
I can read this in VB code like this:
Sub loadMe() Handles Me.Load
Dim t As New websvce.testSoapClient
Dim d As String = t.dic
Dim s As New JavaScriptSerializer
Dim d2 = s.DeserializeObject(d)
Response.Write(d2(1)("name") & "<hr>")
End Sub
which gives me the output of the "name" element with index "1". It works fine.
However, unsurprisingly, it does not work when trying to grab this info with jQuery using code as follows:
$(document).ready(function () {
$.getJSON('URL/test.asmx/dic', function (data) {
alert(data);
});
});
So I have spent a good part of the day Googling this, and found all kinds of comments and conversations telling me about why cross domain scripting is not allowed and that there are ways round it using Proxies, adding headers to pages and so on... but... no conclusive solution to the problem.
Here's some of the SO questions I have found:
Origin http://localhost is not allowed by Access-Control-Allow-Origin
How to implement "Access-Control-Allow-Origin" header in asp.net
There's many more, but I cannot find an absolute solution, which fits my criteria. I want to output data in a format similar to that above, and access it from another domain with jQuery.
The easiest work around I have found is to write a handling page which runs on the receiving server, simply loading the data as per my VB code example above and operating as a webMethod on that server to spit out JSON, but I'd rather the whole thing could be handling by the web service, thus no need to run extra files on the consuming server.
EDIT; actually, I do also need to be able to perform POST operations.

How to Post & Retrieve Data from Website

I am working with a Windows form application. I have a textbox called "tbPhoneNumber" which contains a phone number.
I want to go on the website http://canada411.com and enter in the number that was in my textbox, into the website textbox ID: "c411PeopleReverseWhat" and then somehow send a click on "Find" (which is an input belonging to class "c411ButtonImg").
After that, I want to retrieve what is in between the asterixs of the following HTML section:
<div id="contact" class="vcard">
<span><h1 class="fn c411ListedName">**Full Name**</h1></span>
<span class="c411Phone">**(###)-###-####**</span>
<span class="c411Address">**Address**</span>
<span class="adr">
<span class="locality">**City**</span>
<span class="region">**Province**</span>
<span class="postal-code">**L#L#L#**</span>
</span>
So basically I am trying to send data into an input box, click the input button and store the values retrieved into variables. I want to do this seemlessly so I would need to do something like an HTTPWebRequest? Or do I use a WebBrowser object? I just don't want the user to see that the application is going on a website.
I do a good amount of website scraping and I will show you how I do it. Feel free to skip ahead if I am being too specific, but this is a commonly requested theme and should be made specific.
URL Simplification
The library I use for this is htmlagilitypack (It is a dll, make a new project and add a reference to it). The first thing to check is if we have to go to take any special steps to get to a page by using a phone number. I searched for John Smith and found quite a few. I entered 2 of these results and noticed that the url formatting is very simple. Those results were..
http://www.canada411.ca/res/7056736767/John-Smith/138223109.html
http://www.canada411.ca/res/7052355273/John-Smith/172439951.html
I tested to see if I can remove some of the values from the url that I don't know and just leave the phone number. The result was that I can...
http://www.canada411.ca/search/re/1/7056736767/-
http://www.canada411.ca/search/re/1/7052355273/-
You can see by the url that there are some static areas in the url and our phone number. From this lets construct a string for the url.
Dim phoneNumber as string = "7056736767" 'this could be TextBox1.Text or whatever
Dim URL as string = "http://www.canada411.ca/search/re/1/" + phoneNumber +"/-"
Value Extraction with XPath
Now that we have the page dialed in, lets examine the html you provided above. You need 6 values from the page so we will create them now...
Dim FullName As String
Dim Phone As String
Dim Address As String
Dim Locality As String
Dim Region As String
Dim PostalCode As String
As mentioned above, we will be using htmlagilitypack which uses Xpath. The cool thing about this is that once we can find some unique identifier in the html, we can use Xpath to find our values. I know it may be confusing, but it will become clearer.
All of the values you need are within tags that have a class name. Lets use the class name in our Xpath to find them.
Dim FullNameXPath As String = "//*[#class='fn c411ListedName']"
Dim PhoneXPath As String = "//*[#class='c411Phone']"
Dim AddressXPath As String = "//*[#class='c411Address']"
Dim LocalityXPath As String = "//*[#class='locality']"
Dim RegionXPath As String = "//*[#class='region']"
Dim PostalCodeXPath As String = "//*[#class='postal-code']"
Essentially what we are looking at is a string that will inform htmlagilitypack what to look for. In our case, text contained within the classes we named. There is a lot to XPath and it could take a while to explain all of it. On a side note though...If you use Google Chrome and highlight a value on a page, you can right click inspect element. In the code that appears below, you can right click the value and copy to XPath!!! Very useful.
Basic HTMLAgilityPack Template
Now, all that is left is to connect to the page and get those variables populated.
Dim Web As New HtmlAgilityPack.HtmlWeb
Dim Doc As New HtmlAgilityPack.HtmlDocument
Doc = Web.Load(URL)
For Each nameResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(FullNameXPath)
Msgbox(nameResult.InnerText)
Next
In the above example we create an HtmlWeb object named Web. This is the actual crawler of our project. We then define a HtmlDocument which will consist of our converted and searchable page source. All of this is done behind the scenes. We then send Web to get the page source and assign it to the Doc object we created. Doc is reusable, which thankfully requires us to connect to the page only once.
The for loop looks for any nodes in our Doc that match FullNameXPath which was defined previously as the XPath value for finding the name. When a Node is found, it is assigned to the nameResult variable and from within the loop we call a message box to display the inner text of our node.
So when we put it all together
Complete Working Code (As of 2/17/2013)
Dim phoneNumber As String = "7056736767" 'this could be TextBox1.Text or whatever
Dim URL As String = "http://www.canada411.ca/search/re/1/" + phoneNumber + "/-"
Dim FullName As String
Dim Phone As String
Dim Address As String
Dim Locality As String
Dim Region As String
Dim PostalCode As String
Dim FullNameXPath As String = "//*[#class='fn c411ListedName']"
Dim PhoneXPath As String = "//*[#class='c411Phone']"
Dim AddressXPath As String = "//*[#class='c411Address']"
Dim LocalityXPath As String = "//*[#class='locality']"
Dim RegionXPath As String = "//*[#class='region']"
Dim PostalCodeXPath As String = "//*[#class='postal-code']"
Dim Web As New HtmlAgilityPack.HtmlWeb
Dim Doc As New HtmlAgilityPack.HtmlDocument
Doc = Web.Load(URL)
For Each nameResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(FullNameXPath)
FullName = nameResult.InnerText
MsgBox(FullName)
Next
For Each PhoneResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(PhoneXPath)
Phone = PhoneResult.InnerText
MsgBox(Phone)
Next
For Each ADDRResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(AddressXPath)
Address = ADDRResult.InnerText
MsgBox(Address)
Next
For Each LocalResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(LocalityXPath)
Locality = LocalResult.InnerText
MsgBox(Locality)
Next
For Each RegionResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(RegionXPath)
Region = RegionResult.InnerText
MsgBox(Region)
Next
For Each postalCodeResult As HtmlAgilityPack.HtmlNode In Doc.DocumentNode.SelectNodes(PostalCodeXPath)
PostalCode = postalCodeResult.InnerText
MsgBox(PostalCode)
Next
Yes it is possible, I've done this using the selenium framework, which is aimed for testing automation. However, it provides you with the tools to do exactly that.
Download for .net here:
http://docs.seleniumhq.org/download/