elmonko
elmonko

Reputation: 685

Check Internet Connection vb.net

I am trying to run some vb.net code that indicates if i'm connected to the internet

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

This works fine if I'm connecting to a WiFi signal that doesn't require a login. If I connect to a public WiFi signal that I'm required to login/pay and I execute the code before completing this step it still tells me I'm connected (in theory yes but without paying/logging in I'm not)

Any ideas how set this up?

Thanks

Upvotes: 9

Views: 61512

Answers (10)

AmanAgrawalTech
AmanAgrawalTech

Reputation: 11

    Try
        Dim client = New Net.WebClient
        client.OpenRead("http://www.google.com")
        Label21.Text = "Internet : Connected"
    Catch
        Label21.Text = "Internet : Disconnected"
    End Try

Use this code in vb.net 100% solved, you can use this code form loading.

Upvotes: 1

ibrahim amen
ibrahim amen

Reputation: 31

***** Best ***** The best Code For it, it not make any bug or Any slow.

Button Or Timer .. Etc

    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

At least hope you gave me that "Question Answer", it the best solution .Thanks. (you can try it out)

Upvotes: 1

entoni
entoni

Reputation: 31

My.Computer.Network.Ping gave me problems so I used this function

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

Upvotes: 0

Flash.Developer
Flash.Developer

Reputation: 11

A good way to check if the user is connected to the internet is

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

    MsgBox("Computer is connected to the internet.")

End If

You can also use this code, however it's slower

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

Upvotes: 1

Bob
Bob

Reputation: 9

I am using this code and is working very well:

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

Upvotes: 0

Sergey
Sergey

Reputation: 179

I use this

Public Function HaveInternetConnection() As Boolean

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

End Function

Upvotes: 11

SZL
SZL

Reputation: 855

I create this class to track internet connection changes. This class can check the stable internet connections also (stable means, that the connection not change during N second). The class raise events, if the connection changes.

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

Track changes on a form with 2 listbox. Important! The events are thread unsafe, that need to be handle with invoke method.

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

The result is:

Internet connection changes

I use the stable connection changes.

If you dont want to track changes, only check the connection, you can use the CheckInternetConnectionIsAvailable() shared function.

Upvotes: 4

rubin
rubin

Reputation: 5

or you could use this, a little better function to use. this should help you out if you need a c# version 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

Upvotes: -1

Chris
Chris

Reputation: 5605

You could check for an internet connection by trying to read 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

Taken from: Here

Upvotes: 17

Markus
Markus

Reputation: 22421

You could use the Ping class to try to reach a host in the Internet. In order not to wait too long, you should set a timeout when using Send.

Upvotes: 1

Related Questions