Kismet Agbasi Kismet Agbasi - 1 month ago 11
Vb.net 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.BeginInit()
bi1.UriSource = New Uri("Images\greenbar.png", UriKind.Relative)
bi1.EndInit()
Image2.Source = bi1

Else
Dim bi2 As New BitmapImage
bi2.BeginInit()
bi2.UriSource = New Uri("Images\redbar.png", UriKind.Relative)
bi2.EndInit()
Image2.Source = bi2
MessageBox.Show("INTERNET CONNECTION NOT DETECTED")
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.")
Me.Close()

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.

Answer

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

Public Shared Function CheckForInternetConnection() As Boolean
    Try
        Using client = New WebClient()
            Using stream = client.OpenRead("http://www.google.com")
                Return True
            End Using
        End Using
    Catch
        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.

Comments