Check if the Internet Connection State is active

I wrote a small application which uploads Images of new products and therefore I had to check if the Internet Connection State is active, otherwise it would crash. There are actually two ways (and probably more) of doing this, depending on your system. You could go with a direct api call:

        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        //Creating a function that uses the API function...
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }

The Description can be found on MSDN, depending on the Connection the proper Value has to be entered.

Another way would be resolving some host of which you are sure it is online all the time. That could be microsoft.com, your company’s website or something else. Here we go:

        public static bool IsConnected()
        {
            System.Uri Url = new System.Uri("http://www.microsoft.com");

            System.Net.WebRequest WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);            

            try 
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                return true;
            }

            catch
            {                
                WebReq = null;
                return false;
            }
        }

Include one of those functions in your code and you’re set!

14 comments ↓

#1 raja on 12.14.07 at 10:49 am

Good one

#2 Som on 04.18.08 at 2:09 pm

Very GOOD!

#3 Ervin on 07.29.08 at 7:17 am

Thanks. nice one

#4 kamel on 09.24.08 at 12:08 pm

very very nice

#5 michou on 10.08.08 at 2:31 pm

does not seem to work on Silverlight…

#6 Arhan on 10.25.08 at 11:02 am

GOOD!! Thx 🙂

#7 Jitendra Kumar on 10.30.08 at 9:41 pm

Thanx dude. I was looking for last week to solve this problem finally come over this solutions. and worked. thanx

#8 melzaiady on 11.06.08 at 6:45 am

Thank you

#9 Lathwal on 11.18.08 at 8:58 am

Nice one!

#10 Tek on 01.26.09 at 12:37 pm

very Good

But can control(on and off)the internet using c# or java

#11 john on 01.28.09 at 6:50 am

Hello ,
Your coding is very helpful to me dear…….
Thanks a lot……..

#12 jahnny on 02.11.09 at 10:09 pm

Simple and genial.. thanks

#13 Paul on 04.07.10 at 5:18 pm

Thanks! Simple and easy to use.

#14 Anamika on 02.07.12 at 5:56 am

Hi….
Thanks a lot….
Its very usefull to me… Simple & easy to use….

Leave a Comment