Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if you have live internet connection programmatically using C++

Tags:

c++

connection

How can I check if I have a internet connection or live internet connection using C++?

like image 790
Vibz Avatar asked Aug 31 '10 17:08

Vibz


2 Answers

C++ has no builtin functions for this, you will need to resort to system APIs. An easiest and obvious way is to create a socket and try to connect it to some known IP or check if DNS is working.

Some useful links:
http://msdn.microsoft.com/en-us/library/ms740673(VS.85).aspx (Windows Sockets)
http://www.tenouk.com/cnlinuxsockettutorials.html (Linux/Unix sockets)

like image 160
Karel Petranek Avatar answered Sep 19 '22 15:09

Karel Petranek


The easiest way is to try to connect to a known outside IP address. If it fails in Windows, the connect function will return SOCKET_ERROR, and WSAGetLastError will usually return WSAEHOSTUNREACH (meaning the packet couldn't be sent to the host). In Linux, you'll get back a -1, and errno will be ENETUNREACH.

like image 20
cHao Avatar answered Sep 20 '22 15:09

cHao