2016-02-21 100 views
0

我正在寫一個應用程序在vb.net需要公共IP地址的文本格式。我知道有很多網站以文本格式爲您提供IP。但哪裏總是有機會被關閉或停止服務。但Google永遠不會停止!現在我想從谷歌搜索中獲取我的IP。例如,如果你在谷歌搜索「我的IP」,它會帶來你的IP這樣的: Sample of search 無論如何,從谷歌獲得IP?從谷歌獲取IP

回答

1

謝謝你們,但我找到了一種方法: 在第一個導入一些命名空間:

Imports System.Net 
Imports System.Text.RegularExpressions 

現在,讓我們寫一個函數:

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) 

它現在的工作和生活!

0

硬編碼Div類名稱讓我有點緊張,因爲它們隨時都可以輕鬆更改,所以我稍微擴展了Hirod Behnam的例子。

我刪除了Div類模式,用簡單的IP地址搜索代替它,它將只返回找到的第一個,對於此搜索,它應該是頁面上顯示的第一個(您的外部IP) 。

這也消除了將結果拆分成數組和相關變量的需要。我也簡化了谷歌搜索字符串到最低限度。

如果速度至關重要,那麼爲.DownloadString()和.Match()分別包含一個或兩個超時值可能還是很不錯的。

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