【问题标题】:Check Internet Connection vb.net检查 Internet 连接 vb.net
【发布时间】:2013-10-29 21:12:59
【问题描述】:

我正在尝试运行一些指示我是否已连接到互联网的 vb.net 代码

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

如果我连接到不需要登录的 WiFi 信号,这可以正常工作。如果我连接到需要登录/付款的公共 WiFi 信号,并且在完成此步骤之前执行代码,它仍然告诉我我已连接(理论上可以,但没有付款/登录我没有)

任何想法如何设置?

谢谢

【问题讨论】:

  • 您应该首先定义“计算机已连接”的具体标准;你应该能够ping一些远程目的地吗?您应该能够在某处建立标准的 http/https 连接吗?您还需要检查其他流量吗?
  • 要连接然后我应该能够ping任何页面,发送项目的电子邮件或确实进行任何标准连接。问题是具有登录页面的 WIFI 连接仍然给我一个“已连接”对话框,即使我无法执行之前的任何操作。我还尝试了其他基本上向特定网页发出请求的代码,但这些代码仍然会产生误报。谢谢
  • Ping 到一个中心位置将是一个不错的初始测试(可能是 Google 网络服务器,或者他们的 DNS 服务器之一)。

标签: vb.net


【解决方案1】:

我用这个

Public Function HaveInternetConnection() As Boolean

    Try
        Return My.Computer.Network.Ping("www.google.com")
    Catch
        Return False
    End Try

End Function

【讨论】:

  • 看起来由于 Google 地址拼写错误而投了反对票。修好了。
【解决方案2】:

您可以通过尝试阅读 Google.com 来检查互联网连接:

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

取自:Here

【讨论】:

    【解决方案3】:

    ***** 最好的 ***** 最好的代码,它不会产生任何错误或任何缓慢。

    按钮或定时器..等

        Try
    
            If My.Computer.Network.Ping("www.google.com") Then
    
                Label1.Text = "Internet Founded"
            End If
    
        Catch ex As Exception
    
       '' Else ''
    
                Label1.Text = "No internet Acess"
        End Try
    

    至少希望你给了我那个 “问题答案”,它是最好的解决方案。谢谢。 (你可以试试)

    【讨论】:

      【解决方案4】:
          Try
              Dim client = New Net.WebClient
              client.OpenRead("http://www.google.com")
              Label21.Text = "Internet : Connected"
          Catch
              Label21.Text = "Internet : Disconnected"
          End Try
      

      在vb.net中使用此代码100%解决,可以使用此代码表单加载。

      【讨论】:

        【解决方案5】:

        检查用户是否连接到互联网的好方法是

        If My.Computer.Network.Ping("www.google.com") Then
        
            MsgBox("Computer is connected to the internet.")
        
        End If
        

        您也可以使用此代码,但速度较慢

        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
        

        【讨论】:

          【解决方案6】:

          我正在使用此代码并且运行良好:

          Public Function IsConnectedToInternet() As Boolean
              If My.Computer.Network.IsAvailable Then
                  Try
                      Dim IPHost As IPHostEntry = Dns.GetHostEntry("www.google.com")
                      Return True
                  Catch
                      Return False
                  End Try
              Else
                  Return False
              End If
          End Function
          

          【讨论】:

            【解决方案7】:

            我创建这个类来跟踪互联网连接的变化。此类还可以检查稳定的互联网连接(稳定意味着在 N 秒内连接不会改变)。如果连接发生变化,该类会引发事件。

            Imports System.IO
            Imports System.Runtime.InteropServices
            Imports System.Runtime.InteropServices.ComTypes
            Imports System.Text
            Imports System.Collections.Generic
            Imports System.Linq
            Imports System.Net.NetworkInformation
            Imports System.Net
            
            Public Enum InternetConnectionState
                Connected
                Disconnected
            End Enum
            
            Public Class NetworkConnections
                Implements IDisposable
            
                Public Shared Property CheckHostName As String = "www.google.com"
                Public Property ConnectionStableAfterSec As Integer = 10
            
                Private MonitoringStarted As Boolean = False
                Private StableCheckTimer As System.Threading.Timer
                Private IsFirstCheck As Boolean = True
                Private wConnectionIsStable As Boolean
                Private PrevInternetConnectionState As InternetConnectionState = InternetConnectionState.Disconnected
            
                Public Event InternetConnectionStateChanged(ByVal ConnectionState As InternetConnectionState)
                Public Event InternetConnectionStableChanged(ByVal IsStable As Boolean, ByVal ConnectionState As InternetConnectionState)
            
                Public Sub StartMonitoring()
                    If MonitoringStarted = False Then
                        AddHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
                        MonitoringStarted = True
                        NetworkAddressChanged(Me, Nothing)
                    End If
                End Sub
            
                Public Sub StopMonitoring()
                    If MonitoringStarted = True Then
                        Try
                            RemoveHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
                        Catch ex As Exception
                        End Try
            
                        MonitoringStarted = False
                    End If
                End Sub
            
                Public ReadOnly Property ConnectionIsStableNow As Boolean
                    Get
                        Return wConnectionIsStable
                    End Get
                End Property
            
                <DllImport("wininet.dll")> _
                Private Shared Function InternetGetConnectedState(ByRef Description As Integer, ByVal ReservedValue As Integer) As Boolean
                End Function
            
                Private Shared Function IsInternetAvailable() As Boolean
                    Try
                        Dim ConnDesc As Integer
                        Dim conn As Boolean = InternetGetConnectedState(ConnDesc, 0)
                        Return conn
                    Catch
                        Return False
                    End Try
                End Function
            
                Private Shared Function IsInternetAvailableByDns() As Boolean
                    Try
                        Dim iheObj As IPHostEntry = Dns.GetHostEntry(CheckHostName)
                        Return True
                    Catch
                        Return False
                    End Try
                End Function
            
                Public Shared Function CheckInternetConnectionIsAvailable() As Boolean
                    Return IsInternetAvailable() And IsInternetAvailableByDns()
                End Function
            
                Private Sub NetworkAddressChanged(sender As Object, e As EventArgs)
                    wConnectionIsStable = False
                    StableCheckTimer = New System.Threading.Timer(AddressOf ElapsedAndStable, Nothing, New TimeSpan(0, 0, ConnectionStableAfterSec), New TimeSpan(1, 0, 0))
            
                    If IsFirstCheck Then
                        If CheckInternetConnectionIsAvailable() Then
                            PrevInternetConnectionState = InternetConnectionState.Connected
                            RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Connected)
                        Else
                            PrevInternetConnectionState = InternetConnectionState.Disconnected
                            RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Disconnected)
                        End If
            
                        IsFirstCheck = False
                    Else
                        If CheckInternetConnectionIsAvailable() Then
                            If PrevInternetConnectionState <> InternetConnectionState.Connected Then
                                PrevInternetConnectionState = InternetConnectionState.Connected
                                RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Connected)
                            End If
                        Else
                            If PrevInternetConnectionState <> InternetConnectionState.Disconnected Then
                                PrevInternetConnectionState = InternetConnectionState.Disconnected
                                RaiseEvent InternetConnectionStateChanged(InternetConnectionState.Disconnected)
                            End If
                        End If
                    End If
                End Sub
            
                Private Sub ElapsedAndStable()
                    If wConnectionIsStable = False Then
                        wConnectionIsStable = True
                        Dim hasnet As Boolean = CheckInternetConnectionIsAvailable()
                        RaiseEvent InternetConnectionStableChanged(True, IIf(hasnet, InternetConnectionState.Connected, InternetConnectionState.Disconnected))
                    End If
                End Sub
            
            #Region "IDisposable Support"
                Private disposedValue As Boolean ' To detect redundant calls
            
                ' IDisposable
                Protected Overridable Sub Dispose(disposing As Boolean)
                    If Not Me.disposedValue Then
                        If disposing Then
                            Try
                                RemoveHandler NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
                            Catch ex As Exception
                            End Try
                        End If
            
                        ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
                        ' TODO: set large fields to null.
                    End If
                    Me.disposedValue = True
                End Sub
            
                ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
                'Protected Overrides Sub Finalize()
                '    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
                '    Dispose(False)
                '    MyBase.Finalize()
                'End Sub
            
                ' This code added by Visual Basic to correctly implement the disposable pattern.
                Public Sub Dispose() Implements IDisposable.Dispose
                    ' Do not change this code.  Put cleanup code in Dispose(disposing As Boolean) above.
                    Dispose(True)
                    GC.SuppressFinalize(Me)
                End Sub
            
            #End Region
            
            End Class
            

            跟踪具有 2 个列表框的表单上的更改。重要的!这些事件是线程不安全的,需要使用调用方法来处理。

            Imports System.Net.NetworkInformation
            Imports System.Net
            
            Public Class frmNetworkConnections
            
                Private WithEvents conn As NetworkConnections
                Delegate Sub AddToList1Callback(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
                Delegate Sub AddToList2Callback(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
            
                Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
                    conn = New NetworkConnections
                End Sub
            
                Sub AddToList1(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
                    If Me.InvokeRequired = True Then
                        Dim d As New AddToList1Callback(AddressOf AddToList1)
                        Me.Invoke(d, ConnectionState, IsStable)
                    Else
                        ListBox1.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
                    End If
                End Sub
            
                Sub AddToList2(ByVal ConnectionState As InternetConnectionState, ByVal IsStable As Boolean)
                    If Me.InvokeRequired = True Then
                        Dim d As New AddToList2Callback(AddressOf AddToList2)
                        Me.Invoke(d, ConnectionState, IsStable)
                    Else
                        ListBox1.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
                        ListBox2.Items.Add(Now & " - State: " & ConnectionState.ToString() & ", Stable: " & IsStable)
                    End If
                End Sub
            
                Private Sub conn_InternetConnectionStableChanged(IsStable As Boolean, ConnectionState As InternetConnectionState) Handles conn.InternetConnectionStableChanged
                    AddToList2(ConnectionState, IsStable)
                End Sub
            
                Private Sub conn_InternetConnectionStateChanged(ConnectionState As InternetConnectionState) Handles conn.InternetConnectionStateChanged
                    AddToList1(ConnectionState, False)
                End Sub
            
                Private Sub btnStartMonitoring_Click(sender As Object, e As EventArgs) Handles btnStartMonitoring.Click
                    btnStopMonitoring.Enabled = True
                    btnStartMonitoring.Enabled = False
            
                    conn.StartMonitoring()
                End Sub
            
                Private Sub btnStopMonitoring_Click(sender As Object, e As EventArgs) Handles btnStopMonitoring.Click
                    btnStopMonitoring.Enabled = False
                    btnStartMonitoring.Enabled = True
            
                    conn.StopMonitoring()
                End Sub
            
            End Class
            

            结果是:

            我使用稳定的连接更改。

            如果不想跟踪变化,只检查连接,可以使用CheckInternetConnectionIsAvailable()共享函数。

            【讨论】:

              【解决方案8】:

              或者你可以使用这个,使用更好的功能。如果您需要 c# 版本,这应该可以帮助您 http://www.guideushow.com/code-snippet/function-to-check-if-you-can-connect-to-the-internet-vb-net-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
              

              【讨论】:

                【解决方案9】:

                您可以使用Ping 类尝试访问 Internet 中的主机。为了不等待太久,在使用发送的时候应该设置一个超时时间。

                【讨论】:

                  【解决方案10】:

                  My.Computer.Network.Ping 给我出了问题,所以我使用了这个功能

                  Public Function fVerificaConnessioneInternet() As Boolean
                  
                          Dim objPing As New System.Net.NetworkInformation.Ping
                  
                          Try
                              Return If(objPing.Send("www.google.it").Status = IPStatus.Success, True, False)
                          Catch
                              Return False
                          End Try
                  
                      End Function
                  

                  【讨论】:

                    猜你喜欢
                    • 2023-03-31
                    • 2018-10-09
                    • 2015-11-18
                    • 2015-02-23
                    • 2020-02-05
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-12-01
                    相关资源
                    最近更新 更多