思路:
1.首先查看當前網卡狀態,如果網卡狀態為down,沒有必要進行下面的測試,直接判定為沒有與外網串連bool checkNetStatus()
2.若網卡狀態為up,再檢測是否能訪問某個網址int checkNET(char* url,char * keystr)
查看當前網卡狀態,如果網卡狀態為down,沒有必要進行下面的測試,直接判定為沒有與外網串連
bool checkNetStatus()
bool checkNetStatus()<br />{<br />bool netStatus = true;//預設狀態為已連網<br />PMIB_IFTABLE ifTable;<br />DWORD dwSize = 0;<br />DWORD dwRetVal = 0;<br />MIB_IFROW IfRow;<br />// Allocate memory for our pointers.<br />ifTable = (MIB_IFTABLE*) malloc(sizeof(MIB_IFTABLE));<br />//試探擷取,擷取足夠大的空間<br />if (GetIfTable(ifTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {<br />//釋放ifTable前邊申請的空間,未處理<br />ifTable = (MIB_IFTABLE *) malloc (dwSize);<br />}<br />//真正擷取<br />if ((dwRetVal = GetIfTable(ifTable, &dwSize, 0)) == NO_ERROR)<br />{<br />for (int i = 0; i < (int)ifTable->dwNumEntries; i++)<br />{<br />IfRow = ifTable->table[i];<br />char* ptr = (char*)(IfRow.bDescr);<br />wToLower(ptr);<br />if(strstr(ptr, "usb") || strstr(ptr, "loopback"))<br />continue;<br />dwRetVal = GetIfEntry(&IfRow);<br />if(IfRow.dwAdminStatus == MIB_IF_ADMIN_STATUS_DOWN)<br />netStatus = false;<br />else<br />netStatus = true;<br />}<br />}<br />else<br />{<br />const char * notice11 = "GetIfTable failed.!";<br />log(notice11, strlen(notice11));<br />}<br />free(ifTable);<br />return netStatus;<br />}<br />
查看能否訪問某個網址
#include <Pm.h><br />#include <iphlpapi.h><br />#pragma comment(lib, "iphlpapi.lib")<br />#define MAXSIZE 4096<br />#pragma comment(lib, "Wininet.lib")<br />int checkNET(char* url,char * keystr)<br />{<br />int flag = 0;<br />HINTERNET hSession = InternetOpen(_T("UrlTest"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);<br /> if(hSession != NULL)<br /> {<br />wchar_t * wurl = short2wide(url);<br /> HINTERNET hHttp = InternetOpenUrl(hSession, wurl, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);<br /> if (hHttp != NULL)<br /> {<br /> char Temp[MAXSIZE];<br /> ULONG Number = 1;<br /> while (Number > 0)<br /> {<br />memset(Temp, 0, MAXSIZE);<br />InternetReadFile(hHttp, Temp, MAXSIZE - 1, &Number);<br />if(strstr(Temp, keystr) != 0)<br />{<br />flag = 1;<br />continue;<br />}<br />}<br />InternetCloseHandle(hHttp);<br />hHttp = NULL;<br />}<br />InternetCloseHandle(hSession);<br />hSession = NULL;<br />}<br />return flag;<br />}