检查Internet连接

Kis*_*asi 4 vb.net

我需要我的应用程序来检查用户计算机上的互联网连接.如果有,则显示图像,如果没有,则显示不同的图像.这是我用来实现这个的代码:

    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
Run Code Online (Sandbox Code Playgroud)

我决定通过更改我的默认网关在我自己的计算机上测试它(从而使它看起来好像我失去了连接).但我意识到代码仍显示我已连接.所以我认为它只是检查接口的连接 - 在这种情况下,是我与路由器的连接(这是真的,我连接到路由器).

所以,问题是:如何检查用户的PC是否实际连接到互联网?我读过这篇文章使用.NET检查Internet连接的最佳方法是什么?但它在C#中,我不明白.

Tim*_*ter 6

您可以使用此工具将C#转换为VB.NET,反之亦然:

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
Run Code Online (Sandbox Code Playgroud)

顺便提一下,您使用的NetworkInterface.GetIsNetworkAvailable方法检查是否有任何网络连接可用 - 而不是 Internet连接.

如果任何网络接口标记为"up"且不是环回或隧道接口,则认为网络连接可用.