从 Google 获取 IP

Get IP From Google

我正在 vb.net 中编写一个应用程序,它需要 public 纯文本格式的 IP 地址。我知道有很多网站以文本格式为您提供 IP。但是哪里总是有可能关闭或停止服务。但是 Google 永远不会停止!现在我想从 google 搜索中获取我的 ip。例如,如果您在 google 中搜索 "my ip",它会像这样显示您的 ip: Sample of search 无论如何要从 Google 获取 IP?

谢谢你们,但我找到了一个方法: 首先导入一些命名空间:

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)

现在工作生活!

硬编码的 Div Class 名称让我有点紧张,因为它们随时都可以轻松更改,因此,我对 Hirod Behnam 的示例进行了一些扩展。

我删除了 Div Class 模式,将其替换为更简单的 IP 地址搜索,它 return 只有找到的第一个,对于此搜索,应该成为页面上显示的第一个(您的外部 IP)。

这也消除了将结果拆分为数组的需要,以及那些相关的变量。我还将 Google 搜索字符串简化到最低限度。

如果速度至关重要,为 .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