Programmatically check whether my machine has inte

2019-01-26 06:00发布

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:

enter image description here

I am using Windows 7.

5条回答
ゆ 、 Hurt°
2楼-- · 2019-01-26 06:13

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;
}
查看更多
三岁会撩人
3楼-- · 2019-01-26 06:17

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

查看更多
成全新的幸福
4楼-- · 2019-01-26 06:27

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;
}
查看更多
闹够了就滚
5楼-- · 2019-01-26 06:32

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.

查看更多
【Aperson】
6楼-- · 2019-01-26 06:34

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

查看更多
登录 后发表回答