2013-10-29 123 views
4

我試圖運行一些vb.net代碼,表明如果我連接到互聯網檢查Internet連接vb.net

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

這工作得很好,如果我連接到一個沒有按WiFi信號不需要登錄。如果我連接到需要登錄/付費的公共WiFi信號,並在完成此步驟之前執行代碼,它仍會告訴我我已連接(理論上是,但沒有付費/登錄我不是)

任何想法如何設置?

感謝

+1

你應該首先確定你所使用的具體標準「計算機連接」;你應該能夠ping一些遠程目的地嗎?你應該能夠在某個地方建立一個標準的http/https連接嗎?還有其他交通需要檢查嗎? – admdrew

+0

要連接,我應該能夠ping任何頁面,發送電子郵件形式的項目或確實做任何標準連接。問題是,即使我無法執行任何以前的操作,擁有登錄頁面的WIFI連接仍然會給我一個「連接」對話框。我也嘗試了其他代碼,基本上對特定網頁提出請求,這些代碼仍然會給出誤報。謝謝 – elmonko

+0

Ping到一箇中心位置將是一個體面的初始測試(可能是一個谷歌網絡服務器,或他們的DNS服務器之一)。 – admdrew

回答

12

您可以通過嘗試讀取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

1

您可以使用Ping類力爭達到在互聯網的主機。爲了不要等太久,在使用發送時應該設置一個超時時間。

0

進行檢查因特佳碼器是否

「** *******************************************

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

    MsgBox("Computer is connected.") 

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 

錯誤代碼檢查Internet連接 這段代碼CON不檢查Internet連接或斷開

' dont use this code for check internet is connected or not connected 
If My.Computer.Network.IsAvailable Then 

    MsgBox("Computer is connected.") 
Else 

    MsgBox("Computer is not connected.") 
End If 
-1

,或者你可以用這一點,使用功能稍好一些。這會幫助你,如果你需要一個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 
2

我創建這個類來追蹤互聯網連接的變化。這個班級也可以檢查穩定的互聯網連接(穩定的意思是,連接在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列表框的窗體上跟蹤更改。重要!事件是線程不安全的,需要使用invoke方法處理。

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 

結果是:

Internet connection changes

我用的是穩定連接的變化。

如果您不想跟蹤更改,只檢查連接,則可以使用CheckInternetConnectionIsAvailable()共享函數。

6

我用這個

Public Function HaveInternetConnection() As Boolean 

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

End Function 
+1

由於谷歌地址中的拼寫錯誤,看起來像是有負面投票。修復。 – Sergey

0

我使用此代碼,並運行良好:

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