Checking internet connectivity from C#/VB Code

If you have a question like "How to check internet connectivity from C# or VB code ?" than this small article is for you. Enjoy.
In most of the programs we need to check if the internet is working or not or if internet is available or not.
A good news for your guys.
You can now check for internet connectivity from your C# code with few lines of code given below.
Try it and let me know what you think in the comment section below.

Code Snippet
  1. using System;
  2. using System.Runtime;
  3. using System.Runtime.InteropServices;
  4. public class Internet
  5. {
  6.     [DllImport("wininet.dll")]
  7.     private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
  8.     public static bool IsConnectedToInternet()
  9.     {
  10.         int Desc;
  11.         return InternetGetConnectedState(out Desc, 0);
  12.     }
  13. }


Even if you need code in VB for checking internet connectivity than I am just posting below. :-)

Code Snippet
  1. Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef dwflags As Long, ByVal dwReserved As Long) As Long
  2. Private Const CONNECT_LAN As Long = &H2
  3. Private Const CONNECT_MODEM As Long = &H1
  4. Private Const CONNECT_PROXY As Long = &H4
  5. Private Const CONNECT_OFFLINE As Long = &H20
  6. Private Const CONNECT_CONFIGURED As Long = &H40
  7. Private Const CONNECT_RAS As Long = &H10
  8. Public Function IsWebConnected(Optional ByRef ConnType As String = "") As Boolean
  9.     Dim dwflags As Long
  10.     Dim WebTest As Boolean
  11. WebTest = InternetGetConnectedState(dwflags, 0&)
  12.     Select Case WebTest
  13.         Case dwflags And CONNECT_LAN : ConnType = "LAN"
  14.         Case dwflags And CONNECT_MODEM : ConnType = "Modem"
  15.         Case dwflags And CONNECT_PROXY : ConnType = "Proxy"
  16.         Case dwflags And CONNECT_OFFLINE : ConnType = "Offline"
  17.         Case dwflags And CONNECT_CONFIGURED : ConnType = "Configured"
  18.         Case dwflags And CONNECT_RAS : ConnType = "Remote"
  19.     End Select
  20.     IsWebConnected = WebTest
  21. End Function

Post a Comment