Link to home
Start Free TrialLog in
Avatar of UdiRaz
UdiRaz

asked on

How to check an internet connection?

Hi,

I would like the popup a window with a web browser in it and to navigate to a url only if there is an internet connection.

How do I check it?

Thanks
Avatar of josgood
josgood
Flag of United States of America image

Someone else may have a better idea, but one way would be to attempt to open a connection to a URL that you know exists.  MFC contains CSocket which should allow you to do this.  Caveat: I'm not an MFC expert.

This seems a useful link
http://tangentsoft.net/wskfaq/examples/basics/
This seems to be working for me...I didn't try unplugging my internet connection.

#include "afxsock.h"
#include <iostream>

int main() {
   CSocket sock;
   try {
      sock.Connect("https://www.experts-exchange.com",8080);
      std::cout << "Internet is available." << std::endl;
   } catch (...) {
      std::cout << "Internet is not available." << std::endl;
   }
   sock.Close();
}
Avatar of jkr
The most efficiant way is just calling 'InternetGetConnectedState()' (http://msdn2.microsoft.com/en-us/library/aa384702.aspx). See also http://support.microsoft.com/kb/242558 ("How To Detecting If You Have a Connection to the Internet"). Sockets can fail for a lot of reasons (wrong port, remote host down, no route to host).

The scoop is to
#include <Wininet.h>
#pragma comment(lib,"wininet.lib")
 
if (InternetGetConnectedState(INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_MODEM) == FALSE)
{
    // Don't attempt connection or it will bring up the dialog
}

Open in new window

That's a much better answer than the one I gave.  Thank you, jkr.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Since you are asking new questions again: Is there anything here that needs clarification?
Avatar of UdiRaz
UdiRaz

ASKER

To jkr :

1. Your answer, as usuall, is perfectly good, I didn't get the time to click the green button. I'll do it in a sec.

2. Why do you say that? What question I am asking again?