2013-05-15 170 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