2016-11-14 31 views
0

我正在嘗試編寫一個簡單的程序來查找正在使用的計算機的公共IP。但是,我不確定如何將TextBox的文本設置爲找到的IP地址。誰能幫我?試圖將IP地址寫入到Visual Basic中的文本框中

代碼:

Imports System.Net 
Imports System.Text 
Imports System.Text.RegularExpressions 
Public Class Form1 
    Private Function GetMyIP() As IPAddress 
     Using wc As New WebClient 
      Return IPAddress.Parse(Encoding.ASCII.GetString(wc.DownloadData("http://tools.feron.it/php/ip.php"))) 

     End Using 
    End Function 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     TextBox1.Text = (GetMyIP()) 
    End Sub 

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) 

    End Sub 
End Class 

回答

0

首先,你應該使用Option Strict On。這會向你指出,你需要使用

TextBox1.Text = GetMyIP().ToString() 

接下來,如果檢查從該網頁的標題,你會看到它返回結果在UTF-8編碼,所以你應該使用Encoding.UTF8代替 。不幸的是,這仍然行不通 - 稍後我會再寫更多。

然而,Web客戶端有一個DownloadString method在這種情況下工作良好:

Private Function GetMyIP() As IPAddress 
    Using wc As New WebClient 
     Dim url = "http://tools.feron.it/php/ip.php" 
     Dim x = wc.DownloadString(url) 
     Return IPAddress.Parse(x.Trim()) 
    End Using 

End Function 

如果你仍然想使用DownloadData,你應該檢查返回的字節:你會發現你想要的數據是前面是字節0xEF 0xBB 0xBF。我不知道爲什麼。這是搞亂你想要的字符串,如果你下載它作爲一個字節數組。

你可以使用LINQ刪除怪字節:

Private Function GetMyIP() As IPAddress 
    Using wc As New WebClient 
     Dim url = "http://tools.feron.it/php/ip.php" 
     Dim x = wc.DownloadData(url) 
     Dim y = Encoding.UTF8.GetString(x.Where(Function(b) b < 128).ToArray()) 
     Return IPAddress.Parse(y) 
    End Using 

End Function 

(因爲超過127字節已被刪除,我可以在那裏使用)

+0

非常感謝您對這個迴應,我發現了一個稍微簡單的編碼方式,但這是一種非常明智的方式。非常感謝您的寶貴時間 :)。 – IsaSca

相關問題