Introduction
Hi!! Thanks to all readers for visiting this post. This post could be useful for those who need to check the internet connection before performing some task in their application.
Background
I was working on one project in which I was making a communication to the server each and every time for performing some of the tasks needed by the application. This communication however I was doing with Web service. I took the reference of this web service from my Windows application and was calling the web methods to perform different tasks. However, this application was like a Windows service which automatically needed to make the log on time entry to the server using web method. For this, whenever windows starts, I had to auto login to the server using the internet connection,and for doing so, I needed to check whether the internet is connected over client machine or not, which lead me to find some solution in that direction.
Using the code
The code is so simple. Just Copy & Paste the
class
below in your application, and call the function
IsInternetConnected()
to determine whether the internet is connected or not. Let me explain what actually I am doing here. Here I am referring to an external Windows API function using the
DllImport
. Later on, from my function
IsInternetConnected()
, I am calling that function with sufficient parameters. As the functions return type is boolean, it returns to me whether the internet connected or not. That's all.
However, as this is my first article on CodeProject, maybe my language could be undescriptive. So please forgive me for that. But the code below is easily understandable by any programmer, so I don't think any further explanation is needed for that. With the hope that this article would be useful to my friends, I have put it here.
Imports System
Imports System.Runtime.InteropServices
Imports System.Text
''' <summary>
''' Determine whether or not there is a connection to the Internet present on the local machine.
''' </summary>
''' <remarks></remarks>
Public Class InternetConnectionCheck
<DllImport("WININET", CharSet:=CharSet.Auto)> _
Private Shared Function InternetGetConnectedState_
(ByRef lpdwFlags As InternetConnectionState, ByVal dwReserved As Integer) As Boolean
End Function
<Flags()> _
Public Enum InternetConnectionState As Integer
INTERNET_CONNECTION_MODEM = &H1
INTERNET_CONNECTION_LAN = &H2
INTERNET_CONNECTION_PROXY = &H4
INTERNET_RAS_INSTALLED = &H10
INTERNET_CONNECTION_OFFLINE = &H20
INTERNET_CONNECTION_CONFIGURED = &H40
End Enum
''' <summary>
''' Call this function to know whether the internet is connected or not.
''' </summary>
''' <returns>Boolean</returns>
''' <remarks></remarks>
Public Shared Function IsInternetConnected() As Boolean
Dim flags As InternetConnectionState = 0
Try
If InternetGetConnectedState(flags, 0) Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw ex
Finally
flags = Nothing
End Try
End Function
End Class
History
About the Author
Gandhi Ashish