Programmatically check whether my machine has internet access or not

人盡茶涼 提交于 2019-12-18 05:44:31

问题


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.


回答1:


If you work on Windows, just try this

#include <iostream>
#include <windows.h> 
#include <wininet.h>
using namespace std;

int main(){

if(InternetCheckConnection(L"http://www.google.com",FLAG_ICC_FORCE_CONNECTION,0))
{
        cout << "connected to internet";
}

return 0;
}



回答2:


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, 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. Some useful links:

1. Link for Windows Sockets

2. Link for Linux/Unix sockets




回答3:


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.




回答4:


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




回答5:


The following code will work, if you're on windows:

#include <iostream>
#include <windows.h>

int main(){

  if (system("ping www.google.com")){
          std::cout<<"\nNot connnected to the internet\n\n";
  }
  else{
          std::cout<<"\nConnected to the internet\n\n";

  }
  system("pause");
  return 0;
}


来源:https://stackoverflow.com/questions/15778404/programmatically-check-whether-my-machine-has-internet-access-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!