[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 353
  • Last Modified:

Detecting internet connection fails


I use InternetGetConnectedState() to detect internet connection, but it always returns false. I connected to the Internet via LAN. Does anybody know why?
  • 2
  • 2
2 Solutions
Hi ubiwebdev,

maybe the cause for this is a RAS connection entry in InternetExplorer's connection settings ... I made a little
test app in which InternetGetConnectedState() returns TRUE until I add a default RAS connection with option
'connect always' ... in this case it returns FALSE even if I'm connected via LAN
(see http://support.microsoft.com/default.aspx?scid=kb;en-us;242558 )

Or, if you have Windows ME maybe you should read http://support.microsoft.com/default.aspx?scid=kb;en-us;315035

IMO if this returns FALSE you can only try to check if there's a active network card in the PC allthough this
is not an indication that the PC is connected to the internet.

With Microsoft Platform SDK there is a possiblity to check for active network cards with the functions GetNumberOfInterfaces
and GetIfEntry (check MSDN about this if you're interested) ...

hope that helps,

I use the following class to check for internet connectivity:
(Note two files, Ping.cpp and Ping.h)

// Ping.cpp

#include "stdafx.h"
#include "Ping.h"

unsigned int CPing::Ping (LPCSTR pstrHost)
SOCKET rawSocket;
int nRet;
unsigned int nResult = 0;
struct sockaddr_in saDest;
struct sockaddr_in saSrc;
DWORD dwTimeSent;
DWORD dwElapsed;
u_char cTTL;

      // Create a Raw socket
      rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
      if (rawSocket == SOCKET_ERROR)
            return 1;

      // Lookup host
      lpHost = gethostbyname(pstrHost);
      if (lpHost == NULL) // Host not found
            return 1;

      // Setup destination socket address
      saDest.sin_addr.s_addr = *((u_long FAR *) (lpHost->h_addr) );
      saDest.sin_family = AF_INET;
      saDest.sin_port = 0;

      // Send ICMP echo request
      SendEchoRequest(rawSocket, &saDest);

      nRet = WaitForEchoReply(rawSocket);

      if (nRet == SOCKET_ERROR)
            nResult = 1;
      else if (!nRet) // Timeout
            nResult = 1;
      else // Ping successful
            dwTimeSent = RecvEchoReply(rawSocket, &saSrc, &cTTL); // Receive reply
            dwElapsed = GetTickCount() - dwTimeSent; // Calculate elapsed time

      nRet = closesocket(rawSocket);
      if (nRet == SOCKET_ERROR)
            nResult = 1;

      return nResult;

int CPing::SendEchoRequest (SOCKET s,LPSOCKADDR_IN lpstToAddr)
      static ECHOREQUEST echoReq;
      static nId = 1;
      static nSeq = 1;
      int nRet;

      // Fill in echo request
      echoReq.icmpHdr.Type            = ICMP_ECHOREQ;
      echoReq.icmpHdr.Code            = 0;
      echoReq.icmpHdr.Checksum      = 0;
      echoReq.icmpHdr.ID                  = nId++;
      echoReq.icmpHdr.Seq                  = nSeq++;

      // Fill in some data to send
      for (nRet = 0; nRet < REQ_DATASIZE; nRet++)
            echoReq.cData[nRet] = ' '+nRet;

      // Save tick count when sent
      echoReq.dwTime                        = GetTickCount();

      // Put data in packet and compute checksum
      echoReq.icmpHdr.Checksum = in_cksum((u_short *)&echoReq, sizeof(ECHOREQUEST) );

      // Send the echo request
      nRet = sendto(s,                                    // Socket
                         (LPSTR)&echoReq,                  // Buffer
                         0,                                          // Flags
                         (LPSOCKADDR)lpstToAddr,    // Destination
                         sizeof(SOCKADDR_IN) );     // Address length

      return (nRet);

DWORD CPing::RecvEchoReply (SOCKET s, LPSOCKADDR_IN lpsaFrom, u_char *pTTL)
      ECHOREPLY echoReply;
      int nRet;
      int nAddrLen = sizeof(struct sockaddr_in);

      // Receive the echo reply
      nRet = recvfrom(s,                                  // Socket
                              (LPSTR)&echoReply,          // Buffer
                              sizeof(ECHOREPLY),          // Size of buffer
                              0,                                  // Flags
                              (LPSOCKADDR)lpsaFrom,      // From address
                              &nAddrLen);                      // Pointer to address len

      // Return time sent and IP TTL
      *pTTL = echoReply.ipHdr.TTL;


int CPing::WaitForEchoReply (SOCKET s)
      struct timeval Timeout;
      fd_set readfds;

      readfds.fd_count = 1;
      readfds.fd_array[0] = s;
      Timeout.tv_sec = 1;
    Timeout.tv_usec = 0;

      return(select(1, &readfds, NULL, NULL, &Timeout) );

u_short CPing::in_cksum (u_short *addr, int len)
      register int nleft = len;
      register u_short *w = addr;
      register u_short answer;
      register int sum = 0;

      // Our algorithm is simple, using a 32 bit accumulator (sum),
      // we add sequential 16 bit words to it, and at the end, fold
      // back all the carry bits from the top 16 bits into the lower
      // 16 bits.

      while( nleft > 1 )
            sum += *w++;
            nleft -= 2;

      // Mop up an odd byte, if necessary
      if ( nleft == 1 )
            u_short      u = 0;

            *(u_char *)(&u) = *(u_char *)w ;
            sum += u;

      // Add back carry outs from top 16 bits to low 16 bits
      sum = (sum >> 16) + (sum & 0xffff);      // Add hi 16 to low 16
      sum += (sum >> 16); // Add carry
      answer = ~sum; // Truncate to 16 bits
      return (answer);


// Ping.h

#pragma pack(1)

#define ICMP_ECHOREPLY      0
#define ICMP_ECHOREQ      8

class CPing
      HWND m_hWnd;
      unsigned int Ping(LPCSTR pstrHost);
      int  WaitForEchoReply(SOCKET s);
      // ICMP Echo Request/Reply functions
      int            SendEchoRequest(SOCKET, LPSOCKADDR_IN);
      DWORD      RecvEchoReply(SOCKET, LPSOCKADDR_IN, u_char *);
      u_short in_cksum(u_short *addr, int len);

// IP Header -- RFC 791
typedef struct tagIPHDR
      u_char  VIHL;                  // Version and IHL
      u_char      TOS;                  // Type Of Service
      short      TotLen;                  // Total Length
      short      ID;                        // Identification
      short      FlagOff;            // Flags and Fragment Offset
      u_char      TTL;                  // Time To Live
      u_char      Protocol;            // Protocol
      u_short      Checksum;            // Checksum
      struct      in_addr iaSrc;      // Internet Address - Source
      struct      in_addr iaDst;      // Internet Address - Destination

// ICMP Header - RFC 792
typedef struct tagICMPHDR
      u_char      Type;                  // Type
      u_char      Code;                  // Code
      u_short      Checksum;            // Checksum
      u_short      ID;                        // Identification
      u_short      Seq;                  // Sequence
      char      Data;                  // Data

#define REQ_DATASIZE 32            // Echo Request Data size

// ICMP Echo Request
typedef struct tagECHOREQUEST
      ICMPHDR icmpHdr;
      DWORD      dwTime;
      char      cData[REQ_DATASIZE];

// ICMP Echo Reply
typedef struct tagECHOREPLY
      IPHDR      ipHdr;
      ECHOREQUEST      echoRequest;
      char    cFiller[256];

#pragma pack()


You can then check for internet connectivity as follows:

CPing m_ping;
CString PingHost1 = ""; // some external IP address

if (m_ping.Ping(PingHost1)
      return FALSE; // no internet connection
      return TRUE; // internet connection present

Hope this helps
ubiwebdevAuthor Commented:

Thanks for your reply. However, I don't have RAS connection in my IE.
ubiwebdevAuthor Commented:
HI reidy_boy,

I want to avoid that the default dial up connection pop out if the computer is offline.

Thanks anyway.
hm ... strange ... I wrote about the only two reasons I found for which FALSE is returned allthough the PC is connected through LAN.

Maybe you should give the GetNumberOfInterfaces and GetIfEntry a try, but the problem still is that you can't in this case find
out whether a connection to the internet exists or not ... to find this out you only can test to establish a connection ...


Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now