我正在尝试获取用户的外部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
但是我一直收到格式异常,说“ip无效”
答案 0 :(得分: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
答案 1 :(得分: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