2013-05-15 171 views
0

我试图获取用户的外部IP,以便我可以将其保存到他们的用户文件。但我找不到任何办法。我试着这样做:获取外部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无效”

+2

我们需要知道从什么http://whatismyip.com/automation/n09230945.asp响应样子。 –

+0

这从2012年工作正常,因此评论 - http://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address –

回答

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 
+0

我在中间窗口得到这个“第一次机会例外在System.dll中发生类型“System.Net.WebException”,并在用户文件中出现“无法确认外部IP地址 远程名称无法解析:'automation.whatismyip.com'” – Programming16

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