Наверное самый простой способ пропинговать сервер это так
| Код | BOOL myIsInternetConnected(void) { BOOL bResult=InternetCheckConnection("www.microsoft.com",0,0); if (!bResult && ERROR_NOT_CONNECTED==GetLastError()) return FALSE; // not connected return TRUE; }
|
С использование connect привожу код навскидку Без проверки на ошибки. Не уверен насчет тайм-аута для select - оставить 0 или поставить 5...10 sec? Также не помню точно нужно ли вводить сокет в блокирующий режим перед close. Можно упростить код используя блокирующие сокеты или вместо select использовать WSAEventSelect notifications. Ну еще здесь используется gethostbyname которая не работает с IP v6 адресами, а в остальном все вроде нормально
| Код | BOOL myIsInternetConnected(void) {
BOOL bResult=FALSE; int rc, i, n; LPHOSTENT lpHost = NULL; // Points to the HOSTENT structure struct sockaddr_in dst; SOCKET s[7]; // custom struct timeval tv = {0,0}; // for select fd_set fdset; // fd_set descriptor unsigned long on = 1; // a place where 0x00000001 can be taken from unsigned long off = 0; // a place where 0x00000000 can be taken from DWORD timeout=10000; // timeout --option
char hostname[]={"www.microsoft.com"};
if (NULL==(lpHost = gethostbyname (hostname))) return FALSE;
else // получить адреса хостов для всех возможных зеркал домена microsoft.com { n=0; for(int i=0; lpHost->h_addr_list[i] != NULL ;i++) { memset(&dst,0,sizeof(dst)); // zeroizying dst structure dst.sin_port = htons(80); dst.sin_family = AF_INET; memcpy(&(dst.sin_addr), lpHost->h_addr_list[i], lpHost->h_length);
s[i] = socket(AF_INET,SOCK_STREAM,0); // allocating a socket ioctlsocket(s[i],FIONBIO,&on); // set nonblocking mode
rc = connect(s[i], (struct sockaddr*)&dst, sizeof(dst)); // connecting n++; if (n==7) break; // overflow }
FD_ZERO(&fdset); // zeroizyng fdset for(i=0; i<n; i++) { FD_SET(s[i], &fdset); // and setting them into fdset } rc = select(FD_SETSIZE, NULL, &fdset, NULL, &tv); // select()ing sockets that are ready to force a write
for(i=0; i<n; i++) { if(FD_ISSET(s[i],&fdset)) { // picking sockets that are set bResult=TRUE; // yes! they are connected! } }
for(i=0; i<n; i++) { ioctlsocket(s[i], FIONBIO, &off); // set blocking mode again closesocket(s[i]); } // close socket
return bResult; }
| |