How can I programmatically check whether my machine has internet access or not using C/C++, is it just a matter of pinging an IP? How does NIC do it ? I mean something like:
I am using Windows 7.
How can I programmatically check whether my machine has internet access or not using C/C++, is it just a matter of pinging an IP? How does NIC do it ? I mean something like:
I am using Windows 7.
The following code will work, if you're on windows:
There is actually a very smart way including code snip here.
It basically using the cmd option: While in CMD hit:
route print
.This will map routing table with an array and will look for 0.0.0.0 as an available internet connection.
I used it with a
while(true){//the code in here } //check for inet connection , else will sleep for 10 mins and check again
If you work on Windows, just try this
In addition to the InternetCheckConnection() function, The Win32 API has a function ( InternetGetConnectedState() ) which returns a true/false for (the availability of) some form of internet connectivity:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa384702(v=vs.85).aspx
It also tells you what type of connection to the internet you have(LAN, modem, Proxy etc) - which can often be very handy to know.
There is nothing of that sort I think, but you can try this:
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
, andWSAGetLastError
will usually returnWSAEHOSTUNREACH
(meaning the packet couldn't be sent to the host).In Linux, you'll get back a
-1
, and errno will beENETUNREACH
. Some useful links:1. Link for Windows Sockets
2. Link for Linux/Unix sockets