Solved

Detecting internet connection fails

Posted on 2004-09-08
6
325 Views
Last Modified: 2013-11-20
Hi,

I use InternetGetConnectedState() to detect internet connection, but it always returns false. I connected to the Internet via LAN. Does anybody know why?
0
Comment
Question by:ubiwebdev
  • 2
  • 2
6 Comments
 
LVL 30

Accepted Solution

by:
Zoppo earned 50 total points
Comment Utility
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,

ZOPPO
0
 
LVL 1

Assisted Solution

by:reidy_boy
reidy_boy earned 75 total points
Comment Utility
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;
LPHOSTENT lpHost;
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
                         sizeof(ECHOREQUEST),
                         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;

      return(echoReply.echoRequest.dwTime);
}

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
{
public:
      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
}IPHDR, *PIPHDR;

// 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
}ICMPHDR, *PICMPHDR;

#define REQ_DATASIZE 32            // Echo Request Data size

// ICMP Echo Request
typedef struct tagECHOREQUEST
{
      ICMPHDR icmpHdr;
      DWORD      dwTime;
      char      cData[REQ_DATASIZE];
}ECHOREQUEST, *PECHOREQUEST;

// ICMP Echo Reply
typedef struct tagECHOREPLY
{
      IPHDR      ipHdr;
      ECHOREQUEST      echoRequest;
      char    cFiller[256];
}ECHOREPLY, *PECHOREPLY;

#pragma pack()

/******************************/

You can then check for internet connectivity as follows:

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

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

Hope this helps
0
 

Author Comment

by:ubiwebdev
Comment Utility
Hi ZOPPO,

Thanks for your reply. However, I don't have RAS connection in my IE.
0
 

Author Comment

by:ubiwebdev
Comment Utility
HI reidy_boy,

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


Thanks anyway.
0
 
LVL 30

Expert Comment

by:Zoppo
Comment Utility
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 ...

ZOPPO
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Introduction: Dynamic window placements and drawing on a form, simple usage of windows registry as a storage place for information. Continuing from the first article about sudoku.  There we have designed the application and put a lot of user int…
If you use Adobe Reader X it is possible you can't open OLE PDF documents in the standard. The reason is the 'save box mode' in adobe reader X. Many people think the protected Mode of adobe reader x is only to stop the write access. But this fe…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now