Kismet Agbasi Kismet Agbasi - 8 months ago 54 Question

Check Internet Connectivity

I need my application to check for internet connectivity on my user's computer. If there is, an image is displayed and if there isn't, a different image is displayed. Here's the code I used to get this to work:

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

If NetworkInformation.NetworkInterface.GetIsNetworkAvailable Then
Dim bi1 As New BitmapImage
bi1.UriSource = New Uri("Images\greenbar.png", UriKind.Relative)
Image2.Source = bi1

Dim bi2 As New BitmapImage
bi2.UriSource = New Uri("Images\redbar.png", UriKind.Relative)
Image2.Source = bi2
MessageBox.Show("You must be connected to the internet to use some aspects of this application.")
MessageBox.Show("Please re-establish connection to the Internet and try again, thank you.")

End If
End Sub

I decided to test this on my own computer by changing my default gateway (thereby making it seem as if I lost connection). But I realized that the code still showed that I was connected. So I'm thinking that it's only checking for connectivity of the interface - which in this case, is my connection to the router (which is true, I was connected to the router).

So, the question: How do I check that the user's PC is actually connected to the internet? I read the article Check for Internet connectivity but it's in C# and I don't understand that.


You can use this tool to translate C# to VB.NET or vice-versa:

Public Shared Function CheckForInternetConnection() As Boolean
        Using client = New WebClient()
            Using stream = client.OpenRead("")
                Return True
            End Using
        End Using
        Return False
    End Try
End Function

By the way, the NetworkInterface.GetIsNetworkAvailable method you've used checks whether any network connection is available or not - not Internet Connectivity.

A network connection is considered to be available if any network interface is marked "up" and is not a loopback or tunnel interface.