0

我正在尝试获取用户的外部 IP,以便将其保存到他们的用户文件中。但我找不到任何方法来做到这一点。我试过做:

Private Function getExternalIP() As Net.IPAddress
    Using wc As New Net.WebClient
        Return Net.IPAddress.Parse(Encoding.ASCII.GetString(wc.DownloadData("http://whatismyip.com/automation/n09230945.asp")))
    End Using
End Function

但我不断收到一个 formatException 说“ip 无效”

4

2 回答 2

0

我喜欢使用这个功能。它似乎比使用 API 好得多。我在寻找它时找到了它。它来自这里:

http://www.guideushow.com/code-snippet/get-external-ip-function-vb-net-c/

Function GetExternalIP() As IPAddress
    Dim lol As WebClient = New WebClient()
    Dim str As String = lol.DownloadString("http://www.ip-adress.com/")
    Dim pattern As String = "<h2>My IP address is: (.+)</h2>"
    Dim matches1 As MatchCollection = Regex.Matches(str, pattern)
    Dim ip As String = matches1(0).ToString
    ip = ip.Remove(0, 21)
    ip = ip.Replace("</h2>", "")
    ip = ip.Replace(" ", "")
    Return IPAddress.Parse(ip)
End Function
于 2014-11-28T20:41:30.780 回答
0

这是一些代码,您可能需要添加检查以确保它不会经常运行:

 Private Shared Function GetExternalIP() As String

    Dim Response As String = String.Empty

    Try

        Dim myWebClient As New System.Net.WebClient
        Dim whatIsMyIp As String = "http://automation.whatismyip.com/n09230945.asp"
        Dim file As New System.IO.StreamReader(myWebClient.OpenRead(whatIsMyIp))

        Response = file.ReadToEnd()
        file.Close()
        file.Dispose()
        myWebClient.Dispose()

    Catch ex As Exception
        Response = "Could not confirm External IP Address" & vbCrLf & ex.Message.ToString
    End Try

    Return Response

End Function
于 2013-05-15T11:10:49.760 回答