vb.net 检查互联网连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8800119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:52:20  来源:igfitidea点击:

Check Internet Connectivity

vb.net

提问by Kismet Agbasi

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 What is the best way to check for Internet connectivity using .NET?but it's in C# and I don't understand that.

那么,问题是:如何检查用户的 PC 是否实际连接到 Internet?我阅读了文章使用 .NET 检查 Internet 连接的最佳方法是什么?但它在 C# 中,我不明白。

回答by Tim Schmelter

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

您可以使用此工具将 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

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

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

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

如果任何网络接口被标记为“up”并且不是环回或隧道接口,则认为网络连接可用。

回答by Jimboy Reyes

Or use this code

或使用此代码

If My.Computer.Network.IsAvailable Then
    MsgBox("Computer is connected.")
Else
    MsgBox("Computer is not connected.")
End If

回答by user3249772

If My.Computer.Network.Ping("www.Google.com") Then
...
End If

回答by Nishad

The following will check network connection availability and Internet connection both :

以下将检查网络连接可用性和 Internet 连接:

If My.Computer.Network.IsAvailable Then

    Try
        If My.Computer.Network.Ping("www.Google.com") Then
            Infolabel.Text = "Computer is connected to the internet"
        Else
            Infolabel.Text = "Computer is not connected to the internet"
        End If
    Catch

    End Try

Else
     Infolabel.Text = "Computer is not connected to the internet"
End If

回答by rubin

You could use this, which should help you out for VB & C# versions:

您可以使用this,它应该可以帮助您解决 VB 和 C# 版本:

Public Function IsConnectionAvailable() As Boolean
    ' Returns True if connection is available
    ' Replace www.yoursite.com with a site that
    ' is guaranteed to be online - perhaps your
    ' corporate site, or microsoft.com
    Dim objUrl As New System.Uri("http://www.google.com/")
    ' Setup WebRequest
    Dim objWebReq As System.Net.WebRequest
    objWebReq = System.Net.WebRequest.Create(objUrl)
    objWebReq.Proxy = Nothing
    Dim objResp As System.Net.WebResponse
    Try
        ' Attempt to get response and return True
        objResp = objWebReq.GetResponse
        objResp.Close()
        objWebReq = Nothing
        Return True
    Catch ex As Exception
        ' Error, exit and return False
        objResp.Close()
        objWebReq = Nothing
        Return False
    End Try
End Function

回答by albin.varghese

Public Function IsConnectionAvailable() As Boolean
    ' Returns True if connection is available 
    ' Replace www.yoursite.com with a site that
    ' is guaranteed to be online - perhaps your 
    ' corporate site, or microsoft.com
    Dim objUrl As New System.Uri("http://www.yoursite.com/")
    ' Setup WebRequest
    Dim objWebReq As System.Net.WebRequest
    objWebReq = System.Net.WebRequest.Create(objUrl)
    Dim objResp As System.Net.WebResponse
    Try
        ' Attempt to get response and return True
        objResp = objWebReq.GetResponse
        objResp.Close()
        objWebReq = Nothing
        Return True
    Catch ex As Exception
        ' Error, exit and return False
        objResp.Close()
        objWebReq = Nothing
        Return False
    End Try


'Here's how you might use this function in your application:

If IsConnectionAvailable() = True Then
    MessageBox.Show("You are online!")
End If