Solved

Detecting internet connection fails

Posted on 2004-09-08
6
340 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
6 Comments
 
LVL 31

Accepted Solution

by:
Zoppo earned 50 total points
ID: 12013524
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
ID: 12014752
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
ID: 12015402
Hi ZOPPO,

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

Author Comment

by:ubiwebdev
ID: 12015415
HI reidy_boy,

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


Thanks anyway.
0
 
LVL 31

Expert Comment

by:Zoppo
ID: 12024202
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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.
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

705 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