0

I am writing a program in my computer science class and I have come across an error when trying to obtain the public IPv4 address of the computer.

This is my code:

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

This is then called using this code:

tboxPublicIPv4.Text = GetMyIP().ToString

However, when it tries to write the IPv4 address to the textbox I get this error:

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.

Any help would be appreciated. Thank you.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
IsaSca
  • 23
  • 9

1 Answers1

1

The URL you're calling is redirecting to https, and it seems at least TLS 1.1 is required.

You can enable TLS 1.1 or TLS 1.2 for Net.WebClient by setting the security-protocol with ServicePointManager.SecurityProtocol.

Furthermore you can use DownloadString instead of converting the downloaded data to a string.
I would also wrap it inside a 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 supports up to TLS 1.0 while .NET 4.5 or higher supports up to TLS 1.2
For reference:

MatSnow
  • 7,357
  • 3
  • 19
  • 31
  • I am now getting a System.NullReferenceException with additional info of "Object reference not set to an instance of an object". This occurs at line 36. tboxPublicIPv4.Text = GetmyIP().ToString – IsaSca Oct 18 '17 at 11:41