尝试获取IPv4地址时,无法在vb中创建SSL / TLS连接

时间:2017-10-16 11:56:23

标签: vb.net ssl system.net.webexception

我正在计算机科学课上编写程序,在尝试获取计算机的公共IPv4地址时遇到错误。

这是我的代码:

Private Function GetMyIP() As Net.IPAddress
    Using wc As New Net.WebClient

        Return Net.IPAddress.Parse(Encoding.ASCII.GetString(wc.DownloadData("http://tools.feron.it/php/ip.php")))


    End Using
End Function

然后使用此代码调用它:

tboxPublicIPv4.Text = GetMyIP().ToString

但是,当它尝试将IPv4地址写入文本框时,我收到此错误:

An unhandled exception of type 'System.Net.WebException' occurred in System.dll

Additional information: The request was aborted: Could not create SSL/TLS secure channel.

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

您正在呼叫的网址正在重定向到https,似乎至少需要TLS 1.1

您可以通过使用TLS 1.1设置security-protocol来为Net.WebClient启用TLS 1.2ServicePointManager.SecurityProtocol

此外,您可以使用DownloadString而不是将下载的数据转换为字符串。
我也会把它包裹在Try/Catch

Function GetMyIP() As Net.IPAddress
    Using wc As New Net.WebClient
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

        Try
            Return Net.IPAddress.Parse(wc.DownloadString("https://tools.feron.it/php/ip.php"))
        Catch ex As Exception
            Return New Net.IPAddress(0)
        End Try
    End Using
End Function
  

.NET 4.0支持最多TLS 1.0 .NET 4.5或更高   支持最多TLS 1.2
作为参考: