Solved

is the computer connected to the internet?

Posted on 2003-10-22
9
261 Views
Last Modified: 2010-04-05
Hi, i would just like to know the complete code to check if the computer is connected to the internet through dial up or by all means? thanks..
0
Comment
Question by:orafans
9 Comments
 
LVL 6

Accepted Solution

by:
DaFox earned 43 total points
Comment Utility
Hi orafans,

there's no reliable way to get the internet connection status if you don't ping a server (think of routers, proxies or other internet connections over lan, for example).
The InternetCheckConnection() API is able to ping a specified server to determinve online status. You should take a look at it.
If you're not satisfied with the function, try this unit:

unit BaclOnlineDetection;

interface

function IsIpPresent : boolean;
function IsOnlineRas : boolean;

// Description:
//      Call IsIeUsingOnlineMode to determin the "Work offline/online" status
//      of Internet Explorer. This function is not a reliable way of determining
//      if a user is connected to the Internet. Use IsUserOnline to check if a
//      user is connected or not.
//      Note: IsIeUsingOnlineMode always returns FALSE if installed version of
//      Internet Explorer is less than 4.0.
// Return Value:
//      TRUE if Internet Explorer is working in "online" mode, FALSE
otherwise.
// Summary:
//      IsIeUsingOnlineMode determins if Internet Explorer is in online mode or
//      not.
function IsIeUsingOnlineMode : boolean;

function IsUserOnline : boolean;

implementation

uses
  Windows,
  WinSock;

//------------------------------------------------------------------------------

function IsIpPresent : boolean;
type
  TApInAddr = array [0..10] of PInAddr;
  PApInAddr = ^TApInAddr;
var
  Phe           : PHostEnt;
  Pptr          : PApInAddr;
  Buf           : array [0..63] of char;
  i             : Integer;
  GInitData     : TWsaData;
  Ip            : string;
begin
  Result := FALSE;
  WsaStartup ($101, GInitData);
  GetHostName (Buf, SizeOf(Buf));
  Phe := GetHostByName (Buf);
  if Phe = nil then
    Exit;
  Pptr := PApInAddr(Phe^.h_addr_list);
  i := 0;
  while Pptr^[i] <> nil do
  begin
    Ip := inet_ntoa(Pptr^[i]^);
    Inc(i);
  end;
  WsaCleanup;
  Result := (Ip <> '') and (Ip <> '127.0.0.1');
end;

//------------------------------------------------------------------------------

function IsOnlineRas : boolean;
const
  REG_RAS_BASE = 'System\CurrentControlSet\Services\RemoteAccess';
  REG_RAS_RC   = 'Remote Connection';
var
  OpenKey       : HKEY;
  DataType,
  DataSize,
  Buf           : DWORD;
begin
  Result := FALSE;
  if RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_RAS_BASE, REG_OPTION_NON_VOLATILE, KEY_READ, OpenKey) = ERROR_SUCCESS then
  begin
    DataType := REG_BINARY;
    DataSize := SizeOf(Buf);
    if RegQueryValueEx (OpenKey, REG_RAS_RC, nil, @DataType, @Buf, @DataSize) = ERROR_SUCCESS then       Result := (Buf = 1);
    RegCloseKey (OpenKey);
  end;
end;

//------------------------------------------------------------------------------

function IsIeUsingOnlineMode : boolean;
var
  InetIsOffline         : function (dwFlags : DWORD) : bool; stdcall;
  HLib                  : THandle;

  function GetBasicOsVer : integer;
  var
    VerInfo     : TOsVersionInfo;
  begin
    VerInfo.dwOSVersionInfoSize := SizeOf(TOsVersionInfo);
    if GetVersionEx (VerInfo) then
    begin
      case VerInfo.dwPlatformId of
        VER_PLATFORM_WIN32_WINDOWS : Result := 1;
        VER_PLATFORM_WIN32_NT : Result := 2;
        else
          Result := 0;
      end;
    end
    else
      Result := 0;
  end;

  //
  // Win9x stores the InetIsOffline API in SHELL32.DLL while NT stores it in
  // URL.DLL
  //
  function GetProperLibHandle : THandle;
  begin
    case GetBasicOsVer of
      1 : Result := LoadLibrary ('SHELL32.DLL');
      2 : Result := LoadLibrary ('URL.DLL');
      else
        Result := INVALID_HANDLE_VALUE;
    end;
  end;

begin
  Result := FALSE;
  HLib := GetProperLibHandle;
  if HLib <> INVALID_HANDLE_VALUE then
    try
      @InetIsOffline := GetProcAddress (HLib, 'InetIsOffline');
      if @InetIsOffline <> nil then
        Result := not (InetIsOffline (0));
    finally
      FreeLibrary (HLib);
    end;
end;

//------------------------------------------------------------------------------

function IsUserOnline : boolean;
begin
  Result := IsIpPresent or IsOnlineRas or IsIeUsingOnlineMode;
end;

//------------------------------------------------------------------------------


end.

Regards,
Markus
0
 

Assisted Solution

by:DTHLIEM
DTHLIEM earned 41 total points
Comment Utility
Hi orafans,
  Try this code:
********************************
interface  

uses  
  Windows, SysUtils, Registry, WinSock, WinInet;  

type  
  TConnectionType = (ctNone, ctProxy, ctDialup);  

function ConnectedToInternet: TConnectionType;  
function RasConnectionCount: Integer;  


implementation  

//For RasConnectionCount =======================  
const  
  cERROR_BUFFER_TOO_SMALL = 603;  
  cRAS_MaxEntryName       = 256;  
  cRAS_MaxDeviceName      = 128;  
  cRAS_MaxDeviceType      = 16;  
type  
  ERasError = class(Exception);  

  HRASConn = DWORD;  
  PRASConn = ^TRASConn;  
  TRASConn = record  
    dwSize: DWORD;  
    rasConn: HRASConn;  
    szEntryName: array[0..cRAS_MaxEntryName] of Char;  
    szDeviceType: array[0..cRAS_MaxDeviceType] of Char;  
    szDeviceName: array [0..cRAS_MaxDeviceName] of Char;  
  end;  

  TRasEnumConnections =  
    function(RASConn: PrasConn; { buffer to receive Connections data }  
    var BufSize: DWORD;    { size in bytes of buffer }  
    var Connections: DWORD { number of Connections written to buffer }  
    ): Longint;  
  stdcall;  
  //End RasConnectionCount =======================  


function ConnectedToInternet: TConnectionType;  
var  
  Reg:       TRegistry;  
  bUseProxy: Boolean;  
  UseProxy:  LongWord;  
begin  
  Result := ctNone;  
  Reg    := TRegistry.Create;  
  with REG do  
    try  
      try  
        RootKey := HKEY_CURRENT_USER;  
        if OpenKey('\Software\Microsoft\Windows\CurrentVersion\Internet settings', False) then  
        begin  
          //I just try to read it, and trap an exception  
          if GetDataType('ProxyEnable') = rdBinary then  
            ReadBinaryData('ProxyEnable', UseProxy, SizeOf(Longword))  
          else  
          begin  
            bUseProxy := ReadBool('ProxyEnable');  
            if bUseProxy then  
              UseProxy := 1  
            else  
              UseProxy := 0;  
          end;  
          if (UseProxy <> 0) and (ReadString('ProxyServer') <> '') then  
            Result := ctProxy;  
        end;  
      except  
        //Obviously not connected through a proxy  
      end;  
    finally  
      Free;  
    end;  

  //We can check RasConnectionCount even if dialup networking is not installed  
  //simply because it will return 0 if the DLL is not found.  
  if Result = ctNone then  
  begin  
    if RasConnectionCount > 0 then Result := ctDialup;  
  end;  
end;  

function RasConnectionCount: Integer;  
var  
  RasDLL:    HInst;  
  Conns:     array[1..4] of TRasConn;  
  RasEnums:  TRasEnumConnections;  
  BufSize:   DWORD;  
  NumConns:  DWORD;  
  RasResult: Longint;  
begin  
  Result := 0;  

  //Load the RAS DLL  
  RasDLL := LoadLibrary('rasapi32.dll');  
  if RasDLL = 0 then Exit;  

  try  
    RasEnums := GetProcAddress(RasDLL, 'RasEnumConnectionsA');  
    if @RasEnums = nil then  
      raise ERasError.Create('RasEnumConnectionsA not found in rasapi32.dll');  

    Conns[1].dwSize := SizeOf(Conns[1]);  
    BufSize         := SizeOf(Conns);  

    RasResult := RasEnums(@Conns, BufSize, NumConns);  

    if (RasResult = 0) or (Result = cERROR_BUFFER_TOO_SMALL) then Result := NumConns;  
  finally  
    FreeLibrary(RasDLL);  
  end;  
end;  

*****************************

:)
0
 
LVL 3

Assisted Solution

by:ThoseBug
ThoseBug earned 41 total points
Comment Utility
to know the type of conecction

procedure TForm1.Button1Click(Sender: TObject);
 
  function GetConexion:boolean;
  var
    flags: dword;
  begin
     Result := InternetGetConnectedState(@flags, 0);
    if Result then begin
     showmessage('Conexion On');
     if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then
        showmessage('Conexion by modem');
     if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then
        showmessage('Conexion by lan');
     if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then
        showmessage('Conexion by proxy');
     if (flags and INTERNET_CONNECTION_MODEM_BUSY) =INTERNET_CONNECTION_MODEM_BUSY then
        showmessage('modem busy');
    end;
  end;
begin
  GetConexion;
end;
 
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 3

Expert Comment

by:ThoseBug
Comment Utility
and this ti know if is conected

procedure TForm1.Button1Click(Sender: TObject);
 
  function FuncAvail(_dllname, _funcname: string; var _p: pointer): boolean;
 
  var _lib: tHandle;
  begin
    Result := false;
    if LoadLibrary(PChar(_dllname)) = 0 then exit;
    _lib := GetModuleHandle(PChar(_dllname));
    if _lib <> 0 then
      begin
        _p := GetProcAddress(_lib, PChar(_funcname));
        if _p <> nil then Result := true;
      end;
  end;
 
var
  InetIsOffline : function(dwFlags: DWORD): BOOL; stdcall;
 
begin
  if FuncAvail('URL.DLL', 'InetIsOffline', @InetIsOffline) = true then
    if InetIsOffLine(0) = true
      then ShowMessage('Offline')
        else ShowMessage('Online');
end;
 
0
 
LVL 3

Expert Comment

by:ThoseBug
Comment Utility
you must be add in the uses WinInet
0
 
LVL 6

Expert Comment

by:DaFox
Comment Utility
@ThoseBug: See my first posting above. I already mentioned that function (including an example). The problem with this function is that it only returns a boolean if Internet Explorer (!!!) is in online mode. So this function won't return a reliable internet connection status in most cases!

Markus
0
 

Author Comment

by:orafans
Comment Utility
Okey,
         i will rephrase my question.  actually i have a delphi program mapi
         but the problem with this one is that everytime i run the program and
         the computer is already connected to the internet it will disconnect    
         and prompt for a dialup connection.. all i want is that if it is
         connected to the internet it will just automatically connect..  
 
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

762 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

10 Experts available now in Live!

Get 1:1 Help Now