尝试将 IP 地址写入 Visual Basic 中的文本框

Trying to write IP address to textbox in Visual Basic

我正在尝试编写一个简单的程序来查找正在使用它的计算机的 public IP。但是,我不确定如何将 TextBox 的文本设置为找到的 IP 地址。谁能帮帮我?

代码:

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

首先,你应该使用Option Strict On。那会向您指出您需要使用

TextBox1.Text = GetMyIP().ToString()

接下来,如果您检查该网页中的 headers,您将看到它 returns UTF-8 编码的结果,因此您应该使用 Encoding.UTF8 而不是 Encoding.ASCII。不幸的是,这仍然不起作用 - 我稍后会写更多。

但是,WebClient 有一个 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

(我可以在那里使用 Encoding.ASCII,因为超过 127 的字节已被删除。)