Bonjour,
Voila la fonction que j'utilise pour savoir si je suis connecté à Internet. Elle réalise un ping sur un site dont on passe l'adresse en paramètre : "microsoft.com" ou "192.168.0.2".
Le PC étant connecté via un modem/routeur, les méthodes classiques ne marchent pas; elles répondent toujours oui, ce qui est vrai puisque le PC est toujours connecté ... au modem/routeur ! Avec le ping on est sûr d'être réellement connecté à Internet.
bool IsWebConnected
(
const char* pszWebSite // I:website to ping
) // O:Web connected
{
// --- Quit if incorrect website to ping
if (pszWebSite == NULL) return false; // no string
if (*pszWebSite == 0) return false; // empty string
// --- Initialise the use of "Ws2_32.dll"
WSADATA WSAData;
if (WSAStartup(MAKEWORD(2,2),&WSAData) != 0) return false;
// --- Create a socket that is bound to a specific service provider
SOCKET Socket = socket(AF_INET,SOCK_STREAM,0);
if (Socket == INVALID_SOCKET)
{
WSACleanup();
return false;
}
// --- Retrieve the host information
// --- corresponding to a host name from a host database
bool bRet = false;
HOSTENT* Host = gethostbyname(pszWebSite);
if (Host)
{
SOCKADDR_IN SocketIn;
SocketIn.sin_family = AF_INET;
SocketIn.sin_port = htons(80); // HTTP port
SocketIn.sin_addr.S_un.S_addr = (DWORD)*((DWORD*)Host->h_addr_list[0]);
if (connect(Socket,(SOCKADDR*)&SocketIn,sizeof(SOCKADDR_IN)) == 0) bRet = true;
}
// --- Release the resources
closesocket(Socket);
WSACleanup();
return bRet;
}
Jean-François