使用API判斷網路是否連通 InternetGetConnectedState / IsNetworkAlive
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "test.h"
#include <Wininet.h>
#include <Sensapi.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
void Fun_InternetGetConnectedState()
{
//#define INTERNET_CONNECTION_MODEM 1
//#define INTERNET_CONNECTION_LAN 2
//#define INTERNET_CONNECTION_PROXY 4
//#define INTERNET_CONNECTION_MODEM_BUSY 8
DWORD flags;//上網方式
BOOL m_bOnline=TRUE;//是否線上
m_bOnline=InternetGetConnectedState(&flags,0);
if(m_bOnline)//線上
{
if ((flags & INTERNET_CONNECTION_MODEM) ==INTERNET_CONNECTION_MODEM)
{
cout<<"線上:撥號上網/n";
}
if ((flags & INTERNET_CONNECTION_LAN) ==INTERNET_CONNECTION_LAN)
{
cout<<"線上:通過區域網/n";
}
if ((flags & INTERNET_CONNECTION_PROXY) ==INTERNET_CONNECTION_PROXY)
{
cout<<"線上:代理/n";
}
if ((flags & INTERNET_CONNECTION_MODEM_BUSY) ==INTERNET_CONNECTION_MODEM_BUSY)
{
cout<<"MODEM被其他非INTERNET連線佔用/n";
}
}
else
cout<<"不線上/n";
}
void Fun_IsNetworkAlive()
{
DWORD flags;//上網方式
BOOL m_bOnline=TRUE;//是否線上
m_bOnline=IsNetworkAlive(&flags);
if(m_bOnline)//線上
{
if ((flags & NETWORK_ALIVE_LAN) ==NETWORK_ALIVE_LAN)
{
cout<<"線上:NETWORK_ALIVE_LAN/n";
}
if ((flags & NETWORK_ALIVE_WAN) ==NETWORK_ALIVE_WAN)
{
cout<<"線上:NETWORK_ALIVE_WAN/n";
}
if ((flags & NETWORK_ALIVE_AOL) ==NETWORK_ALIVE_AOL)
{
cout<<"線上:NETWORK_ALIVE_AOL/n";
}
}
else
cout<<"不線上/n";
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
// CString strHello;
// strHello.LoadString(IDS_HELLO);
// cout << (LPCTSTR)strHello << endl;
int i=0;
while (TRUE)
{
cout << "請選擇測試的方式:/n"
<< "1. InternetGetConnectedState/n"
<< "2. IsNetworkAlive"
<< endl;
cin >> i;
switch(i)
{
case 1:
Fun_InternetGetConnectedState();
break;
case 2:
Fun_IsNetworkAlive();
break;
default:
cout << "錯誤!/n";
}
cout << endl;
}
}
return nRetCode;
}
說明:
InternetGetConnectedState():對網路狀況不能及時反應
IsNetworkAlive():可以及時反應網路連通情況,但是需要服務System Event Notification支援(系統預設自動啟動該服務)。使用該函式,需要安裝最新的SDK(如.net的)
再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://www.cnblogs.com/captainbed